尝试扩展AbstractUser以在Django中创建多个用户类型

时间:2018-01-23 08:55:18

标签: python django

所以我一直在互联网上搜索一个完整的例子,说明当你有至少2个不同的模型时如何使用AbstractUser。没有找到任何结论..至少可以使用最新版本的Django(2.0.1)。 我有两个模型,老师和学生,注册需要不同。除了用户名,电子邮件,姓名和姓氏外,我还需要为学生上传个人资料图片,电子邮件,电话,student_ID。并为教师,生物,学术头衔和网站。我开始好吗?什么是正确的方法?



class Profile(AbstractUser):
    photo = models.ImageField(upload_to='students_images')
    email = models.EmailField()
    phone = models.CharField(max_length=15, )


class Student(Profile):
    student_ID = models.CharField(unique=True, max_length=14,
                                  validators=[RegexValidator(regex='^.{14}$',
                                                             message='The ID needs to be 14 characters long.')])

    def __str__(self):
        return self.name


class Teacher(Profile):
    academic_title = models.CharField(max_length=30)
    bio = models.TextField()
    website = models.URLField(help_text="E.g.: https://www.example.com", blank=True)




2 个答案:

答案 0 :(得分:0)

添加

class Meta:
    abstract = True

分析模型

并将AbstractUser更改为models.Model

答案 1 :(得分:0)

您的目标可以使用'个人资料'图案。您不一定需要使用自定义用户模型。但是你需要有一个通用模型来进行身份验证;您可以将builtin django用户用于此类或自定义类...您的StudentTeacher模型应该是OnetoOne关系。这是每the documentation推荐的解决方案。

  

如果您希望存储与用户相关的信息,可以将OneToOneField用于包含其他信息字段的模型。这种一对一模型通常称为配置文件模型,因为它可能存储有关站点用户的非身份验证相关信息。

在您的情况下,您可能会这样做:

class StudentProfile(models.Model):
    user = models.OneToOneField('User', related_name='student_profile')
    # additional fields for students

class TeacherProfile(models.Model):
    user = models.OneToOneField('User', related_name='teacher_profile')
    # additional fields for teachers

然后,您可以根据这些个人资料模型创建注册表单。

class StudentResistrationForm(forms.ModelForm):
    class Meta:
        model = StudentProfile
        fields = (...)

class TeacherRegistrationForm(forms.ModelForm):
    class Meta:
        model = TeacherProfile
        fields = (...)

您可以在创建配置文件的同时创建与配置文件相关的用户实例。例如,您可以使用formset执行此操作。

相关问题