Django: redirect users from account

I want to configure my site so that if a user gets to the /login page and they are already logged in, he redirects them to the main page. If they are not logged in, they will be displayed normally. How to do this since Django login code is inline?

+54
django
Feb 23 '10 at 18:09
source share
9 answers

I assume that you are using built-in login, with

 (r'^accounts/login/$', 'django.contrib.auth.views.login'), 

or something similar in your urls.

You can write your own login window, which wraps by default. It will check if the user is already registered and redirected if there is one, and otherwise use the default view.

something like:

 from django.contrib.auth.views import login def custom_login(request): if request.user.is_authenticated(): return HttpResponseRedirect(...) else: return login(request) 

and of course change your urls accordingly:

 (r'^accounts/login/$', custom_login), 
+72
Feb 23 '10 at 18:28
source share

Django 1.10 way

For Django 1.10, released in August 2016, a new parameter called redirect_authenticated_user was added to the view based on the login() function present in django.contrib.auth [1].

example

Suppose we have a Django application with a file named views.py and another file called urls.py The urls.py file will contain this Python code:

 # # Django 1.10 way # from django.contrib.auth import views as auth_views from . import views as app_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/', auth_views.login, name='login', kwargs={'redirect_authenticated_user': True}), url(r'^dashboard/', app_views.Dashboard.as_view(), name='dashboard'), url(r'^$', TemplateView.as_view(template_name='index.html'), name='index'), ] 

From this urlpatterns file urlpatterns part in the urlpatterns variable urlpatterns is as follows, which uses the already mentioned redirect_authenticated_user parameter with the value True :

  url(r'^login/', auth_views.login, name='login', kwargs={'redirect_authenticated_user': True}), 

Note that the default value for redirect_authenticated_user is False .

Django 1.11 way

For Django 1.11, released in April 2017, the LoginView view of the LoginView classes is based on the login() function [2], which gives you two options:

  • Use the same Django 1.10 method that has just been described above, which is a positive point, since your current code will continue to work fine. If you tell the Python interpreter to display warnings, for example, by running the command python -Wd manage.py runserver in the python -Wd manage.py runserver directory of your Django project, and then going to the login page with a web browser, you will see the same thing. the console terminal displays a warning message, for example:

/usr/local/lib/python3.6/site-packages/django/contrib/auth/views.py:54: RemovedInDjango21Warning: The login () view is replaced by the loginView () class based one.

  • Use the new Django 1.11 way , which will make your code more modern and compatible with future releases of Django. With this option, the above example will now look like this:

example

We again assume that we have a Django application with a file named views.py and another file called urls.py The urls.py file will contain this Python code:

 # # Django 1.11 way # from django.contrib.auth import views as auth_views from . import views as app_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/', auth_views.LoginView.as_view(redirect_authenticated_user=True), name='login'), url(r'^dashboard/', app_views.Dashboard.as_view(), name='dashboard'), url(r'^$', TemplateView.as_view(template_name='index.html'), name='index'), ] 

From this file, the corresponding part in the urlpatterns definition of the variable is as follows, which again uses the already mentioned redirect_authenticated_user parameter with True value, but pass it as an argument to the as_view method of the LoginView class:

  url(r'^login/', auth_views.LoginView.as_view(redirect_authenticated_user=False), name='login'), 

Note that here the default value for the redirect_authenticated_user parameter is also False .

Recommendations

+49
Aug 08 '16 at 23:34
source share

anonymous_required decorator

For class-based views

The code:

 from django.shortcuts import redirect def anonymous_required(func): def as_view(request, *args, **kwargs): redirect_to = kwargs.get('next', settings.LOGIN_REDIRECT_URL ) if request.user.is_authenticated(): return redirect(redirect_to) response = func(request, *args, **kwargs) return response return as_view 

Application:

 url(r'^/?$', anonymous_required(auth_views.login), ), url(r'^register/?$', anonymous_required(RegistrationView.as_view()), name='auth.views.register' ), # Could be used to decorate the dispatch function of the view instead of the url 

For viewing functions

From http://blog.motane.lu/2010/01/06/django-anonymous_required-decorator/

The code:

 from django.http import HttpResponseRedirect def anonymous_required( view_function, redirect_to = None ): return AnonymousRequired( view_function, redirect_to ) class AnonymousRequired( object ): def __init__( self, view_function, redirect_to ): if redirect_to is None: from django.conf import settings redirect_to = settings.LOGIN_REDIRECT_URL self.view_function = view_function self.redirect_to = redirect_to def __call__( self, request, *args, **kwargs ): if request.user is not None and request.user.is_authenticated(): return HttpResponseRedirect( self.redirect_to ) return self.view_function( request, *args, **kwargs ) 

Application:

 @anonymous_required def my_view( request ): return render_to_response( 'my-view.html' ) 
+19
Oct 17 '13 at 7:26
source share

Add this decorator above your login to redirect to / home if the user is already registered

@user_passes_test(lambda user: not user.username, login_url='/home', redirect_field_name=None)

and don't forget to import the decorator

from django.contrib.auth.decorators import user_passes_test

+8
Dec 20 '13 at 4:33
source share

I know this is a rather old question, but I will add my technique in case someone needs it:




MyProject / MyApp / views / misc.py

 from django.contrib.auth.views import login as contrib_login, logout as contrib_logout from django.shortcuts import redirect from django.conf import settings def login(request, **kwargs): if request.user.is_authenticated(): return redirect(settings.LOGIN_REDIRECT_URL) else: return contrib_login(request, **kwargs) logout = contrib_logout 



MyProject / MyApp / urls.py

 from django.conf.urls import patterns, url urlpatterns = patterns('myapp.views.misc', url(r'^login/$', 'login', {'template_name': 'myapp/login.html'}, name='login'), url(r'^logout/$', 'logout', {'template_name': 'myapp/logout.html'}, name='logout'), ) ... 
+3
Sep 09 '13 at 18:41
source share

As class performances (CBV) are on the rise. This approach will help you redirect to a different URL when accessing the view only for unauthenticated users.

In my example, the page up sign overlaps the dispatch() method.

 class Signup(CreateView): template_name = 'sign-up.html' def dispatch(self, *args, **kwargs): if self.request.user.is_authenticated: return redirect('path/to/desired/url') return super().dispatch(*args, **kwargs) 

Hurrah!

+3
Feb 09 '18 at 5:31
source share

For Django 2.x in your urls.py:

 from django.contrib.auth import views as auth_views from django.urls import path urlpatterns = [ path('login/', auth_views.LoginView.as_view(redirect_authenticated_user=True), name='login'), ] 
0
Dec 13 '18 at 14:38
source share

Assuming you have finished setting up Django's built-in user authentication (and using decorators), add this to your settings.py:

LOGIN_REDIRECT_URL = '/welcome/'

NOTE: "/ welcome /" is the URL of the main page. It is up to you to replace it.

-one
Jan 12 '12 at 8:10
source share

All you have to do is set the "root" url to your home page. Since the presentation of the homepage is already limited to registered users, it automatically redirects anonymous users to the login page.

List the URL as is. And add something like:

 (r'^$', 'my_project.my_app.views.homepage'), 
-6
Feb 23 '10 at 20:26
source share



All Articles