根据https://docs.djangoproject.com/en/dev/ref/forms/validation/
# Good
ValidationError(
_('Invalid value: %(value)s'),
params={'value': '42'},
)
# Bad
ValidationError(_('Invalid value: %s') % value)
文档并没有真正解释为什么它是坏/好。有人可以举一个具体的例子吗?
此外,当我检查时form.errors
,我会得到类似的东西'Invalid: %(value)s'
。如何从验证错误中获取参数并将它们插入到错误消息中?
已编辑
那么这被认为是好的吗?
ValidationError(
_('Invalid value: %(value)s') % {'value': '42'},
)
我认为真正的问题是:为什么要通过参数分别传递变量params
?为什么不直接插入到错误消息中(暂时忽略命名或位置插值)???
已编辑
好的,从来源@ https://github.com/django/django/blob/stable/1.5.x/django/forms/forms.py 我认为没有任何方法可以检索 ValidationError 的参数,因为 Form 确实如此甚至不保存 ValidationError 对象本身。请参阅下面的代码。
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]