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 the individual logging in belongs to I'd like to redirect them to separate pages. Right now I have this in my settings.py
LOGIN_REDIRECT_URL = 'admin_list'
This redirects all users who sign in to 'admin_list', but the view is only accessible to members of the Admins group -- otherwise it returns a 403. As for the login view itself, I'm just using the one Django provides. I've added this to my main urls.py file to use these views:
url(r'^accounts/', include('django.contrib.auth.urls')),
How can I make this so that only members of the Admins group are redirect to this view, and everyone else is redirected to a different view?
Django Redirects: A Super Simple Example Just call redirect() with a URL in your view. It will return a HttpResponseRedirect class, which you then return from your view. Assuming this is the main urls.py of your Django project, the URL /redirect/ now redirects to /redirect-success/ .
Django comes with an optional redirects application. It lets you store redirects in a database and handles the redirecting for you. It uses the HTTP response status code 301 Moved Permanently by default.
The redirect() function allows us to redirect a user to the URL of our choice. In the Flask application that we are building so far, we have a /shortenurl route that checks to see what method type is in use. If it is a GET request, we are simply returning some text to the user.
How do I go back in Django template? Use HTTP_REFERER value: for use in func return HttpResponseRedirect(request.
Create a separate view that redirects user's 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 the view to your urls.py
,
url(r'login_success/$', views.login_success, name='login_success')
then use it for your LOGIN_REDIRECT_URL
setting.
LOGIN_REDIRECT_URL = 'login_success'
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With