Royal
Royal

Reputation: 752

How to validate number in django

I am learning Django,looked into django validation but the below type i want.searched in google no result.

In my app,their are two character fields,i want it to be validate so that the conditons are,

1.Either any one of the field is entered.

2.It should validate the entered data are integer.

that means,both fields are not mandatory,but any one is mandatory and that mandatory field should accept number only.

How to do it in django.

Upvotes: 1

Views: 2339

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34563

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 return None 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't None. If neither value is found, the ValidationError will be raised.

Hope that helps you out.

Upvotes: 2

Related Questions