如何在模型表单中的表单字段上创建验证器

时间:2013-02-11 05:11:33

标签: django django-class-based-views

如何验证模型字段标题?例如,如果标题字段的每次使用都以“博客”一词开头。

models.py

class TitleAbstract(models.Model):
    title = models.CharField(max_length=255)
    class Meta:
        abstract = True

class Blog(TitleAbstract):
    ..............

forms.py

class BlogForm(forms.ModelForm):
     class Meta:
         model = Blog

views.py

class BlogCreateView(CreateView):
     model = Blog
     action = 'created'

1 个答案:

答案 0 :(得分:0)

<强> validators.py

from django.core.exceptions import ValidationError

def validate_title(value):
    if not value.lower().startswith(u'blog'):
        msg = u"Enter a value starting with 'Blog'"
        raise ValidationError(msg)

<强> forms.py

class BlogForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
    super(BlogForm, self).__init__(*args, **kwargs)
    self.fields['title'].validators = [validate_title]

    class Meta:
        model = Blog

<强> views.py

class BlogCreateView(CreateView):
    model = Blog
    action = 'created'
    form_class = BlogForm