Django: Redirect to previous page after login

I'm trying to build a simple website with login functionality very similar to the one here on SO. The user should be able to browse the site as an anonymous user and there will be a login link on every page. When clicking on the login link the user will be taken to the login form. After a successful login the user should be taken back to the page from where he clicked the login link in the first place. I'm guessing that I have to somehow pass the url of the current page to the view that handles the login form but I can't really get it to work.

EDIT: I figured it out. I linked to the login form by passing the current page as a GET parameter and then used 'next' to redirect to that page. Thanks!

EDIT 2: My explanation did not seem to be clear so as requested here is my code: Lets say we are on a page foo.html and we are not logged in. Now we would like to have a link on foo.html that links to login.html. There we can login and are then redirected back to foo.html. The link on foo.html looks like this:

      <a href='/login/?next={{ request.path }}'>Login</a> 

Now I wrote a custom login view that looks somewhat like this:

def login_view(request):
   redirect_to = request.REQUEST.get('next', '')
   if request.method=='POST':
      #create login form...
      if valid login credentials have been entered:
         return HttpResponseRedirect(redirect_to)  
   return render_to_response('login.html', locals())

And the important line in login.html:

<form method="post" action="./?next={{ redirect_to }}">

So yeah thats pretty much it, hope that makes it clear.

Asked by: Thomas304 | Posted: 30-11-2021

Answer 1

You do not need to make an extra view for this, the functionality is already built in.

First each page with a login link needs to know the current path, and the easiest way is to add the request context preprosessor to (the 4 first are default), then the request object will be available in each request:


Then add in the template you want the Login link:


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

This will add a GET argument to the login page that points back to the current page.

The login template can then be as simple as this:


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

Answered by: Blake585 | Posted: 01-01-2022

Answer 2

To support full urls with param/values you'd need:

?next={{ request.get_full_path|urlencode }}

instead of just:

?next={{ request.path }}

Answered by: Wilson872 | Posted: 01-01-2022

Answer 3

This may not be a "best practice", but I've successfully used this before:

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

Answered by: Dominik577 | Posted: 01-01-2022

Answer 4

Django's built-in authentication works the way you want.

Their login pages include a next query string which is the page to return to after login.

Look at

Answered by: Michael477 | Posted: 01-01-2022

Answer 5

I linked to the login form by passing the current page as a GET parameter and then used 'next' to redirect to that page. Thanks!

Answered by: Ryan485 | Posted: 01-01-2022

Answer 6

I encountered the same problem. This solution allows me to keep using the generic login view:

