当前位置: 动力学知识库 > 问答 > 编程问答 >

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.

网友答案:
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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: