Django Redirect to previous view

后端 未结 3 680
星月不相逢
星月不相逢 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:41

    Store information about the pages your user has been visiting, so you can retrieve it later. Probably the best place to do that is in the session.

    0 讨论(0)
  • 2020-12-30 08:45

    Django request knows what the page the user came from is:

    previous_page = request.META['HTTP_REFERER']
    

    It will contain something like:

    >>> print(previous_page)
    'http://www.myserver.com/myApp/z'
    

    Hence you know where you came from (warning, treat it as unsafe data and verify it thoroughly, it might even contain malicious data) and use the information.

    First you pass it to template as

    data = {
        ...,
        # also indicate, that saved data are valid and user can leave
        'previous_page': previous_page,
    }
    

    Render the page z.html

    return render(request, 'myApp/z.html', data)
    

    And in the template of the page z, you add the meta-refresh tag to the . It will cause that once the form is saved and page loaded, user will be redirected redirected back automatically:

    {% if form_is_saved and previous_page %}<meta http-equiv="refresh" content="0; url={{ previous_page }}" />{% endif %}
    

    This has the advantage, that form is saved by the page z.html, where it is filled and you do not need to handle it by pages x and y (this is the only way to do it if pages x and y are outside of your Django app).

    0 讨论(0)
  • 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:

    <a href="/page_z/?from={{ request.path|urlencode }}" />go to form</a>
    

    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:

    <form action="{% if from %}?next={{ from }}{% endif %}" />
    ...
    

    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)}
    
    0 讨论(0)
提交回复
热议问题