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

时间:2020-10-01 11:34:37

标签: python django django-forms django-views

这是我的表格:

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

对不起,我的英语不好。

1 个答案:

答案 0 :(得分:1)

您可以尝试使用lastUpdated形式的方法来设置选择,也许是这样的:

__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
相关问题