2

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

1 回答 1

3

在模型文件中但在类声明之外(示例 2)声明验证方法应该可以正常工作

如果您在另一个文件中使用该函数而不首先导入该方法,您可能会收到 NameError

于 2013-09-03T20:33:08.207 回答