如何验证模型字段标题?例如,如果标题字段的每次使用都以“博客”一词开头。
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'
答案 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