[Solved]-Django Redirect to previous view

13๐Ÿ‘

โœ…

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)}
๐Ÿ‘คTimmy O'Mahony

2๐Ÿ‘

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).

๐Ÿ‘คMr. Napik

-3๐Ÿ‘

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.

๐Ÿ‘คMarcin

Leave a comment