Python 如何在django视图中设置forms.ChoiceField的值?

Python 如何在django视图中设置forms.ChoiceField的值?,python,django,django-forms,django-views,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':[

这是我的表格:

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'),
                    ]
                }
            )
但这不是工作。 所以我的问题是如何在运行时设置视图中函数的值


对不起,我的英语不好。

您可以尝试在表单
\uuu init\uuu()
方法中设置选项,可能如下所示:

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,
        })
然后这样称呼它:

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,
        })