美文网首页
Django表单使用校验后的数据

Django表单使用校验后的数据

作者: Chaweys | 来源:发表于2020-11-02 07:33 被阅读0次

使用校验后的数据
调用表单is_valid()方法时会执行数据校验,当所有字段数据均合法时,该方法返回True,否则返回False。
执行校验时,Django为表单对象创建了cleaned_data属性,通过校验的数据是"有效的",被保存在表单的cleaned_data属性中。
cleaned_data属性只能在执行校验之后访问,否则会触发AttributeError异常。


>>> class bound_test(forms.Form):
...     name=forms.CharField(max_length=50)
...     age=forms.IntegerField(max_value=50)
...
>>> d=bound_test({"name":"mike","age":20})

>>> d.cleaned_data
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'bound_test' object has no attribute 'cleaned_data'  【因为未提前做校验,所以报错:AttributeError异常。】

>>> d.is_valid()       【校验表单】
True
>>> d.cleaned_data     【获取被校验后的数据】
{'age': 20, 'name': 'mike'}

>>> d=bound_test({"name":"mike","age":80})
>>> d.is_valid()       【校验表单】
False
>>> d.cleaned_data     【获取被校验后的数据,因为age限制了最大值50,所以超过了50的值不被校验成功】
{'name': 'mike'}

>>> d.errors           【获取校验失败的错误信息】
{'age': ['Ensure this value is less than or equal to 50.']}

>>> d.errors.as_json() 【获取校验失败的错误信息,转成json格式】
'{"age": [{"code": "max_value", "message": "Ensure this value is less than or equal to 50."}]}'

>>> d.errors.get_json_data() 【获取校验失败的错误信息,转成json格式2】
{'age': [{'code': 'max_value', 'message': 'Ensure this value is less than or equal to 50.'}]}
>>>

相关文章

  • Django表单使用校验后的数据

  • element清除数据和校验效果

    element dialog对话框关闭后需要清除from表单的数据和校验,可以使用以下方法 方法:

  • antd from表单

    antd from表单简介及必填校验使用 一、功能 具有数据收集、校验和提交功能的表单,包含复选框、单选框、输入框...

  • Django表单使用介绍

    Django版本:2.1.3Django表单非常强大,熟悉后可以大大提高工作效率。 Django表单分为两种使用方...

  • django form表单

    使用django表单进行数据验证首先必须导入相关的包 from django import forms 然后导入相...

  • ElementUI 提交表单校验时跳转到错误位置

    我们在使用ElementUI 提交表单,会使用formEle来做表单校验,当用户输入的数据不合法时,会出现红色错误...

  • elementUI中动态表单的校验

    首先需要再data中定义表单变量 循环的表单数据 表单的校验规则如下 通过给每一个循环的表单数据添加对应的校验规则...

  • Djano获取post数据

    1.获取POST中表单键值数据 如果要在django的POST方法中获取表单数据,则在客户端使用JavaScrip...

  • Django教程--Form表单

    Django教程--Form表单 前面我们已经了解如何在django中使用GET、POST传递数据,但是我们并没有...

  • iview cdn引用过程中出现的问题

    1.表单数据校验回调函数传进去无效(与标签有关,不能使用驼峰式,否则校验后的回调函数无法进入)2.新建的组件便签不...

网友评论

      本文标题:Django表单使用校验后的数据

      本文链接:https://www.haomeiwen.com/subject/gfwsvktx.html