我得到了一个ModelForm
,其中包含一些创建字段的ajax操作:
<input type="hidden" name="myfield" value="1" />
<input type="hidden" name="myfield" value="2" />
我可以使用ManyToMany
将这些数据保存为request.POST.getlist('myfield')
,但我似乎无法在更新视图中初始化隐藏的输入字段。
到目前为止我得到了什么:
class MyModelForm(forms.ModelForm):
myfield = forms.Field('Some field')
class Meta:
model = MyModelForm
def __init__(self, *args, **kwargs):
other_models = OtherModel.objects.filter(mymodelform=kwargs['instance'])
现在,如何将other_models
__init__
的{{1}}作为隐藏字段包含在内?
答案 0 :(得分:1)
您可以以这种方式动态添加模型表单字段。
class MyModelForm(forms.ModelForm):
myfield = forms.Field('Some field')
class Meta:
model = MyModelForm
def __init__(self, *args, **kwargs):
instance = kwargs.pop('instance')
other_models = OtherModel.objects.filter(mymodelform=instance)
super(MyModelForm, self).__init__(*args, **kwargs)
for i, other_model in enumerate(other_models):
self.fields['other_model_field_{i}'.format(i=i)] = forms.CharField(widget = forms.HiddenInput(), initial=other_model.name)