django-form and fields validation

参考资料

清除数据与表单验证

清除数据时会进行表单验证。 在表格处理时有三种clean方法可调用,通常是在对表单调用is_valid()时执行。
clean响应:一般有两种结果,如果处理的数据有问题,则抛出ValidationError错误信息;若是正常,则会返回一个类型为python对象的规范化data

  • 在field子类的clean方法,此方法返回干净的数据,然后插入到表单的cleaned_data字典中。
  • clean_() 方法在表单子类上调用。其中fieldname由表单字段名替代,此方法不返回任何参数。若查找self.cleaned_data字段中的值,记住这是一个python对象类型。
  • 表单验证流程:
    1. 对于form中的字段,按照顺序运行Field.clean方法
    2. 运行clean_()
    3. 最后,无论之前两步是否抛出了错误,都将执行Form.clean()方法。

在实践中运用验证

using validators

我们可以自定义form field,验证输入字符串是否符合预设值规范,比如说是电子邮件地址类型。

from django import forms
from django.core.validators import validate_emailclass MultiEmailField(forms.Field):def to_python(self, value):"""Normalize data to a list of strings."""# Return an empty list if no input was given.if not value:return []return value.split(',')def validate(self, value):"""Check if value consists only of valid emails."""# Use the parent's handling of required fields, etc.super(MultiEmailField, self).validate(value)for email in value:validate_email(email)

然后我们可以创建一个简单的函数来使用自定义field

class ContactForm(forms.Form):subject = forms.CharField(max_length=100)message = forms.CharField()sender = forms.EmailField()recipients = MultiEmailField()cc_myself = forms.BooleanField(required=False)

当在form中调用is_valid()方法时,自动使用了我们自定义的MultiEmailField()方法,它将作为clean过程中的一部分执行。

cleaning and validating fields that depend on each other

当我们同时验证多个字段时,表单的form.clean()方法是个很好的选择。

It's important to keep the field and form difference clear when working out where to validate things. Fields are single data points, forms are a collection of fields.
By the time the form's clean() method is called, all the individual field clean methods will have been run (the previous two sections), so self.cleaned_data will be populated with any data that has survived so far. So you also need to remember to allow for the fact that the fields you are wanting to validate might not have survived the initial individual field checks.

有两种方法可以抛出该过程中出现的error.

第一种

在此过程中抛出的错误,我们可以用clean()方法中提供的ValidationError,令其在窗口顶部显示错误。如:

from django import formsclass ContactForm(forms.Form):# Everything as before....def clean(self):cleaned_data = super(ContactForm, self).clean()cc_myself = cleaned_data.get("cc_myself")subject = cleaned_data.get("subject")if cc_myself and subject:# Only do something if both fields are valid so far.if "help" not in subject:raise forms.ValidationError("Did not send for 'help' in the subject despite ""CC'ing yourself.")

在示例代码中对 super(ContactForm, self).clean() 的调用,确保可以实现父类中的所有验证逻辑。

第二种

可以将error信息分配给一个指定field。
Form.add_error(field, error)
这种方法允许从 Form.clean() 方法内的特定字段添加错误,或者从外部添加错误;例如在视图中。
但在开发环境中,我们要小心这种方式可能产生的输出格式混乱,修改了上面代码如下:

from django import formsclass ContactForm(forms.Form):# Everything as before....def clean(self):cleaned_data = super(ContactForm, self).clean()cc_myself = cleaned_data.get("cc_myself")subject = cleaned_data.get("subject")if cc_myself and subject and "help" not in subject:msg = "Must put 'help' in subject when cc'ing yourself."self.add_error('cc_myself', msg)self.add_error('subject', msg)

请注意,Form.add_error() 会自动从 cleaned_data 中删除相关字段

Form.errors

访问 errors 属性以获取错误消息的字典。注意这里的错误消息是dict形式传出,但某个字段可以有多个error,故错误信息存储在列表list中。

Form.errors.as_json(escape_html=False)

返回序列化为JSON的错误信息。

>>> f.errors.as_json()
{"sender": [{"message": "Enter a valid email address.", "code": "invalid"}],
"subject": [{"message": "This field is required.", "code": "required"}]}

By default, as_json() does not escape its output. If you are using it for something like AJAX requests to a form view where the client interprets the response and inserts errors into the page, you'll want to be sure to escape the results on the client-side to avoid the possibility of a cross-site scripting attack. It's trivial to do so using a JavaScript library like jQuery - simply use $(el).text(errorText) rather than .html().

