我正在一个需要多个用户的项目中工作。我应该如何根据用户的角色将用户发送到不同的页面?这是与登录相关的模型和视图的代码。
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
Roles = (
('sales', 'SALES'),
('operations', 'OPERATIONS'),
('cashier', 'CASHIER'),
('frontdesk', 'FRONTDESK'),
('client', 'CLIENT'),
)
class UserProfile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True)
role = models.CharField(max_length=50, choices=Roles, default='client')
def __str__(self):
return self.user.username
查看登录信息:
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username = username , password = password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse("ACCount not active!!")
else:
print("someone tried to login and falied!")
print("Username : {} and Password : {}".format(username,password))
return HttpResponse("Invalid credentials!")
else:
return render(request , 'NewApp/login.html' , {})
答案 0 :(得分:1)
您可以执行以下操作:检查角色值,然后重定向到适当的视图:
if user.is_active:
login(request, user)
if user.userprofile.role == 'sales':
# sales users landing page
elif user.userprofile.role == 'operations':
# operations users landing page
. . . . .
else:
return HttpResponseRedirect(reverse('index'))