Form表单验证(进阶)

#  -----------------Form表单的钩子函数------------------

  #  全局钩子函数

#   重新父类的clean方法可以做到全局验证,因为form组件校验字段时都会执行一次clean()方法
    def clean(self):
        ''''''
        for k,v in self.cleaned_data.items():
            print(k,v)
            if re.search(r'haha', str(v)):
                # 将错误信息添加到self.__errors中
                self.add_error('错误信息',ValidationError('信息中包含haha 不合法'))
        return self.cleaned_data

  #  局部钩子函数

#   当每个字段调用完clean()方法时还会 调用hasattr(clean_%s,字段名)

#  添加新方法 def clean_字段名(self)
    def clean_username(self):
        '''校验成功则返回成功后的用户名, 失败则将错误信息添加到_errors字典中  等同于返回None
            然后cleaned__data中对应字段的数据会变为 cleaned_data[字段名] = None
        '''
        username = self.cleaned_data.get('username')
        if username.startswith('s'):
            self.add_error('username', ValidationError('用户名不能以s开头')) # 不写return 相当于返回None
        else:
            return username (或者 新的值)

# 个人想法:感觉局部钩子和自定义一个校验函数的功能是一样的  用哪个都可以达到效果

# ORM中把一个对象转换成字典格式

from django.forms import model_to_dict

book_obj = models.Book.objects.filter(id=edit_id).first()
book_dict = model_to_dict(book_obj)


 

猜你喜欢

转载自www.cnblogs.com/liubailiang/p/11470754.html