Django根据权限和组将用户重定向到应用程序

时间:2017-04-18 14:35:08

标签: django python-3.x

假设我有一个django项目,其中有4个应用程序,1个应用程序用于登录

项目网址:

from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings

urlpatterns = [
    url(r'^', include('Login.urls')),
    url(r'^admin/', admin.site.urls),
]

设置:

LOGIN_REDIRECT_URL = '/'

登录app urls:

from django.conf.urls import url
from django.contrib.auth import views as auth_views

urlpatterns = [
    url(r'^login/$', auth_views.login, name='login'),
    url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'),
]

现在说我有3个基于用户类型的应用,即Admin,Team Lead,Worker 所以我想根据用户的类型重定向用户。

我怎样才能做到这一点? 任何帮助表示赞赏

1 个答案:

答案 0 :(得分:1)

我猜你会手动添加/编辑用户组。 这可以从django管理面板完成。 以下是群组/权限django文档:Permissions and Authorization

这就是我所做的: 我已经创建了一个索引视图,以便获取用户组并重定向到您想要的相应视图。

因此,views.py中的索引视图:

from django.contrib.auth.decorators import login_required

@login_required
def index(request):
    group = request.user.groups.filter(user=request.user)[0]
    if group.name=="employees":
        return HttpResponseRedirect(reverse('worker'))
    elif group.name=="teamLeader":
        return HttpResponseRedirect(reverse('teamLeader'))
    elif group.name=="admin":
        return HttpResponseRedirect(reverse('adm'))

    context = {}
    template = "index.html"
    return render(request, template, context)

urls.py中的网址:

from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from app import views as app_views
urlpatterns = [
    url(r'^login/$', auth_views.login, name='login'),
    url(r'^$', app_views.index, name='index'),
    url(r'^employees/$', app_views.employees, name='employees'),
    url(r'^teamLeader/$', app_views.teamLeader, name='teamLeader'),
    url(r'^adm/$', app_views.adm, name='adm'),
]

在settings.py

LOGIN_URL = '/login'
LOGIN_REDIRECT_URL = '/'

这是你想要做的吗?