I face a problem which I can't find a solution for. I have a button in navbar which is available on all pages and it is a button responsible for creating some content.
View that links with button:
def createadv(request): uw = getuw(request.user.username) if request.method =='POST': form = AdverForm(request.POST, request.FILES) if form.is_valid(): form.instance.user = request.user form.save() return HttpResponseRedirect('/', {'username': request.user.username, 'uw': uw}) args = {} args.update(csrf(request)) args['username'] = request.user.username args['form'] = AdverForm() args['uw'] = uw return render_to_response('createadv.html', args)
If you can see now I always redirect to main page '/' after creating content but I want to go back to the page with which I launched the creation of content.
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. GET.
You can do that by using request. META['HTTP_REFERER'] , but it will exist if only your tab previous page was from your website, else there will be no HTTP_REFERER in META dict . So be careful and make sure that you are using . get() notation instead.
It is called reverse because it is a reverse process of determining which view should be called for a given URL (which process is called resolving). Redirects are not specific to Django or any other web frameworks. Redirect means that for a given URL (or action), the user should be instructed to visit a specific URL.
The render function Combines a given template with a given context dictionary and returns an HttpResponse object with that rendered text. You request a page and the render function returns it. The redirect function sends another request to the given url.
You can add a next
field to your form, and set it to request.path
. After you processed your form you can redirect to the value of this path.
template.html
<form method="POST"> {% csrf_token %} {{ form }} <input type="hidden" name="next" value="{{ request.path }}"> <button type="submit">Let's Go</button> </form>
views.py
next = request.POST.get('next', '/') return HttpResponseRedirect(next)
This is roughly what django.contrib.auth
does for the login form if I remember well.
If you pass through an intermediate page, you can pass the 'next' value via the querystring:
some_page.html
<a href="{% url 'your_form_view' %}?next={{ request.path|urlencode }}">Go to my form!</a>
template.html
<form method="POST"> {% csrf_token %} {{ form }} <input type="hidden" name="next" value="{{ request.GET.next }}"> <button type="submit">Let's Go</button> </form>
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