0

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

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'
4

1 回答 1

0

验证器.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)

表格.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

视图.py

class BlogCreateView(CreateView):
    model = Blog
    action = 'created'
    form_class = BlogForm
于 2013-02-11T05:16:06.753 回答