默认情况下,as_json()不会转义输出。如果你处理从表单来的AJAX请求,客户端解释这个响应并在页面中插入错误信息。你需要确保在不遭受XSS攻击的情况下转义结果。如果使用JavaScript库(如jQuery)这样实现很简单 - 只需使用 $(el).text(errorText),而不是 .html()。

Accessing the fields from the form

Form.fields
如何从字段访问表单呢?

You can access the fields of Form instance from its fields attribute

>>> for row in f.fields.values(): print(row)
...
<django.forms.fields.CharField object at 0x7ffaac632510>
<django.forms.fields.URLField object at 0x7ffaac632f90>
<django.forms.fields.CharField object at 0x7ffaac3aa050>
>>> f.fields['name']
<django.forms.fields.CharField object at 0x7ffaac6324d0>

我们也可修改 Form 实例的字段参数,以更改其在表单中显示的方式

>>> f.as_table().split('\n')[0]
'<tr><th>Name:</th><td><input name="name" type="text" value="instance" required /></td></tr>'
>>> f.fields['name'].label = "Username"
>>> f.as_table().split('\n')[0]
'<tr><th>Username:</th><td><input name="name" type="text" value="instance" required /></td></tr>'

Accessing "clean" data(The resources:https://docs.djangoproject.com/en/2.0/ref/forms/api/#accessing-clean-data)

Form 类中的每个字段不仅负责验证数据,还负责“清理"它 "- 将其标准化为一致的格式。这是一个很好的功能,因为它允许以各种方式输入特定字段的数据,转换为一致类型的输出。

For example, ~django.forms.DateField normalizes input into a Python datetime.date object. Regardless of whether you pass it a string in the format '1994-07-15', a datetime.date object, or a number of other formats, DateField will always normalize it to a datetime.date object as long as it's valid.

一旦您创建了一个具有一组数据并验证它的 Form 实例,您可以通过其 cleaned_data 属性访问干净的数据:

>>> data = {'subject': 'hello',
...         'message': 'Hi there',
...         'sender': 'foo@example.com',
...         'cc_myself': True}
>>> f = ContactForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data
{'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}

在这里,任何文本输入的字段,如EmailField,CharField都会将输入数据clean为标准字符串类型。

转载于:https://www.cnblogs.com/dion-90/p/8443506.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/414701.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

1、vue 笔记之 组件

1、组件个人理解&#xff1a; <组件>是页面的一部分&#xff0c;将界面切分成部分&#xff0c;每部分称为 <组件>2、组件化思想&#xff1a; //2.1、定义一个全局的组件&#xff0c;组件支持‘驼峰命名’规则Vue.component("TodoItem",{props: [content]…

工作236:点击直接进入

<div class"container"><!-- <el-radio-group v-model"mode">--><div><!-- <el-radio-button class"login-btn" label"0">营销端</el-radio-button>--><el-button class"login-b…

java spring框架使用实例demo

首先导入spring的jar包 1、创建web项目&#xff0c;创建spring.xml文件 注&#xff1a;base-package即是包名 spring.xml详情&#xff1a; <?xml version"1.0" encoding"UTF-8"?> <!-- 查找最新的schemaLocation 访问 http://www.springfram…

语料库

http://blog.sina.com.cn/s/blog_66dfbcca0100r3ex.html转载于:https://www.cnblogs.com/lhuser/p/8445287.html

工作237:vuex取值

1获取vuex的取值 /*通过vuex的状态去判断现在所处的业务端还是营销端*/computed:{/*取出对应的业务端和营销端的内容*/Mode(){return this.$store.state.mode}}, 2直接赋值 task_business_module(){getAction(/task/task_business_module).then(res > {this.menus res.da…

2、Flutter 填坑记录篇

1、前言 之前写了一篇文章关于 flutter 初体验的一篇&#xff0c;https://www.cnblogs.com/niceyoo/p/9240359.html&#xff0c;当时一顿骚操作&#xff0c;然后程序就跑起来了。 隔了好一段时间&#xff0c;换了个电脑&#xff0c;重新装了个AndroidStudio&#xff0c;继续搭建…

为何setRequestMethod(GET)不生效

在上传文件时&#xff0c;想使用setRequestMethod&#xff08;“GET”&#xff09;。结果无效 因为需要使用输出流上传文件&#xff0c;而使用输出流时&#xff0c;HttpURLConnection默认使用post请求。是无法更改的 conn.setDoOutput(true); //允许输出流 与 conn.setR…

工作238:Vue.js中this.$nextTick()的使用

this.$nextTick()将回调延迟到下次 DOM 更新循环之后执行。在修改数据之后立即使用它&#xff0c;然后等待 DOM 更新。它跟全局方法 Vue.nextTick 一样&#xff0c;不同的是回调的 this 自动绑定到调用它的实例上。 假设我们更改了某个dom元素内部的文本&#xff0c;而这时候我…

拉勾网大数据相关岗位数据爬虫分析

拉勾网大数据相关招聘数据分析 观察对象&#xff1a;大数据相关岗位的招聘数据 观察时间&#xff1a;2016.3.28 数据来源&#xff1a;拉勾网 1、分析目的 眼下&#xff0c;大数据是一个非常热门的话题。受到非常多人的关注和追捧。其创造的相关职业也受到大家的青睐。但大数据相…

3、Finished with error: FormatException: Bad UTF-8 encoding 0xc3 (at offset 169)

这是由于 app 的版本为 release 找不到 keystore 文件&#xff0c; 我们只需要在 app 下的 build.gradle 文件中修改为 signingConfigs.debug 即可&#xff1a; buildTypes {release {signingConfig signingConfigs.debugproguardFiles getDefaultProguardFile(proguard-androi…

plsql 弹出 register,plsql注册码

注册码&#xff1a; Product Code&#xff1a;4t46t6vydkvsxekkvf3fjnpzy5wbuhphqz serial Number&#xff1a;601769 password&#xff1a;xs374ca https://blog.csdn.net/ma141982/article/details/76154919/

2018--20179215--《文献管理与信息分析》第三讲 英文数据库资源的发展趋势和利用...

《文献管理与信息分析》第三讲 英文数据库资源的发展趋势和利用 一、科研相关的文献资源有以下十大来源&#xff1a; 专利、会议论文、期刊、学位论文、科技报告、科技档案、产品资料、政府出版物、标准文献、图书。 二、数据库的使用 1.不同搜索引擎的差异&#xff1a; 覆盖的…

工作239:内容过长省略号失败 直接改的样式表

给元素加入以下样式&#xff1a; white-space:nowrap;overflow:hidden; text-overflow:ellipsis; 此外&#xff0c;还要注意给元素加上宽度&#xff1a; width:100px;

4、Flutter 采坑记录篇二_依赖库不兼容

1、报错信息 Because every version of flutter_test from sdk depends on package_resolver 1.0.4 which depends on http ^0.11.0, every version of flutter_test from sdk requires http ^0.11.0.And because cached_network_image >0.5.0 depends on flutter_cache_man…

Android身份证识别demo,文字识别

百度云链接&#xff1a;https://console.bce.baidu.com/?fromai1#/aip/overview 1、1首先去百度文字识别创建应用&#xff0c;获取ak和sk 配置ak和sk 1、2 jniLibs文件夹复制过去 2、识别身份证信息方法&#xff1a; /**** 解析身份证图片** param idCardSide 身份证正反面*…

jq消除网页滚动条

网页有些时候需要能滚动的效果&#xff0c;但是不想要滚动条&#xff0c;我就遇到了这样的需求。自己用jq写了一个垂直滚动条。 纯css也可以实现 .box::-webkit-scrollbar{display:none} 但是edge和Firefox不兼容&#xff0c;自己想了一下只要监听滚轮事件&#xff0c;用jq写应…

5、Flutter 实现 ViewPager、bottomNavigationBar 界面切换

1、前言 首先我们想一下&#xff0c;如果在 Android 中实现 布局切换&#xff0c;通常的思路是&#xff1a; 做一个 viewpager一组 Fragment每个 Fragment 绑定一个 xml最后填充至 viewpager2、Flutter 实现 上边提到的用安卓原生做&#xff0c;思路是很明确&#xff0c;但是代…

Android 应用内实现导航页面,接入百度SDK内置导航,高德SDK内置导航

1、首先到百度地图开放平台创建应用&#xff0c;获取应用AK http://lbsyun.baidu.com/apiconsole/key 2、到百度语言平台创建应用&#xff0c;获取Secret Key和语言APP ID http://yuyin.baidu.com/app 3、到百度地图开放平台下载Android 导航SDK https://pan.baidu.com/s/1z…

Python高级用法总结

Python很棒&#xff0c;它有很多高级用法值得细细思索&#xff0c;学习使用。本文将根据日常使用&#xff0c;总结介绍Python的一组高级特性&#xff0c;包括&#xff1a;列表推导式、迭代器和生成器、装饰器。 列表推导&#xff08;list comprehensions&#xff09; 场景1&…

工作241:判断数组里面是否有某个值

<el-form class"left-right"><el-form-item label"分发账号名称" label-width"100px"><el-select v-model"form.index" placeholder"选择绑定的分发账号"><el-option :disabled"item.status||Ro…