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!
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.
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.
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.
Django absolute provide 2 template tags: absolute: acts like url but provide a full URL based on incoming request.
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)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With