How to redirect to previous page in Django after POST request

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>

You can use this

return redirect(request.META.get('HTTP_REFERER'))

Make sure to import this

from django.shortcuts import redirect

You can use the HTTP_REFERER value:

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

Note that this will not work if the client disabled sending referrer information (for example, using a private/incognito browser Window). In such a case it will redirect to /.