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])