2👍
✅
class MyForm(forms.Form):
field_one = forms.IntegerField(required=False)
field_two = forms.IntegerField(required=False)
def clean(self):
cleaned_data = self.cleaned_data
field_one = cleaned_data.get('field_one')
field_two = cleaned_data.get('field_two')
if not any([field_one, field_two]):
raise forms.ValidationError(u'Please enter a value')
return cleaned_data
- Using an IntegerField will validate that only numeric characters are
present, covering your blank space use case. - Specifying
required=False
on both fields allows either field to be left blank. - Implementing
clean()
on the form gets you access to both fields. .get()
will returnNone
if the key isn’t found, so the use of
any([field_one, field_two])
will return true if at least one of the
values in the list isn’tNone
. If neither value is found, the
ValidationError
will be raised.
Hope that helps you out.
Source:stackexchange.com