Jay
Jay

Reputation: 770

Django Forms - Can't raise validation error in tests

I'm struggling to get my tests to throw a form validation error in Django. This is using standard/default input types.

# forms.py
class NewUserForm(forms.Form):
    first_name = floppyforms.CharField(widget=floppyforms.TextInput(attrs={'class': 'form-control input-lg', 'placeholder': 'First Name'})),
    last_name = floppyforms.CharField(widget=floppyforms.TextInput(attrs={'class': 'form-control input-lg', 'placeholder': 'Last Name'})),
    email = forms.EmailField(),
    mobile = floppyforms.CharField(
        required=False,
        widget=floppyforms.TextInput(attrs={'class': 'form-control input-lg', 'placeholder': 'Mobile number', 'autocomplete': 'false'})),
    postcode = floppyforms.CharField(widget=floppyforms.TextInput(attrs={'class': 'form-control input-lg', 'placeholder': 'Postcode'})),
    super_balance = floppyforms.CharField(widget=floppyforms.RangeInput(attrs={'class': 'bar', 'type': 'range', 'id': 'rangeinput',
                                                                               'value': '492500', 'min': '75000', 'max': '1000000',
                                                                               'step': '5000', }))

# tests.py
class NewUserFormTest(TestCase):
    def setUp(self):
        self.valid_data = {
            'first_name': 'herp',
            'last_name': 'derp',
            'email': '[email protected]',
            'mobile': '0412345678',
            'postcode': '00000',
            'relationship_status': 'S',
            'super_balance': '100000',
            'current_super_provider': '49'
        }

...
    def test_invalid_fields(self):
        form = NewUserForm({})
        self.assertFalse(form.is_valid()) # correct
        data = self.valid_data
        data['email'] = 24234 # this field should fail
        form = NewUserForm(data)
        form.is_valid() # returns True

When I pass a blank dictionary to the initial form. form.errors displays {'super_balance': ['This field is required.']}. This is more confusing because the documentation states that unless explicitly declared then all fields are assumed to be required.

I'm using 1.8.5

Cheers in advance

Upvotes: 1

Views: 424

Answers (1)

Alasdair
Alasdair

Reputation: 308779

You need to remove the trailing commas from all the fields in your form.

Instead of

class NewUserForm(forms.Form):
    ...
    email = forms.EmailField(),
    ...

it should be

class NewUserForm(forms.Form):
    ...
    email = forms.EmailField()
    ...

At the moment, NewUserForm.email is a tuple, not a field, so any values for that field in the data dictionary are ignored. The only field without the trailing comma is super_balance, which is why it is the only error that appears when you pass a blank dictionary to the form.

Upvotes: 2

Related Questions