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

标签 python django

所以我一直在互联网上搜索一个完整的例子,当你有至少 2 个不同的模型时如何使用 AbstractUser。没有找到任何决定性的东西......至少可以在最新版本的 Django (2.0.1) 上工作。
我有2个模型,老师和学生,注册需要不同。除了用户名、电子邮件、姓名和姓氏之外,我还需要例如为学生上传个人资料图片、电子邮件、电话、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)

最佳答案

您可以使用“配置文件”模式来实现您的目标。您不一定需要为此使用自定义用户模型。但是你需要有一个单一的通用模型来进行身份验证;您可以为此或自定义类使用内置 django 用户...您的 StudentTeacher模型应该是一对一的关系。这是根据 the documentation 推荐的解决方案.

If you wish to store information related to User, you can use a OneToOneField to a model containing the fields for additional information. This one-to-one model is often called a profile model, as it might store non-auth related information about a site user.



在您的情况下,您可以执行以下操作:
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 = (...)

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

关于python - 尝试扩展 AbstractUser 以在 Django 中创建多个用户类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48397608/

相关文章:

python - 在没有 Django 其余部分的情况下使用 Django 的模板引擎

python - 使用 TastyPie 自定义输出 XML(带有属性)?

python - 将 Python 中的打印列表转换回实际列表的最佳方法是什么

Python Django REST 调用返回对象编号而不是对象名称

python - 在 Python 中设置时区

django - 在 Django View 中设置语言

python - 使用 'statsmodels' 指定将哪个类别视为基础

python - 自定义 Django Rest Framework 序列化器输出?

python - 如何排除 Django 中同一天创建的项目

Django 使用另一个表中的数据更新表