我正在使用DjangoCrispyForms
,并且为我的ModelForm
模型创建了一个User
。
在Meta
类中,我以表格的形式注册了我想要拥有的字段,其中之一是User的id
。
问题是此id
字段没有出现在表单中,我不得不手动将这样的字段添加到表单类中。当我想将更改保存到数据库并且需要从id
中提取cleaned_data
时,它变得更加复杂。
class EditUserForm(forms.ModelForm):
id = forms.IntegerField() # needed to add this
def __init__(self, *args, **kwargs):
super(EditUserForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.fields['id'].widget = HiddenInput()
self.helper.layout = Layout(
Fieldset(
'Edit user',
'username',
'first_name',
'last_name',
'email',
'is_superuser',
'id'
),
ButtonHolder(
Submit('submit', 'Save')
))
def clean(self):
username = self.cleaned_data.get('username')
email = self.cleaned_data.get('email')
if len(User.objects.filter(username=username)) > 1:
self.add_error('username', 'Username is taken.')
if len(User.objects.filter(email=email)) > 1:
self.add_error('email', 'Account with this email exists')
return self.cleaned_data
def save(self, commit=True):
instance = super(EditUserForm, self).save(commit=False)
data_id = self.cleaned_data.get('id') # need to get this from data
instance.id = data_id # and set id for instance
if commit:
instance.save()
return instance
class Meta:
model = User
fields = ['id', 'username', 'first_name', 'last_name', 'email', 'is_superuser'] # here we can see that id is actually present in fields
我错过了什么吗?应该是吗?