在Django中为字符字段添加自定义验证

时间:2016-02-23 09:49:31

标签: python django django-models django-forms

假设我在模型中定义了一个字符字段 -

class model_name(models.Model):
    name = models.CharField()

我想验证某些特定名称的名称条目,例如 -

name_list = ['foo', 'bar']

我怎样才能实现这个目标?

2 个答案:

答案 0 :(得分:1)

您可以在表单中定义自定义clean_name方法。例如

......
def clean_name(self):
    name_list = ['foo', 'bar']
    cd = self.cleaned_data
    if cd['name'] not in name_list:
        raise forms.ValidationError('Name is not in the list.')
    return cd['name']

答案 1 :(得分:1)

您必须按照https://docs.djangoproject.com/es/1.9/ref/models/fields/#choices

中的说明设置参数choices

那里的例子:

from django.db import models

class Student(models.Model):
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    SENIOR = 'SR'
    YEAR_IN_SCHOOL_CHOICES = (
        (FRESHMAN, 'Freshman'),
        (SOPHOMORE, 'Sophomore'),
        (JUNIOR, 'Junior'),
        (SENIOR, 'Senior'),
    )
    year_in_school = models.CharField(max_length=2,
                                      choices=YEAR_IN_SCHOOL_CHOICES,
                                      default=FRESHMAN)

    def is_upperclass(self):
        return self.year_in_school in (self.JUNIOR, self.SENIOR)