这个问题类似于
和
我需要的基本上与MultiValueField相反,我可以将数据从一个表单字段 - Name保存到两个模型字段 - Firstname, Lastname。我无法找到与 MultiValueField 相反的任何东西。
有人可以建议我什么是更好的方法。
为什么不在Form 中定义name
字段并覆盖 save 方法以保存到模型字段,如下所示:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句