Menu Close

How to redirect to previous page after login with Python Django?

To redirect to previous page after login with Python Django, we change some settings and then add the previous page URL into the template,

For instance, we write

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.core.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.request",
)

to add the django.core.context_processors.request and django.core.context_processors.auth template context processors.

Then we add the URL by writing

<a href="{% url django.contrib.auth.views.login %}?next={{request.path}}">Login</a>

to add the django.contrib.auth.views.login URL as the URL with the request.path path set to the redirect URL in base.html so the login form submit button will redirect to the request.path.

And then we add

{% block content %}
<form method="post" action="">
  {{form.as_p}}
<input type="submit" value="Login">
</form>
{% endblock %}

to add the login form.

Posted in Python, Python Answers