表单验证错误和错误代码

编程入门 行业动态 更新时间:2024-10-28 15:28:26
本文介绍了表单验证错误和错误代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在Django文档中 https://docs.djangoproject。 com / en / dev / ref / forms / validation /#raising-validationerror 表示,在引发ValidationError异常的同时生产错误代码是一种好习惯。

In Django documentation docs.djangoproject/en/dev/ref/forms/validation/#raising-validationerror said that it is good practice to prodive error code while raising ValidationError exception.

# Good ValidationError(_('Invalid value'), code='invalid') # Bad ValidationError(_('Invalid value'))

我的应用程序中有API,并且正在使用表单来验证输入数据。 如果表单无效,我想得到这些错误代码(不是错误消息)。

I have API in my application and I'm using form to validate input data. If form is not valid, I whant to get these error codes (not error messages).

所以我看了看在BaseForm的_clean_fields方法的源代码中: github/django/django/blob/master/django/forms/forms.py#L278

So I looked at source code of _clean_fields method of BaseForm: github/django/django/blob/master/django/forms/forms.py#L278

except ValidationError as e: self._errors[name] = self.error_class(e.messages) if name in self.cleaned_data: del self.cleaned_data[name]

据我了解,此参数( self.code )没有传递到任何地方,并且在

As I understand this parameter (self.code) is not passed anywhere and can not be obtained after the form validation.

有人可以解释使用此错误代码的目的吗?

Can someone explain what the purpose of using this error code?

推荐答案

在Django 1.7中,您现在可以从表单访问原始错误数据。您可以在 ErrorList 或 ErrorDict 。例如: my_form.errors.as_data()。基本上,这将为您提供原始的 ValidationError 对象,而不是消息本身。从中您可以访问 .code 属性,例如: my_form.errors [ __ all __]。as_data()[0] .code 。

In Django 1.7, you can now access the original error data from the form. You can call the as_data() method on an ErrorList or ErrorDict. For example: my_form.errors.as_data(). This basically gives you the original ValidationError object instead of the message itself. From this you can access the .code property, eg: my_form.errors["__all__"].as_data()[0].code.

您也可以序列化表单错误,非常适合API:

You can also serialize form errors, great for APIs:

>>> print(form.errors.as_json()) {"__all__": [ {"message": "Your account has not been activated.", "code": "inactive"} ]}

更多推荐

表单验证错误和错误代码

本文发布于:2023-10-09 21:15:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1476805.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   错误代码   错误

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!