django forms 错误处理
2016-11-10 10:27
519 查看
源码文件,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的错误,如数据库中有复合主键重复等.
#部分源码
#官方文档
Access the
Returns a
Returns the errors serialized as JSON.
This method allows adding errors to specific fields from within the
This method returns a boolean designating whether a field has an error with a specific error
This method returns the list of errors from
一个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
errorsattribute 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
errorswithout having to call
is_valid()first. The form’s data will be validated the first time either you call
is_valid()or access
errors.The validation routines will only get called once, regardless of how many times you access
errorsor 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
dictthat maps fields to their original
ValidationErrorinstances.
>>> 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
ValidationErrorinstances were lost as soon as their rendered error messages were added to the
Form.errorsdictionary. Ideally
Form.errorswould 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=Trueand error messages will be escaped so you can use them directly in HTML.
Form.
add_error(field, error)
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
fieldargument is the name of the field to which the errors should be added. If its value is
Nonethe error will be treated as a non-field error as returned by
Form.non_field_errors().The
errorargument 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(field, code=None)
This method returns a boolean designating whether a field has an error with a specific error
code. If
codeis
None, it will return
Trueif the field contains any errors at all.To check for non-field errors use
NON_FIELD_ERRORSas the
fieldparameter.
Form.
non_field_errors()
This method returns the list of errors from
Form.errorsthat aren’t associated with a particular field. This includes
ValidationErrors that are raised in
Form.clean()and errors added using
Form.add_error(None, "...").
相关文章推荐
- 书羊农历控件使用步骤及处理错误:引发了“System.Windows.Forms.AxHost.InvalidActiveXStateException”类型的异常
- Sys.WebForms.PageRequestManagerServerErrorException: 在服务器上处理请求时出现未知错误。服务器返回的状态码为: 500
- django一对多查询错误处理
- Celery启动Django项目:Client sent AUTH, but no password is set 错误处理
- django一对多查询错误处理
- Sys.WebForms.PageRequestManagerServerErrorException: 在服务器上处理请求时出现未知错误解决办法
- Django--form验证及错误处理
- Python错误处理-ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MO
- Python3之Django Web框架URL匹配、反向解析及部分错误处理
- Sys.WebForms.PageRequestManagerServerErrorException: 在服务器上处理请求时出现未知错误解决办法
- 错误处理:WebForms UnobtrusiveValidationMode 需要“jquery”ScriptResourceMapping
- 在使用updatepanel 时,上传到服务器出现如下错误: Sys.WebForms.PageRequestManagerServerErrorException: 在服务器上处理请求时出现未知错误。服务器返回的状态码为: 500
- mysql远程访问 sql删除记录 伪造浏览器post php错误处理学习 django模板改tdk
- python3.3 django错误处理“sre_constants.error: nothing to repeat”
- 错误: Sys.WebForms.PageRequestManagerServerErrorException: 在服务器上处理 请求时出现未知错误。服务器返回的状态码为: 500
- django的request处理流程和错误处理
- django开发错误处理
- Django错误处理:DoesNotExist: User matching query does not exist.
- Django之模板继承与ajax使用错误处理~
- django 对于csrf错误的处理