Reputation: 994
I am trying to use custom validation on a Django CharField model field. I'm checking whether the name has number in it. If it does, raise a ValidationError
. I use the line if name.isalpha() is False: raise ValidationError
. For some reason this equates to False whether there is a number present in the string or not. I checked to make sure that name
was the value I was expecting it to be and that it was indeed a string. Here is my code:
models.py
name = models.CharField(validators=[validate_name], max_length=100, default='', unique=True)
validation.py
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
def validate_name(name):
print(name.isalpha())
if name.isalpha is False:
raise ValidationError(
_('Name can only contain letters A-Z. Not numbers.'),
params={'name': name},
)
Upvotes: 0
Views: 311
Reputation: 1909
change to
if name.isalpha() is False:
raise ValidationError(
_('Name can only contain letters A-Z. Not numbers.'),
params={'name': name},
)
Besides you could use the RegexValidator to save some lines of code
from django.core.validators import RegexValidator
letters_only = RegexValidator(r'^[a-zA-Z ]*$', _('Only letters are allowed.'))
Upvotes: 1