0

我得到了ModelForm一些创建字段的 ajax 操作,例如:

<input type="hidden" name="myfield" value="1" />
<input type="hidden" name="myfield" value="2" />

我很好地将这些数据保存为ManyToManyusing 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'])

那么现在,如何将每个 of 包含other_models__init__隐藏字段?

4

1 回答 1

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)
于 2013-11-11T02:56:58.970 回答