Django Redirect to previous view

后端 未结 3 679
星月不相逢
星月不相逢 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: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 %}{% 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).

提交回复
热议问题