源码文件,site-packages/django/forms/forms.py

一个form实例.

Form.errors

返回一个ErrorDict实例,包含当前表单所有的错误,可以在is_valid之前调用

Form.has_error(field, code=None)

返回指定field是否有错误

Form.add_error(field, error)

向指定field添加一个错误

Form.non_field_errors()

不属于field的错误,如数据库中有复合主键重复等.

#部分源码

@property
def errors(self):"Returns an ErrorDict for the data provided for the form"if self._errors is None:self.full_clean()return self._errors
@html_safe
@python_2_unicode_compatible
class ErrorDict(dict):"""A collection of errors that knows how to display itself in various formats.The dictionary keys are the field names, and the values are the errors."""def as_data(self):return {f: e.as_data() for f, e in self.items()}def as_json(self, escape_html=False):return json.dumps({f: e.get_json_data(escape_html) for f, e in self.items()})def as_ul(self):if not self:return ''return format_html('<ul class="errorlist">{}</ul>',format_html_join('', '<li>{}{}</li>', ((k, force_text(v)) for k, v in self.items())))def as_text(self):output = []for field, errors in self.items():output.append('* %s' % field)output.append('\n'.join('  * %s' % e for e in errors))return '\n'.join(output)def __str__(self):return self.as_ul()

#官方文档

  • Form.errors

Access the errors attribute to get a dictionary of error messages:

>>> f.errors{'sender': ['Enter a valid email address.'], 'subject': ['This field is required.']}

In this dictionary, the keys are the field names, and the values are lists of Unicode strings representing the error messages. The error messages are stored in lists because a field can have multiple error messages.

You can access errors without having to call is_valid() first. The form’s data will be validated the first time either you callis_valid() or access errors.

The validation routines will only get called once, regardless of how many times you access errors or call is_valid(). This means that if validation has side effects, those side effects will only be triggered once.

  • Form.errors.as_data()

Returns a dict that maps fields to their original ValidationError instances.

>>> f.errors.as_data(){'sender': [ValidationError(['Enter a valid email address.'])],'subject': [ValidationError(['This field is required.'])]}

Use this method anytime you need to identify an error by its code. This enables things like rewriting the error’s message or writing custom logic in a view when a given error is present. It can also be used to serialize the errors in a custom format (e.g. XML); for instance,as_json() relies on as_data().

The need for the as_data() method is due to backwards compatibility. Previously ValidationError instances were lost as soon as their rendered error messages were added to the Form.errors dictionary. Ideally Form.errors would have stored ValidationErrorinstances and methods with an as_ prefix could render them, but it had to be done the other way around in order not to break code that expects rendered error messages in Form.errors.

  • Form.errors.as_json(escape_html=False)

Returns the errors serialized as 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().

If for some reason you don’t want to use client-side escaping, you can also set escape_html=True and error messages will be escaped so you can use them directly in HTML.

  • Form.add_error(fielderror)

This method allows adding errors to specific fields from within the Form.clean() method, or from outside the form altogether; for instance from a view.

The field argument is the name of the field to which the errors should be added. If its value is None the error will be treated as a non-field error as returned by Form.non_field_errors().

The error argument can be a simple string, or preferably an instance of ValidationError. See Raising ValidationError for best practices when defining form errors.

Note that Form.add_error() automatically removes the relevant field from cleaned_data.

  • Form.has_error(fieldcode=None)

This method returns a boolean designating whether a field has an error with a specific error code. If code is None, it will return True if the field contains any errors at all.

To check for non-field errors use NON_FIELD_ERRORS as the field parameter.

  • Form.non_field_errors()

This method returns the list of errors from Form.errors that aren’t associated with a particular field. This includes ValidationErrors that are raised in Form.clean() and errors added using Form.add_error(None, "...").

转载于:https://blog.51cto.com/quxf2012/1871359