urlpatterns += patterns('django.views.generic.simple',
    (r'^accounts/profile/$', 'redirect_to', {'url': 'generic_account_url'}),

Answered by: Anna841 | Posted: 01-01-2022

Answer 7

In registration/login.html (nested within templates folder) if you insert the following line, the page will render like Django's original admin login page:

{% include "admin/login.html" %}

Note: The file should contain above lines only.

Answered by: Wilson154 | Posted: 01-01-2022

Answer 8

See django docs for views.login(), you supply a 'next' value (as a hidden field) on the input form to redirect to after a successful login.

Answered by: Samantha680 | Posted: 01-01-2022

Answer 9

You can also do this

<input type="hidden" name="text" value="{% url 'dashboard' %}" />

Answered by: Fiona967 | Posted: 01-01-2022

Similar questions

python - Django: Redirect to previous page *with query string* after login

I am using django.contrib.auth and would like to redirect to the previous page after logging in. I would like something like the following: Django: Redirect to previous page after login except the redirected-to URL can contain a query string. Currently I have the following link in my template:...

python - web2py redirect to previous page

When from a page , I goto another page via some hyperlink,is there any way to go back to the previous page. The previous page has some arguments also. SO I want to ask whether the previous page is saved somewhere or is there any other way to go back to that page

python - Django: Redirect to previous page *with query string* after login

I am using django.contrib.auth and would like to redirect to the previous page after logging in. I would like something like the following: Django: Redirect to previous page after login except the redirected-to URL can contain a query string. Currently I have the following link in my template:...

python - Redirect back to previous page after logged in (Django)

I have created login page forced login in several pages. Now i need to redirect back to previous page after successful login. When i force login by @login_required(login_url='/login/'). It includes next parameter in query string. I tried to catch it with redirect_to =

python - Redirect to previous user's last page after new user login

I am currently developing a Django website and I am using django.contrib.auth and django-security-session for closing user sessions automatically. In case a user leaves its session open and a new user arrives at the same navigator after that session expired, if the new user attempts to use that same session, the session will be automatically closed. However, if now this new user logs in again, he is redirected to ...

python - Django redirect back to previous page on form post

I'm trying to have a form post redirect back to the page it was posted from. So my app has a detail page that displays information about a place, /arena/123, and on the same page there is a form that a user can enter some comments or ratings about the current place they are looking at. These are my view functions. class DetailView(LoginRequiredMixin, generic.DetailView): model = Arena template_name ...

python - Django redirect appends the url to the previous one

I am trying to redirect from an url /alerta/3304557/ to one /alerta/rio using the redirect('/alerta/rio/') call. /alerta/rio/ works just fine when typed in manually. But redirect is issuing a redirect to http://localhost:8000/alerta/3304557/alerta/rio which obviously causes a 404 error since that URL does not exist. Relevant lines of code:...

python - Django redirect doesn't append to previous pattern url(r'^reg/$', views.reg_view, name='reg'), url(r'^logout/$', views.logout_view, name="logout"), url(r'^search/$', views.search_redirect, name='search_redirect'), url(r'^search/(?P&lt;keyword&gt;.*?)/page/(?P&lt;page&gt;[0-9]+)/$', views.SearchView.as_view(), name='search'), url(r'^search/(?P&lt;keyword&gt;.*?)/$', views.SearchView.as_view(), name='search'), url...

python - Django redirect to previous page saving queries

So I have a page that displays a table and on each row I have a button called delete that deletes that row and all the information related to it in my database. The delete button works fine, as in it deletes the information in my DB, but I'd like to redirect it to the page where I display the table. The problem is that, to access the page that shows the table, it is done through a search with POST method. I...

python - How can I redirect to previous page on flask?

I'm at a beginner's level with flask and am trying to create a web app. The user will upload a photo from the file explorer and the image is displayed on screen (thanks to an answer I found here). My issue is that when I click "go back" when I'm at the confirmation page, I want to redirect to the file up...

python - When i redirect to the previous route some information don't appear

Now, I'm rendering books information where I allow the user to add comments to any book when the user click at &quot;add comment&quot; button at book route they redirect to addcomment route, and &quot;comment.html&quot; appear where they can add comments and see previous comments of other users. However, when I click at &quot;add comment&quot; button at book route I can add my comment and see previous comments, but when I ...

bash - Redirect command to input of another in Python

I would like to replicate this in python: gvimdiff &lt;(hg cat file.txt) file.txt (hg cat file.txt outputs the most recently committed version of file.txt) I know how to pipe the file to gvimdiff, but it won't accept another file: $ hg cat file.txt | gvimdiff file.txt - Too many edit arguments: "-" Getting to the python part... # hg...

Python + Django page redirect

How do I accomplish a simple redirect (e.g. cflocation in ColdFusion, or header(location:http://) for PHP) in Django?

python - How to pass information using an HTTP redirect (in Django)

I have a view that accepts a form submission and updates a model. After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page. How can I "pass" this message to the other page? HttpResponseRedirect only accepts a URL. I've seen this done bef...

How to redirect the output of .exe to a file in python?

In a script , I want to run a .exe with some command line parameters as "-a",and then redirect the standard output of the program to a file? How can I implement that?

python - How to Redirect To Same Page on Failed Login

The Django framework easily handles redirecting when a user fails to log in properly. However, this redirection goes to a separate login page. I can set the template to be the same as the page I logged in on, but none of my other objects exist in the new page. For example, I have a front page that shows a bunch of news articles. On the sidebar is a login form. When the user logs in, but fails to authenticate, I wou...

cgi - How to redirect to another page in Python in CGIAr

If I want to redirect the user from a cgi script to a HTML page using core libraries from the following: import cgi Please could someone point me in the right direction. Nothing more. Simply redirect from cgi script to html page. How ever you would do this Python. If you have to physically write out the HTTP Response Headers to achieve this, then I would appreciate any i...

How to redirect stderr in Python? Via Python C API?

This is a combination of my two recent questions: [1] Python instance method in C [2] How to redirect stderr in Python? I would like to log the output of both stdout and stderr from a python script. The thing I want to ask is...

How to redirect stderr in Python?

I would like to log all the output of a Python script. I tried: import sys log = [] class writer(object): def write(self, data): log.append(data) sys.stdout = writer() sys.stderr = writer() Now, if I "print 'something' " it gets logged. But if I make for instance some syntax error, say "print 'something# ", it wont get logged - it will go into the console instead. Ho...

linux - Redirect stderr to stdout on exec-ed process from python?

In a bash script, I can write: exec 2&gt;&amp;1 exec someprog And the stderr output of someprog would be redirected to stdout. Is there any way to do a similar thing using python's os.exec* functions? This doesn't have to be portable, just work on Linux.

python - How to set cookies with redirect in Pylons

In light of the cookie-handling bugs affecting Safari and Chrome (see this thread), and Pylons implementation of redirect_to as an exception, is it possible to reliably set a tracking cookie and redirect at the same time? Is the META refresh method looked down upon?

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python