Django Redirect to previous view

后端 未结 3 697
星月不相逢
星月不相逢 2020-12-30 07:58

I have a button on page x and page y that redirects to page z. On page z, I have a form that needs filling out. Upon saving, I want to redirect to page x or y (whichever on

3条回答
  •  执念已碎
    2020-12-30 08:49

    You can use GET parameters to track from which page you arrived to page z. So when you are arriving normally to page z we remember from which page we came. When you are processing the form on page z, we use that previously saved information to redirect. So:

    The button/link on page y should include a parameter whose value is the current URL:

    go to form
    

    Then in page_z's view you can pass this onto the template:

    def page_z_view(self, request):
        ...
        return render_to_response('mytemplate.html', { 'from' : request.GET.get('from', None) })
    

    and in your form template:

    ...

    So now the form - when submitted - will pass on a next parameter that indicates where to return to once the form is successfully submitted. We need to revist the view to perform this:

    def page_z_view(self, request):
        ...
        if request.method == 'POST':
            # Do all the form stuff
            next = request.GET.get('next', None)
            if next:
                return redirect(next)
        return render_to_response('mytemplate.html', { 'from' : request.GET.get('from', None)}
    

提交回复
热议问题