django forms 错误处理相关推荐

  1. Django Forms实例

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

  2. Django forms组件

    校验字段 模板文件 <!DOCTYPE html> <html lang="en"> <head><meta charset=" ...

  3. django.forms生成HTML,第21天,Django之Form组件

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

  4. django forms表单

    目录: forms表单介绍 forms常用字段与插件 forms所有内置字段 正则校验字段 钩子函数自定义校验 FORMS介绍 在许多应用场景下都需要对用户的输入做校验,比如校验用户是否输入,输入的长 ...

  5. markdownpad2 html渲染组件出错_Day68 Django forms组件

    目录 forms组件 forms组件类书写 forms组件如何校验数据 forms组件如何渲染标签 forms组件展示错误信息 forms组件钩子函数(HOOK) forms组件常见参数 forms组 ...

  6. django NoReverseMatch 错误问题

    对照这django官方教程(1.8)写第一个APP,在第3部分(Removing hardcoded URLs in templates),将index.html的链接<a href=" ...

  7. django 创建mysql失败_创建表时出现Django MySQL错误

    我正在用MySQL数据库构建一个django应用程序.当我第一次运行"python manage.py migrate"时,一些表创建得很好,然后出现一些错误.出现的错误是:dja ...

  8. django 403 错误:CSRF token missing or incorrect

    最近觉得SAE不错,就开始试试看,从Django开始.把原来MVC3的一个小项目转过来,记录下碰到的问题. 用的Django版本为1.4. 我比较喜欢用jquery的ajax来做表单提交(我觉得aja ...

  9. django数据库错误django. db. utils. OperationalError: ( 1044,‘Access denied for user’ erqueque’@' %’to‘dj’

    数据库配置的两种方法 第一种,在settings内直接配置,缺点就是如果上传到GitHub或码云会把数据库给暴露出来 DATABASES = { 'default': { 'ENGINE': 'dja ...

最新文章

  1. Spring Cloud(八)高可用的分布式配置中心 Spring Cloud Config
  2. 基于人工智能和物联网的“智能护理
  3. idea tomcat热部署_IDEA设置热部署
  4. python语言翻译-教你用Python抓取百度翻译
  5. 1月12日,HTML学习笔记2
  6. 多层次报表的性能优化方案
  7. px、em、pt之间的区别与互相转换
  8. jdbc连接数据scanip_java数据库连接_jdbc
  9. oracle 11gR2 RAC root.sh 错误 ORA-15072 ORA-15018
  10. 基于注解的AOP实现事务控制及问题分析
  11. js性能优化--学习笔记
  12. Fatal error compiling: java.lang.ExceptionInInitializerError: com.sun.tools.javac.code.TypeTags
  13. (转)淘淘商城系列——Redis持久化方案
  14. html5 网页宽度100,HTML5 Canvas 100%视口宽度?
  15. python类方法需要传入cls参数_如何从Python 3.x中的类定义传递参数到元类?
  16. 去哪网实习总结:JavaWeb配置404页面(JavaWeb)
  17. 你是如何找到自己的第一份测试工作的?
  18. java计算机毕业设计企业员工档案管理源码+系统+数据库+lw文档+mybatis+运行部署
  19. execute immediate 用法详解
  20. 我的世界服务器ess配置信息,我的世界ess指令大全及用法详解

热门文章

  1. 大数据与数据挖掘考试题_大数据时代下的数据挖掘试题及答案
  2. JavaScript中函数文档注释
  3. GitLab+Jenkins+Ansible
  4. 【BZOJ】1823: [JSOI2010]满汉全席(2-sat)
  5. Linux远程远程控制程序TeamViewer
  6. Hibernate一对多(注解)
  7. 二叉树 —— 中序遍历结点的后继
  8. 第三方登录 (faceBook )
  9. fzu 1686(DLX 重复点覆盖)
  10. error: xxxx.o: Relocations in generic ELF (EM: 3)解决办法