繁体   English   中英

如何在 Django 视图中的 forms.ChoiceField 上设置值?

[英]How to set value on forms.ChoiceField in django view?

这是我的表格:

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设置值。

对不起,我的英语不好。

您可以尝试在__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,
        })

暂无
暂无

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

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