How to redirect to pagination page in Django?

I have
view:

def questions(request,id):
   if request.method=='GET':
        if question.objects.findId(id) == None:
            raise Http404 
        ans=answer.objects.sortByTop(id)
        return render(request, 'question_page.html',{'page_obj':paginate(ans,request,2),
                                                'answers':ans,
                                                'que':question.objects.findId(id)}
                                                )
   
   if request.method == 'POST':
        form = AnswerForm(data=request.POST)
        print(form.data)
        que = question.objects.findId(id)
        print(que)
        print(que.title)
        ans = answer(
            txt=form.data['anstxt'],
            authorId=Profile.objects.get(profile=request.user),
            questionId=que,
            id=answer.objects.getLastId()+1
        )
        ans.save()
        a=answer.objects.sortByTop(id)
        i=0
        for c in a:
            if c==ans:
                break
            i=i+1

        return redirect('questions', id=que.id)#how to redirect???

When user has asked question django must redirect him to page with answer. I use standart pagination object to implement pagination so pages are in GET parametes(?page=…)
urls:

urlpatterns = [
    path('',listing, name='main'),
    path('login/', Login, name='login'),
    path('signup/',registration,name='signup'),
    path('hot/',hot,name='hots'),
    path('ask/',ask,name='ask'),
    path('question/<int:id>/', questions, name='questions'),
    path('tag/<slug:tg>/',tag_search,name='tag'),
    path('logout/',logout,name='logout'),
    path('edit/',settings,name='edit')
    
]

question has dynamic url.
How can I redirect user to page of answers after submitting?

form template:

<div class="yourans"><form class="ansfrom" method="POST" action="{%url 'questions' id=que.id%}?page={{page_obj.number}}">
            {%csrf_token%}
            <div class="allf"><textarea name="anstxt"  class="atxt" placeholder="answer" required maxlength="1000"></textarea></div>
           <div class="ansbut"> <input type="submit" value="Answer" class="goans"></div>
        
    </form></div> 

I tried this:

path('question/<int:id>/(?P<page>\d+)/$', questions, name='questions'),

But it’s not good.

And this:

return redirect('questions', id=que.id,page=int(i/2)+i%2)

But it doesn’t work

>Solution :

I think you want to pass a GET parameter to the request (?page=...). It’s not possible directly with redirect, but as you can pass an absolute URL to redirect, you can generate the url for the question, and then add the GET parameter:

return redirect(f"{reverse('questions', kwargs={"id":que.id})}?page={int(i/2)+i%2}")

If you want other methods to generate the url with GET parameters you can check this question: How do i pass GET parameters using django urlresolvers reverse

Leave a Reply