Django - Conditional Login Migration

I am working on a Django application that will have two types of users: admins and users. Both are groups in my project, and depending on which group a separate login belongs to, I would like to redirect them to separate pages. Now I have it in my .py settings

LOGIN_REDIRECT_URL = 'admin_list' 

This redirects all users who are members of the "admin_list", but the view is accessible only to members of the Admins group, otherwise the value 403 is returned. As for the login itself, I just use the one Django provides. I added this to my main urls.py file to use these views:

 url(r'^accounts/', include('django.contrib.auth.urls')), 

How can I do this so that only members of the Admins group are redirected to this view, and everyone else is redirected to another view?

+8
python django django-admin django-views
source share
2 answers

Create a separate view that redirects the user based on whether they are in the admin group.

 from django.shortcuts import redirect def login_success(request): """ Redirects users based on whether they are in the admins group """ if request.user.groups.filter(name="admins").exists(): # user is an admin return redirect("admin_list") else: return redirect("other_view") 

Add view to urls.py ,

 url(r'login_success/$', views.login_success, name='login_success') 

then use it to configure LOGIN_REDIRECT_URL .

 LOGIN_REDIRECT_URL = 'login_success' 
+16
source share

I use an intermediate view to accomplish the same thing:

 LOGIN_REDIRECT_URL = "/wherenext/" 

then in my urls.py:

 (r'^wherenext/$', views.where_next), 

then in the view:

 @login_required def wherenext(request): """Simple redirector to figure out where the user goes next.""" if request.user.is_staff: return HttpResponseRedirect(reverse('admin-home')) else: return HttpResponseRedirect(reverse('user-home')) 
+3
source share

All Articles