更新时间:2023-11-09 21:15:40
为什么不在 Form 中定义 name
字段,并覆盖save方法以将其保存到模型字段中,如下所示:
Why don't you define the name
field in Form and override the save method to save to the model fields like this:
class SomeForm(forms.ModelForm):
name = forms.CharField(max_length=255, required=True)
class Meta:
model = YourModel
fields = ['name', 'and_other_fields']
def save(self, commit=True)
instance = super(SomeForm, self).save(commit=False)
_name = self.cleaned_data.get('first_name').split(' ')
instance.first_name = _name[0]
instance.last_name = ' '.join(_name[1:])
instance.save()
return instance