Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Redirect to previous view

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 one I was on initially).

Normally, you use "redirect" in the view, and specify the page you want to redirect to. But what would you do in a case like this?

Any ideas?

Thanks!

like image 615
JohnnyCash Avatar asked Feb 19 '12 16:02

JohnnyCash


People also ask

How do I go to previous page in Django?

M Yes, of course, you just have to pass next={{ request. path|urlencode }} query parameter to the URL of your products page. Then you make your back button with href="{{ request.

What is reverse redirect in Django?

the reverse function allows to retrieve url details from url's.py file through the name value provided there. This is the major use of reverse function in Django. Syntax: Web development, programming languages, Software testing & others. from django.urls import reverse.

What is HttpResponseRedirect in Django?

HttpResponseRedirect takes a single argument: the URL to which the user will be redirected (see the following point for how we construct the URL in this case). As the Python comment above points out, you should always return an HttpResponseRedirect after successfully dealing with POST data.

What is absolute URL in Django?

Django absolute provide 2 template tags: absolute: acts like url but provide a full URL based on incoming request.


1 Answers

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)}
like image 168
Timmy O'Mahony Avatar answered Oct 06 '22 00:10

Timmy O'Mahony