Django - 有条件登录重定向 [英] Django -- Conditional Login Redirect
问题描述
我正在处理一个Django应用程序,它将有两种类型的用户:管理员和用户。两个都是我的项目中的组,并且取决于个人登录属于哪个组,我想将它们重定向到单独的页面。现在我在我的settings.py
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'
这将重定向所有登录到admin_list的用户,但该视图只能由Admins组的成员访问,否则返回403。至于登录视图本身,我只是使用一个Django提供。我已将其添加到我的主要urls.py文件中以使用这些视图:
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')),
只有Admins组的成员才能重定向到此视图,其他所有人都被重定向到另一个视图。
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?
推荐答案
创建一个单独的视图根据他们是否在管理员组中重定向用户。
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")
将视图添加到您的 urls.py
,
url(r'login_success/$', views.login_success, name='login_success')
然后将其用于您的 LOGIN_REDIRECT_URL
设置
LOGIN_REDIRECT_URL = 'login_success'
这篇关于Django - 有条件登录重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!