Django: Form Validation For Accepting Strings With First Letter In Caps
I have a model form defined in my application, and in one of my form fields, I want the users to enter their inputs, but with the first letter of their inputs in capital. If that's
Solution 1:
from django.db import models
from django.core.exceptions import ValidationError
defvalidate_capitalized(value):
if value != value.capitalize():
raise ValidationError('Invalid (not capitalized) value: %(value)s',
code='invalid',
params={'value': value})
classMyModel(models.Model):
name = models.CharField(max_length=50, validators=[validate_capitalized])
You can customize ValidationError for your needs. Docs: validators, ValidationError.
Solution 2:
You could use validators on the form or model fields, see the Documentation: Using validators and Writing validators.
Reference a simple callable that does the check and raise an exception.
Post a Comment for "Django: Form Validation For Accepting Strings With First Letter In Caps"