Django 表单单元测试与 ChoiceField 和 MultipleChoiceField 失败 is_valid()

Django form unittest with ChoiceField and MultipleChoiceField failing is_valid()

我 运行 在为 Django 表单编写单元测试时遇到了一个小问题。我真的只想检查 is_valid() 方法并看过示例,但我的代码无法正常工作,在阅读 Google 大约一天后我还没有找到答案正在寻找。下面是 forms.py 和 test_forms.py

的代码

forms.py

class DataSelectForm(forms.Form):
    #these are done in the init funct.
    result_type = forms.ChoiceField(widget=forms.Select(attrs={'class': 'field-long'}))
    band_selection = forms.MultipleChoiceField(widget=forms.SelectMultiple(attrs={'class': 'multiselect field-long'}))
    title = forms.CharField(widget=forms.HiddenInput())
    description = forms.CharField(widget=forms.HiddenInput())

    def __init__(self, result_list=None, band_list=None, *args, **kwargs):
        super(DataSelectForm, self).__init__(*args, **kwargs)
        if result_list is not None and band_list is not None:
            self.fields["result_type"] = forms.ChoiceField(choices=result_list, widget=forms.Select(attrs={'class': 'field-long'}))
            self.fields["band_selection"] = forms.MultipleChoiceField(widget=forms.SelectMultiple(attrs={'class': 'multiselect field-long'}), choices=band_list

test_forms.py

 def test_data_select_form(self):
        results = ResultType.objects.all()
        results_value = []
        for result in results:
            results_value.append(result.result_type)
        bands = SatelliteBand.objects.all()
        bands_value = []
        for band in bands:
            bands_value.append(band.band_name)
        form_data = {'result_type': results_value, 'band_selection': bands_value, 'title': 'a title', 'description': 'some description'}
        form = DataSelectForm(data = form_data)

        print(form['title'].value())
        print(form['description'].value())
        print(form['result_type'].value())
        print(form['band_selection'].value())

        self.assertTrue(form.is_valid())

当我 运行 测试用例时,我唯一得到的是 "AssertionError: False is not true" 我理解错误,只是不知道为什么我会得到它。我正在传递所有数据,当我 运行 打印语句时我可以看到它。我试过使用 result_type 和 band_selection 并将其传递给构造函数,而不是将其作为 form_data 的一部分,但这也不起作用。我错过了什么?

您在构建表单时需要传递 result_listband_list

# These aren't the actual choices you want, I'm just showing that
# choices should be a list of 2-tuples.
result_list = [('result1', 'result1'), ('result2', 'result2'), ...]
band_list = [('band1', 'band1'), ('band2', 'band2'), ...]

DataSelectForm(result_list=result_list, band_list=band_list, data=form_data)

如果您不将值传递给表单,则不会为字段设置选项。如果字段没有任何选择,则 data dict 中的值无效,因此表单将始终无效。