如何防止用户成为这两种类型?

How to prevent user to be both of types?

我有一个模型来自 this answer:

class MyUser(AbstractUser):
    is_student = models.BooleanField(default=False)
    is_teacher = models.BooleanField(default=False)

是否可以在模型级别阻止同时创建两种类型的新用户?换句话说,它可能只有 is_student == Falseis_teacher == True,反之亦然。

据我所知,您不能拥有多个具有不同属性的用户模型。 Django 只能有一个用户模型。 如果您需要的唯一更改是其中一个字段需要消失,我最好的选择是在需要时忽略该字段。 例如,当学生想要注册时,他们会单击 "Sign up as a student" link,您只需从表单中省略 is_teacher 字段,反之亦然。

例如:

用户模型:

class User(AbstractUser):
    """User model."""
    username = models.CharField(max_length=75, unique=True)
    email = models.EmailField(_('email address'), unique=True)
    is_student = models.BooleanField(default=False)
    is_teacher = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    objects = UserManager()

    def __str__(self):
        """Return a string representation of the user."""
        string_repr = str(self.username) + ' (' + str(self.email) + ')'

        return string_repr

UserCreationForm 模型(学生和教师):

class CreateUserStudentForm(UserCreationForm):
    # Require the email field.
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ("email", "username", "is_student", "password1", "password2")

    def clean_email(self):
        data = self.cleaned_data['email']
        return data.lower()

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        # Get all the relevant data, and save it.
        user.email = self.clean_email()
        user.username = self.cleaned_data["username"]
        user.is_student = self.cleaned_data["is_student"]
        user.set_password(self.cleaned_data['password1'])

        # Save the newly created user.
        if commit:
            user.save()
        return user

class CreateUserTeacherForm(UserCreationForm):
    # Require the email field.
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ("email", "username", "is_teacher", "password1", "password2")

    def clean_email(self):
        data = self.cleaned_data['email']
        return data.lower()

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        # Get all the relevant data, and save it.
        user.email = self.clean_email()
        user.username = self.cleaned_data["username"]
        user.is_teacher = self.cleaned_data["is_teacher"]
        user.set_password(self.cleaned_data['password1'])

        # Save the newly created user.
        if commit:
            user.save()
        return user