How do I validate data on model layer in Django without modelform? Do I have to override some functions? Suppose I have a CharField in a model class, what function should I override to validate input's data type?
I'm new to django. Sorry if the question is not specific.
You can add validators to your model fields: https://docs.djangoproject.com/en/1.8/ref/validators/#writing-validators From the docs:
from django.db import models
from django.core.exceptions import ValidationError
def validate_even(value):
if value % 2 != 0:
raise ValidationError('%s is not an even number' % value)
class MyModel(models.Model):
even_field = models.IntegerField(validators=[validate_even])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With