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
设置.
then use it for your LOGIN_REDIRECT_URL
setting.
LOGIN_REDIRECT_URL = 'login_success'
这篇关于Django -- 条件登录重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!