参考资料

清除数据与表单验证

清除数据时会进行表单验证。 在表格处理时有三种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_email class 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 forms

class 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 forms

class 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为标准字符串类型。

django-form and fields validation的更多相关文章

  1. django form表单验证

    一. django form表单验证引入 有时时候我们需要使用get,post,put等方式在前台HTML页面提交一些数据到后台处理例 ; <!DOCTYPE html> <html ...

  2. django: form fileupload - 1

    本节介绍 Form 中一些字段类型的使用,以文件上传字段 FileField 为例:(注,其它字段和相关用法见官方文档中的 Forms -> Built-in Fields) 一,配置 urls ...

  3. Django form模块使用心得

    最近用Django 写了一个网站,现在来分享一下对Django form 的一些心得. 一,创建一个表单 创建一个Form表单有两种方式: 第一种方式是继承于forms.Form,的一个子类,通过在f ...

  4. Python Web框架篇:Django Form组件

    Form简介 在HTTP中,表单(form标签),是用来提交数据的,其action属性说明了其传输数据的方法:如何传.如何接收. 访问网站时,表单可以实现客户端与服务器之间的通信.例如查询,就用到了表 ...

  5. Web框架django[Form]组件

    新手上路 Django的Form主要具有一下几大功能: 生成HTML标签 验证用户数据(显示错误信息) HTML Form提交保留上次提交数据 初始化页面显示内容 小试牛刀 1.创建Form类 # 创 ...

  6. 32.Django form组件

    Form组件 Django的Form主要具有一下几大功能: 生成HTML标签 验证用户数据(显示错误信息) HTML Form提交保留上次提交数据 初始化页面显示内容 创建Form类时,主要涉及到 [ ...

  7. Django form表单

    Form介绍 之前在HTML页面中利用form表单向后端提交数据时,都会写一些获取用户输入的标签并且用form标签把它们包起来.与此同时我们在好多场景下都需要对用户的输入做校验,比如校验用户是否输入, ...

  8. django Form组件

    django Form组件 Django的Form主要具有一下几大功能: 生成HTML标签 验证用户数据(显示错误信息) HTML Form提交保留上次提交数据 初始化页面显示内容 小试牛刀 1.创建 ...

  9. Django Form组件 学生管理系统

    from django.db import models # Create your models here. class Classes(models.Model): title=models.Ch ...

  10. 饮冰三年-人工智能-Python-27 Django Form组件

    Django的Form主要具有一下几大功能: 生成HTML标签 验证用户数据(显示错误信息) HTML Form提交保留上次提交数据 初始化页面显示内容 后台逻辑(导包+建类) from django ...

随机推荐

  1. BZOJ_2216_[Poi2011]Lightning Conductor_决策单调性

    BZOJ_2216_[Poi2011]Lightning Conductor_决策单调性 Description 已知一个长度为n的序列a1,a2,...,an. 对于每个1<=i<=n, ...

  2. Hadoop2 使用 YARN 运行 MapReduce 的过程源码分析

    Hadoop 使用 YARN 运行 MapReduce 的过程如下图所示: 总共分为11步. 这里以 WordCount 为例, 我们在客户端终端提交作业: # 把本地的 /home/hadoop/t ...

  3. Hadoop Shell 介绍

    以 hadoop 2.7.3 为例 bin 目录下是最基础的集群管理脚本, 用户可通过该脚本完成各种功能, 如 HDFS 管理, MapReduce 作业管理等. 作为入门, 先介绍bin 目录下的 ...

  4. intellj idea 使用

    1. 导入包快捷 Alt + Enter 2. 查看方法注释,点击进入源码即可,若想和eclipse一样鼠标停留即可出现注释提示,开启方法为: Preferences->Editor->G ...

  5. ElasticSearch基础之查询功能

    [01]查询类型: [02]基本查询和组合查询是参与打分的 1.创建映射: 注意事项:基于上面映射的创建: "type": "keyword" # 如果某个字段 ...

  6. TypeScript完全解读(26课时)_18.Mixins混入

    本节的代码在mixin.ts文件内 同时在index.ts内引入 混入就是把两个对象或者类的内容混合到一起,从而实现一些功能复用. 对象混入 js中对象的混入 先来看一个js中对象的混入的例子 首先定 ...

  7. Eclipse中建立自己的类库,给不同的工程使用

    win7 进入服务 开始 运行 services.msc 在多个工程当中,可能使用到相同的jar包,这时,如果我们建立一个自己的类库,该类库中存放着所有工程均需要的jar包,就可以免去重复导入的麻烦. ...

  8. UVaLive 3971 Assemble (水题二分+贪心)

    题意:你有b元钱,有n个配件,每个配件有各类,品质因子,价格,要每种买一个,让最差的品质因子尽量大. 析:很简单的一个二分题,二分品质因子即可,每次计算要花的钱的多少,每次尽量买便宜且大的品质因子. ...

  9. jQuery 学习笔记(一)jQuery 语法

    jQuery 是一个 JavaScript 库,极大地简化了 JavaScript 编程,很容易学习 添加 jQuery 库 <head> <script type="te ...

  10. 在CentOS6.6上以replSet方式部署MongoDB集群

    此文已由作者袁欢授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 部署方式在3台centos6.6系统上以Replica Set方式部署mongodb3.0.2集群. 官方参考 ...