【问题标题】:How to set value on forms.ChoiceField in django view?如何在 django 视图中设置 forms.ChoiceField 的值?
【发布时间】:2020-10-01 11:34:37
【问题描述】:

这是我的表格:

class ch_form(forms.Form):
    ch_field = forms.ChoiceField(
        required=True , label= 'ch_field : ' , 
    )

这是我的观点:

def testView(request):
    form = ch_form(
                initial={
                    'ch_field':[
                        (1, 'test1'),
                        (2, 'test2'),
                        (3, 'test3'),
                    ]
                }
            )

但它不起作用。 所以我的问题是如何在运行时在视图函数中设置forms.ChoiceField 的值。

对不起,我的英语不好。

【问题讨论】:

    标签: python django django-forms django-views


    【解决方案1】:

    您可以尝试在__init__() 方法中设置选项,可能是这样的:

    class MyForm(forms.Form):
        ch_field = forms.ChoiceField(
            required=True,
            label= 'ch_field')
    
        def __init__(self, *args, **kwargs):
            my_choices = kwargs.pop('my_choices')
    
            super().__init__(*args, **kwargs)
    
            self.fields['ch_field'].choices = my_choices
    

    然后这样称呼它:

    def testView(request):
        form = MyForm(
            my_choices=[
                (1, 'test1'),
                (2, 'test2'),
                (3, 'test3'),
            ],
            initial={
                'ch_field': 2,
            })
    

    【讨论】:

      猜你喜欢
      • 2010-10-14
      • 1970-01-01
      • 2020-06-18
      • 2011-08-20
      • 1970-01-01
      • 2023-02-10
      • 2013-11-15
      • 2012-08-01
      • 2017-03-04
      相关资源
      最近更新 更多