Django:具有相同名称的初始modelform字段

时间:2013-11-11 02:18:39

标签: django django-forms

我得到了一个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}}作为隐藏字段包含在内?

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)