本节内容:

1:Model

2:Form

3:Model

 

http://www.cnblogs.com/wupeiqi/articles/6144178.html  武sir:Form组件
http://www.cnblogs.com/wupeiqi/articles/6216618.html  武sir:Model
http://www.cnblogs.com/wupeiqi/articles/6229414.html  武sir:ModelForm

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()   ####执行clean的方法验证 
        except ValidationError as e:
            errors = e.update_error_dict(errors)  ###如果错误,把错误添加到errors中

        # Run unique checks, but only for fields that passed validation.
        if validate_unique:
            for name in errors:
                if name != NON_FIELD_ERRORS and name not in exclude:
                    exclude.append(name)
            try:
                self.validate_unique(exclude=exclude)
            except ValidationError as e:
                errors = e.update_error_dict(errors)

        if errors:   ###如果有错误,就直接报错了,so 我们要自己去views视图中去判断,try
            raise ValidationError(errors)
View Code

相关文章:

  • 2021-11-04
  • 2021-12-05
  • 2022-12-23
  • 2021-08-17
  • 2022-12-23
  • 2021-11-22
  • 2021-08-21
猜你喜欢
  • 2021-10-07
  • 2022-12-23
  • 2022-12-23
  • 2022-01-22
  • 2019-12-05
  • 2021-10-27
  • 2022-12-23
相关资源
相似解决方案