我想在Django views.py而不是forms.py中创建表单字段

时间:2017-07-17 13:53:39

标签: python django forms django-forms

我在Form.py中创建我的表单,如下所示:

class pdftabelModelForm(forms.ModelForm):
    class Meta:
        model = pdftabel_tool_
        fields = ['apn', 'owner_name']
    apn = forms.ModelChoiceField(queryset= Field.objects.values_list('name', flat=True), empty_label="(Choose field)")
    owner_name = forms.ModelChoiceField(queryset= Field.objects.values_list('name', flat=True), empty_label="(Choose field)")

但由于某些原因,例如“自我”和“自我”。在form.py中不可用。我只能在views.py中访问它。所以我想让它像

   class FieldForm(ModelForm):
    class Meta:
        model = pdftabel_tool_
        fields = (
            'apn',
            'owner_name',)

如何将这些字段设为下拉状态,就像我在forms.py中一样?

1 个答案:

答案 0 :(得分:1)

为什么要在views.py中进行此操作? forms.py是执行此操作的合适位置。

您应该使用表单的__init__方法覆盖字段的查询集,而不是重新定义字段,如下所示:

class pdftabelModelForm(forms.ModelForm):
    class Meta:
        model = pdftabel_tool_
        fields = ['apn', 'owner_name']

    def __init__(self, *args, **kwargs):
        super(pdftabelModelForm, self).__init__(*args, **kwargs)
        self.fields['apn'].queryset = X
        self.fields['owner_name'].queryset = X

编辑:如果您需要将额外的参数传递给表单,请将init方法更新为:

    def __init__(self, *args, **kwargs):
        self.layer_id = self.kwargs.pop('layer_id')
        super(pdftabelModelForm, self).__init__(*args, **kwargs)
        self.fields['apn'].queryset = X
        self.fields['owner_name'].queryset = X

当您从views.py初始化表单时,传递参数:

form = pdftableModelForm(layer_id=X)