我努力让我的测试在Django中抛出表单验证错误。这是使用标准/默认输入类型。
# 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': 'herp@derp.com',
'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
当我将空白字典传递给初始表单时。 form.errors
显示{'super_balance': ['This field is required.']}
。这更令人困惑,因为文档说明除非明确声明,否则假定所有字段都是必需的。
我使用1.8.5
提前干杯
答案 0 :(得分:2)
您需要从所有表单中的字段中删除尾随逗号。
而不是
class NewUserForm(forms.Form):
...
email = forms.EmailField(),
...
应该是
class NewUserForm(forms.Form):
...
email = forms.EmailField()
...
目前,NewUserForm.email
是元组,而不是字段,因此忽略数据字典中该字段的任何值。唯一没有尾随逗号的字段是super_balance
,这就是为什么它是将空白字典传递给表单时出现的唯一错误。