[Django]-Django: How to return to previous URL

4πŸ‘

βœ…

If you want next to be included in the query string, then move it outside of the url tag:

<a href="{% url 'main:buy_punchcard' member.id %}?next={{ request.path }}">Buy punchcard</p>

In your view, you can fetch next from request.GET, and return the redirect response using either HttpResponseRedirect or the redirect shortcut.

from django.utils.http import is_safe_url

next = request.GET.get('next', '/default/url/')
# check that next is safe
if not is_safe_url(next):
    next = '/default/url/'
return redirect(next)

Note that it might not be safe to redirect to a url fetched from the query string. For example, it could link to a different domain. Django has a method is_safe_url that it uses to check next urls when logging in or out.

πŸ‘€Alasdair

1πŸ‘

You don’t need {{ }} there, just:

<a href="{% url 'main:buy_punchcard' member.id next=request.path %}">Buy punchcard</p>
πŸ‘€Gocht

Leave a comment