仅限Django中某些用户组的某些页面

时间:2017-05-10 14:12:54

标签: python django django-views django-urls

此时,当一种类型的用户登录时,他只需更改URL即可访问任何其他用户的页面。如何将某些页面限制为仅限某些用户以及@login_required

views.py

def login_user(request):
if request.method == "POST":
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        u = User.objects.get(username=username)
        if user.is_active:
            login(request, user)
            if user.groups.filter(name='hod').exists():
                return redirect('/hod')
            elif user.groups.filter(name='principal').exists():
                return redirect('/principal')
            elif user.groups.filter(name='Rep').exists():
                return redirect('/rep')
            elif user.groups.filter(name='Ajithzen').exists():
                return redirect('/ajithsen')
            elif user.groups.filter(name='graphics').exists():
                return redirect('/ashok')
            elif user.groups.filter(name='Event_incharge').exists():
                return redirect('/incharge')
            elif user.groups.filter(name='Event_coord').exists():
                return redirect('/chair')
            elif user.groups.filter(name='IEEE').exists():
                return redirect('/ieee')
            else:       
                return render(request, 'retest/login.html', {'error_message': 'Invalid login'})
        else:
            return render(request, 'retest/login.html', {'error_message': 'Your account has been disabled'})
    else:
        return render(request, 'retest/login.html', {'error_message': 'Invalid login'})
return render(request, 'retest/login.html')
@login_required
def rep(request):
    u = request.user
    all_requests= Retest.objects.all() 
    return render(request, 'retest/home.html', {'u':u, 'all_requests' : all_requests }) 

urls.py

url(r'^$', views.login_user, name='login_user'),
url(r'^rep$', views.rep, name='rep'),

如果群组代表的用户已登录,则可以通过更改/代表其他人来访问其他人的页面

1 个答案:

答案 0 :(得分:0)

一种方法是编写自己的decorator,检查天气,允许当前用户查看他们尝试访问的页面。这可以通过使用会话来完成。当用户登录时,他们将获得身份验证并获得与其权限相对应的会话变量。