Django验证错误 [英] Django ValidationError

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

问题描述

根据 https://docs.djangoproject.com/en/dev / ref / forms / validation /

 #好
ValidationError(
_('无效值:%(value)s'),
params = {'value':'42'},


#错误的
ValidationError(_( '无效值:%s')%值)

文档并没有真正解释它为什么不好/好。有人可以举一个具体的例子吗?



此外,当我检查 form.errors 时,会得到类似无效:%(value)s 。如何从验证错误中获取参数并将其插值到错误消息中?



已编辑



那么这被认为是很好吗?

  ValidationError(
_('无效值:%(value)s')%{'value':'42'},

我认为真正的问题是:为什么分别通过<$ c $传递变量c> params 参数?为什么不直接插值到错误消息中(现在暂时忽略命名插值或位置插值)?



已编辑



好,从来源@ https://github.com/django/django/blob/stable/1.5.x/django/forms/forms.py
我不认为由于Form不会 甚至保存ValidationError对象本身,因此有任何方法可以检索ValidationError的参数。参见下面的代码。

  class ValidationError(Exception):
验证数据时出错。
def __init __(self,message,code = None,params = None):
从django.utils.encoding导入操作符
import force_text

ValidationError可以传递可以打印的任何对象(通常是
a字符串),对象列表或字典。

if isinstance(消息,字典):
self .message_dict = message
#将每个消息列表简化为一个列表。
message = reduce(operator.add,message.values())

if isinstance(message,list):
self.messages = [force_text(msg)for msg in message]
else:
self.code =代码
self.params = params
message = force_text(message)
self.messages = [message]

类形式:
....
def _clean_fields(...):
....
除了ValidationError如e:
self ._errors [name] = self.error_class(e.messages)#仅在名称为self.cleaned_data时保存消息

del self.cleaned_data [name]


解决方案

如果您有多个参数,则在翻译错误消息时它们可能会以不同的顺序出现。 / p>

使用命名参数,您可以更改参数的显示顺序,而无需更改 params



请注意,您要链接到Django文档的开发版本。验证错误不是插值参数,因为您使用的是Django 1.5或更早版本。如果您在1.6 Beta中尝试使用代码,则参数会插入到错误消息中。


According to https://docs.djangoproject.com/en/dev/ref/forms/validation/

   # Good
   ValidationError(
        _('Invalid value: %(value)s'),
        params={'value': '42'},
   )

   # Bad
   ValidationError(_('Invalid value: %s') % value)

The docs doesnt really explain why it is bad / good. Can someone give a concrete example?

Furthermore, when I inspect form.errors, I get something like 'Invalid: %(value)s'. How do I get the params from the Validation error and interpolate them into the error msg?

Edited

So is this considered good?

   ValidationError(
        _('Invalid value: %(value)s') % {'value': '42'},
   )

I think the real question is: why pass the variables separately via the params argument? Why not interpolate directly into the error msg (ignore named or positional interpolation for now)???

Edited

Ok, From the source @ https://github.com/django/django/blob/stable/1.5.x/django/forms/forms.py I don't think there is any way to retrieve ValidationError's params since the Form does not even save the ValidationError object itself. See code below.

class ValidationError(Exception):
    """An error while validating data."""
    def __init__(self, message, code=None, params=None):
        import operator
        from django.utils.encoding import force_text
        """
        ValidationError can be passed any object that can be printed (usually
        a string), a list of objects or a dictionary.
        """
        if isinstance(message, dict):
            self.message_dict = message
            # Reduce each list of messages into a single list.
            message = reduce(operator.add, message.values())

        if isinstance(message, list):
            self.messages = [force_text(msg) for msg in message]
        else:
            self.code = code
            self.params = params
            message = force_text(message)
            self.messages = [message]

class Form:
    ....
    def _clean_fields(...):
       ....
       except ValidationError as e:
            self._errors[name] = self.error_class(e.messages)  # Save messages ONLY
            if name in self.cleaned_data:
                del self.cleaned_data[name]

解决方案

If you have multiple parameters, they might appear in a different order when you translate the error message.

Named arguments allow you to change the order in which the arguments appear, without changing params. With a tuple of arguments, the order is fixed.

Note that you are linking to the development version of the Django docs. The validation error is not interpolating the parameters because you are using Django 1.5 or earlier. If you try your code in the 1.6 beta, then the parameters are interpolated into the error message.

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

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