Django“此字段为必填。”尝试更新CustomUser

时间:2020-09-30 23:01:25

标签: django django-models django-forms django-views django-custom-user

在我的models.py中,我有这个:

class CustomUser(AbstractUser):
    USER_TYPE = ((1, 'HOD'), (2, 'Staff'), (3, 'Student'))
    username = None
    email = models.EmailField(unique=True)
    ....

class Student(models.Model):
    admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
    gender = models.CharField(max_length=1, choices=GENDER)
    address = models.TextField()
    profile_pic = models.ImageField(upload_to='media')
    session_start_year = models.DateField(null=True)
    session_end_year = models.DateField(null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now_add=True)

在我的forms.py中,我有这个:

class CustomUserForm(forms.ModelForm):
    email = forms.EmailField(required=True)
    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)
    password = forms.CharField(widget=forms.PasswordInput)
    widget = {
        'password': forms.PasswordInput()
    }

    def __init__(self, *args, **kwargs):
        super(CustomUserForm, self).__init__(*args, **kwargs)
        for visible in self.visible_fields():
            visible.field.widget.attrs['class'] = 'form-control'

    class Meta:
        model = CustomUser
        fields = ['first_name', 'last_name', 'email', 'password', ]


class StudentForm(CustomUserForm):
    def __init__(self, *args, **kwargs):
        super(StudentForm, self).__init__(*args, **kwargs)
        for visible in self.visible_fields():
            visible.field.widget.attrs['class'] = 'form-control'

    class Meta(CustomUserForm.Meta):
        model = Student
        fields = CustomUserForm.Meta.fields + \
            ['course', 'gender', 'address', 'profile_pic',
                'session_start_year', 'session_end_year']
        widgets = {
            'session_start_year': DateInput(attrs={'type': 'date'}),
            'session_end_year': DateInput(attrs={'type': 'date'}),
        }

通过将context = {'form': StudentForm()}传递到模板,我可以从中添加新学生。 但是现在,我在尝试更新学生方面遇到问题。 我可以将student对象作为instance传递给StudentForm(),但仅设置了['course', 'gender', 'address', 'profile_pic','session_start_year', 'session_end_year']字段值。

  1. 如何设置CustomUserForm的初始值?
  2. 我想在更新时将passwordprofile_pic设置为可选(它说This field is required.;我是否需要另一个modelForm
  3. 建议将CustomUserFormStudentForm合并为一个表格,还是应该分开处理?

0 个答案:

没有答案