How to redirect to previous page in Django after POST request

When you are starting to use buttons in your projects in django, which are responsible for some contents and you wish to be redirected to some new page after the content is viewed.

The article below will in detail discuss the question “How to redirect to previous page in Django after POST request” and will help you understand the how to render HTML tags on a much deeper level.

How to redirect to previous page in Django after POST request?

To redirect to previous page in Django, add next field with the value ‘request.path’ to your form. Once your form has been processed, you can reroute to the value of this path.

You can do so by following the below mentioned example template.html:

<form method="POST">
    {% csrf_token %}
    {{ form }}
    <input type="hidden" name="next" value="{{ request.path }}">
    <button type="submit">Let's Go</button>
</form>

An example of your views.html would be:

next = request.POST.get('next', '/')
return HttpResponseRedirect(next)

The login form’s functionality is roughly handled by django.contrib.auth.

You can pass the “next” value across an intermediary page using the query string for some example HTML page:

<a href="{% url 'your_form_view' %}?next={{ request.path|urlencode }}">This is a form</a>

Your template.html should look like:

<form method="POST">
    {% csrf_token %}
    {{ form }}
    <input type="hidden" name="next" value="{{ request.GET.next }}">
    <button type="submit">Let's Go</button>
</form>

An alternative method to do so is to use the HTTP_REFERER value. 

However, if you prevent transmitting referrer information, this won’t function.

In other words, if the user operates their browser in private or incognito mode. Given below is an example of how you could implement this:

return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))

Conclusion

To redirect to previous page in Django after POST request you can add a next field with the value request.path to your form.

Once your form has been processed, you can reroute to the value of this path. An alternative method to do so is to use the HTTP_REFERER value. 

However, if you prevent transmitting referrer information, this won’t function. In other words, if the user operates their browser in private or incognito mode.