Django有一个很棒的用户模型以及身份验证。使用这个,我想定义多个用户类型,例如学生和教授。我想使用对现有模型的最小改动来做到这一点。
一种方法是用户组。另一个方法是扩展用户模型并存储标志。考虑到两个实体不是完全独立的,并且类型一的成员也可以是类型二的成员,这对于我的问题而言是一种更好的方法。
如果我完全理解您的问题,我的选择是OneToOneField
。
当我在客户需要自定义用户的项目上工作时,最好的解决方案之一是创建一个新模型,并OneToOneField
像Profile
模型一样指向Django用户。当您拥有一个User
对象时,您可以执行操作,user.profile
并获得与用户相关的配置文件(因此您可以执行user.profile.any_profile_field
)。
我建议您使用这种解决方案,因为它易于管理且可扩展。如果在1个月内需要为用户添加新的属性/字段/值,则使用此解决方案,您只需更改此新模型。
在这里,您可以根据需要将任意多个字段添加到Profile模型,并且易于管理,因为如果您拥有用户,则拥有Profile,反之亦然
class Profile(models.Model):
USER_TYPE_CHOICES = (
('s', 'Student'),
('t', 'Teacher' ),
)
user = models.OneToOneField(User)
type_user = models.CharField(max_length=20, default='s',choices=USER_TYPE_CHOICES)
# ... ... ...
# Your fields here
编辑
如果使用此authenticate
方法,则您的方法可以保持不变,不正确。
您可以按照以下示例进行操作:
user = User.objects.all()[0] # Get the first user
user.profile # This would return the profile object
user.profile.type_user # This would return the type_user of the profile related with this user
因此,您可以在登录功能中使用配置文件字段,或者在用户访问某些URL时使用它,然后检查用户类型是否允许。
控制仅教师可以输入的模板的示例:
def teacher_view(request):
if not request.user.is_authenticated:
# If user is not logged in, send it to login page
else:
if request.user.profile.type_user == 's': # If the user is student
# Here you can raise an error (not enough permissions), raise an error or redirect
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句