Michael Platt Michael Platt - 1 year ago 206
Python Question

Django form unittest with ChoiceField and MultipleChoiceField failing is_valid()

I'm running into a small problem with writing a unit test for a Django form. I really just want to check the is_valid() method and have seen examples but my code isn't working and after a day or so of reading up on Google I've yet to find the answer I'm looking for. Below is the code for the forms.py and 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:
bands = SatelliteBand.objects.all()
bands_value = []
for band in bands:
form_data = {'result_type': results_value, 'band_selection': bands_value, 'title': 'a title', 'description': 'some description'}
form = DataSelectForm(data = form_data)



The only thing I get when I run the test case is "AssertionError: False is not true" I understand the error, just not why I'm getting it. I'm passing in all the data and I can see it when I run the print statements. I've tried taking the result_type and band_selection and passing it into the constructor instead of it being a part of the form_data but that didn't work either. What am I missing?

Answer Source

You need to pass result_list and band_list when you construct your form.

# 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)

If you don't pass the values to the form, then you don't set the choices for the fields. If the fields don't have any choices, then the values in the data dict cannot be valid, so the form will always be invalid.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download