我在为Django表单编写单元测试时遇到了一个小问题。我真的只想检查is_valid()方法并看过示例,但我的代码无法正常工作,在Google上阅读一天左右之后我还没有找到我正在寻找的答案。下面是forms.py和test_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
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不正确”我理解错误,而不是为什么我得到它。我传递了所有数据,我可以在运行print语句时看到它。我已尝试将result_type和band_selection传递给构造函数,而不是将其作为form_data的一部分,但这也不起作用。我错过了什么?
答案 0 :(得分:2)
构建表单时,您需要传递result_list
和band_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中的值无效,因此表单始终无效。