本节内容:
1:Model https://www.cnblogs.com/shuai1991/p/10844662.html
2:Form https://www.cnblogs.com/shuai1991/p/10763508.html https://www.cnblogs.com/shuai1991/p/10766649.html
3:ModelForm https://www.cnblogs.com/shuai1991/p/10852254.html
Model ==> 强大的数据库操作,弱小的数据验证。
Form ==>强大的数据验证
ModelForm ===>二者结合,强大的数据验证,适中的数据库操作。在ModelForm是能够封装一个model对象。
1:Model
对于Model来说,他的验证是需要自己去创建一个model对象,然后去进行判断
model: 针对单一字段 :full_clean 针对多个的字段: clean full_clean -- >字段正则判定 -- >clean方法(钩子) 他是没有最终产物
views:
def fm(request): obj = models.News(title='root') ##full_clean就进行了验证,如果要是有errors的话,就直接报错,所以在进行验证的时候,我们要自己做try判断 obj.full_clean() ##进行model的验证。里面的def clean 方法 obj.save() ##报错 django.core.exceptions.ValidationError: {'__all__': ['title不能是root']} return render(request,"form.html",locals())
models:
from django.db import models from django.core.exceptions import ValidationError class News(models.Model): title = models.CharField(max_length=32) ##验证错误会输出到errors中去 def clean(self): if self.title == "root": raise ValidationError("title不能是root")
model的源码分析:
def full_clean(self, exclude=None, validate_unique=True): """ Call clean_fields(), clean(), and validate_unique() on the model. Raise a ValidationError for any errors that occur. """ errors = {} if exclude is None: exclude = [] else: exclude = list(exclude) try: self.clean_fields(exclude=exclude) ####执行单个字段的验证 except ValidationError as e: errors = e.update_error_dict(errors) # Form.clean() is run even if other validation fails, so do the # same with Model.clean() for consistency. try: self.clean() #