我在ModelForm中有一个模型中不存在的字段。通过重写ModelForm.save()函数单独保存该字段:
class MyForm(ModelForm):
custom_field = CharField(label='Custom field', widget=TextInput())
def save(self, commit=True):
data = self.cleaned_data
# save custom_field
现在如何在呈现之前将此自定义字段加载到ModelForm中(在编辑模式下)。我尝试设置字段字典,但ModelForm中不存在字典字典:
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['custom_field'] = self.instance._meta.model.custom_field
我收到以下错误:
type object 'MyForm' has no attribute 'fields'
答案 0 :(得分:2)
要为字段提供初始数据,请使用initial
参数:
form = MyForm(instance=my_obj, initial={'custom_field': 'Test'})
或者,如果您想在__init__
构造函数中执行此操作:
def __init__(self, *args, **kwargs):
kwargs['initial'] = kwargs.get('initial', {})
kwargs['initial']['custom_field'] = 'Test'
super(MyForm, self).__init__(*args, **kwargs)