Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

python - Django -- Conditional Login Redirect

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...