表单验证错误和错误代码 [英] Forms ValidationError and error code

查看:68
本文介绍了表单验证错误和错误代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Django documentation https://docs.djangoproject.com/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方法的源代码中:

https://github.com/django/django/blob/master/django/forms/forms.py#L278

So I looked at source code of _clean_fields method of BaseForm:
https://github.com/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 as_data()方法c>。例如: 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"}
]}

这篇关于表单验证错误和错误代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