如何使用现有的用户模型在Django中定义多个用户类型?

时间:2014-12-01 11:13:09

标签: python django django-users

Django有一个很棒的用户模型加上身份验证。使用它,我想定义多个用户类型,比如学生和教授。我想使用对现有模型的最小改动来做到这一点。

其中一种方式是用户组。另一种方法是扩展用户模型并存储标志。鉴于这两个实体不是完全独立的,第一类的成员也可以是第二类的成员,这对我的问题来说是更好的方法。

1 个答案:

答案 0 :(得分:2)

如果我完全理解您的问题,我的选择将是OneToOneField

当我处理客户想要定制用户的项目时,最好的解决方案之一就是创建一个新模型,其中OneToOneField指向Django用户,就像Profile模型一样。如果您有User个对象,则可以执行user.profile并获得与用户相关的个人资料(因此您可以执行user.profile.any_profile_field)。

建议您使用此类解决方案,因为它易于管理和扩展。如果在1个月内您需要向用户添加新的属性/字段/值,使用此解决方案您只需要更改此新模型。

在这里,您可以根据需要将配置文件模型添加到多个字段中,并且易于管理,因为如果您拥有该用户,则您拥有该配置文件,反之亦然

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