Django:同名的初始modelform字段
我得到了一个带有一些ajax操作的Django:同名的初始modelform字段,django,django-forms,Django,Django Forms,我得到了一个带有一些ajax操作的ModelForm,可以创建如下字段: <input type="hidden" name="myfield" value="1" /> <input type="hidden" name="myfield" value="2" /> 那么现在,我如何将\uu init\uu的每个其他\u模型包含为隐藏字段?您可以以这种方式动态添加模型表单字段 class MyModelForm(forms.ModelForm): myfiel
ModelForm
,可以创建如下字段:
<input type="hidden" name="myfield" value="1" />
<input type="hidden" name="myfield" value="2" />
那么现在,我如何将
\uu init\uu
的每个其他\u模型
包含为隐藏字段?您可以以这种方式动态添加模型表单字段
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)
好的,谢谢,但是在每个隐藏输入标记的
name
属性上使用相同的other_model
怎么样?您可以指定初始属性。检查一下edt,有点像。由于我的项目,我不得不做一些其他的修改,但我将你的答案标记为接受。谢谢你的帮助。:)伟大的反馈总是有助于将来提供更好的答案:)谢谢
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)