简体   繁体   English

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

[英]I want to create form fields in Django views.py rather then forms.py

I am creating my form in Form.py like this: 我在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)")

But due to some reasons like 'self' is not available in form.py. 但是由于某些原因,例如form.py中无法使用“ self”。 I can only access it in views.py. 我只能在views.py中访问它。 So I want to make it like 所以我想让它像

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

How can I make these fields as dropdown like I did in my forms.py? 如何像在forms.py中一样将这些字段设置为下拉列表?

Why are you set on doing it in views.py? 为什么要在views.py中进行设置? forms.py is the appropriate place to do this. forms.py是执行此操作的适当位置。

Instead of redefining your fields, you should use the form's __init__ method to override the querysets for your fields, like so: 与其重新定义字段, __init__使用表单的__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

EDIT: if you need to pass extra parameters to your form, update the init method to this: 编辑:如果您需要将额外的参数传递到您的窗体,将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

And when you initialize your form from views.py, pass the parameter: 当您从views.py初始化表单时,传递参数:

form = pdftableModelForm(layer_id=X)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM