Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data validation on model layer?

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.

like image 462
Brian Avatar asked Oct 16 '25 10:10

Brian


1 Answers

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])
like image 174
Kit Sunde Avatar answered Oct 19 '25 00:10

Kit Sunde