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 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 /.


You can use this

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

Make sure to import this

from django.shortcuts import redirect

My favorite way to do that is giving the request.path as GET parameter to the form. It will pass it when posting until you redirect. In Class-Based-Views (FormView, UpdateView, DeleteView or CreateView) you can directly use it as success_url. Somewhere i read that it's bad practise to mix GET and POST but the simplicity of this makes it to an exception for me.


Example urls.py:

urlpatterns = [
    path('', HomeView.as_view(), name='home'),
    path('user/update/', UserUpdateView.as_view(), name='user_update'),
]

Link to the form inside of the template:

<a href="{% url 'user_update' %}?next={{ request.path }}">Update User</a>

Class-Based-View:

class UserUpdateView(UpdateView):
    ...
    def get_success_url(self):
        return self.request.GET.get('next', reverse('home'))

In your function based view you can use it as follows:

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()
            next = request.GET.get('next', reverse('home'))
            return HttpResponseRedirect(next)

    args = {}
    args.update(csrf(request))
    args['username'] = request.user.username
    args['form'] = AdverForm()
    args['uw'] = uw
    return  render_to_response('createadv.html', args)