Django保存多种用户类型

时间:2017-03-15 07:38:59

标签: python django

我是Django的新手,想为我的网络应用程序做一个注册页面。目前,我需要两种类型的用户(学生和教师)。我有一个复选框供用户选择他们是我的RegistrationForm中的学生还是教师。我想知道在我的RegistrationForm下,如何在save()方法下分别将它们保存到Student或Instructor表中?

register.py

class RegistrationForm(forms.ModelForm):
    email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder': 'Email'}), label='')
    password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'}), label='')
    password2 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password'}), label='')
    INSTRUCTOR = "INS"
    STUDENT = "STU"
    roles_choices = [(INSTRUCTOR, "Instructor"), (STUDENT, "Student")]
    role = forms.ChoiceField(choices=roles_choices, widget=forms.RadioSelect(), label='')

    class Meta:
        model = User
        fields = ['email', 'password1', 'password2']

    def clean(self):
        """
        Verifies that the values entered into the password fields match

        NOTE: Errors here will appear in ``non_field_errors()`` because it applies to more than one field.
        """
        cleaned_data = super(RegistrationForm, self).clean()
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError("Passwords don't match. Please enter both fields again.")
        return self.cleaned_data

    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.set_password(self.cleaned_data['password1'])
        user.set_role(self.cleaned_data['role'])
        if commit:
            user.save()
        return user

models.py

class User(AbstractBaseUser):
    role = models.CharField(max_length=3)

    email = models.EmailField(max_length=100, primary_key=True)
    first_name = models.CharField(max_length=30, null=False)
    last_name = models.CharField(max_length=30, null=False)
    password = models.CharField(max_length=100, null=False)
    is_staff = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'

    class Meta:
        abstract = True

     def get_absolute_url(self):
        return "/%s/%s/" % (self.role, urlquote(self.email))

    def set_role(self, role):
        self.role = role

    def get_role(self):
        return self.role

    def get_short_name(self):
        pass

    def get_full_name(self):
        pass


class Instructor(User):
    pass

class Student(User):    
    matric_id = models.CharField(max_length=10, blank=False, null=False)

1 个答案:

答案 0 :(得分:1)

我将学生和教师字段作为一个单独的模型与用户one to one field,这样您甚至可以选择让同一个用户工作作为教练和学生,如果那样适用于您的情况。

对于您的表单,您可以在同一页面上有3个表单视图(一个用于常规注册,另外两个根据用户选择的内容,教师或学生而不同)。

保存部分可以在views.py中完成,因为您可以提取2个表单并保存+链接两个实例。

如果您需要更多说明,请提出并且我很乐意加入一些代码段。