Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put validator for Django model field?

The Django documentation shows an example of a custom validator for a model field. However the doc doesn't say where to put the validator function in your code. If I put it in my models.py file in either location (as shown below), I get this error when I try to start the server:

NameError: name 'validate_name' is not defined

Where is the right location for this validate_name function? Thanks.

# models.py, example 1
from django.db import models
from django.core.exceptions import ValidationError

class CommentModel(models.Model):
    # I get the error if I define the validator here
    def validate_name(value):
        if value == '':
            raise ValidationError(u'%s cannot be left blank' % value)

    name = models.CharField(max_length=25, validators=[validate_name])


# models.py, example 2
from django.db import models
from django.core.exceptions import ValidationError

# I also get the error if I define the validator here
def validate_name(value):
    if value == '':
        raise ValidationError(u'%s cannot be left blank' % value)

class CommentModel(models.Model):
    name = models.CharField(max_length=25, validators=[validate_name])
like image 648
Jim Avatar asked Oct 24 '25 05:10

Jim


1 Answers

declaring your validation method within your models file but outside your class declaration (example 2) should work fine

you may be getting a NameError if you're using the function within another file without importing the method first

like image 141
jbr3zy Avatar answered Oct 27 '25 00:10

jbr3zy