在我的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']
字段值。
CustomUserForm
的初始值?password
和profile_pic
设置为可选(它说This field is required.
;我是否需要另一个modelForm
?CustomUserForm
和StudentForm
合并为一个表格,还是应该分开处理?