多个ValidationError函数的正确语法是什么?

huangapple go评论72阅读模式
英文:

What's the correct syntax for multiple ValidationError functions?

问题

以下是翻译好的代码部分:

def clean(self):
    if self.personal_id_type == 0 and self.personal_id is None:
        raise ValidationError(
            {
                'personal_id_type': [
                    "如果您已设置值,则无法将ID类型设置为'None'。",
                ]
            }
        )

    if self.personal_phone_mobile is None and self.personal_phone_direct is None:
        raise ValidationError(
            {
                'personal_phone_mobile': [
                    '请至少输入一个个人电话号码。',
                ],
                'personal_phone_direct': [
                    '请至少输入一个个人电话号码。',
                ],
            }
        )

希望这有所帮助。如果您需要更多帮助,请随时提问。

英文:

I have a model on which I want to raise 2 conditional validation errors:

def clean(self):
    if self.personal_id_type == 0 and self.personal_id is None:
        raise ValidationError(
            {
                'personal_id_type': [
                    "ID type can not be 'None' if you have set a value.",
                ]
            }
        )

    if self.personal_phone_mobile is None and self.personal_phone_direct is None:
        raise ValidationError(
            {
                'personal_phone_mobile': [
                    'Please enter at least one personal phone number',
                ],
                'personal_phone_direct': [
                    'Please enter at least one personal phone number',
                ],
            }
        )

This displays the errors in isolation fine, so the logic is sound, however when both errors exist only the first exception is raised. Have I got the syntax wrong?

I want to be able to continue to use this in a Model (not a Form) display the error messages against the field_names.

答案1

得分: 1

这在文档的 raising multiple errors 部分 [Django-doc] 中有详细说明。

> 如果在清理方法中检测到多个错误并希望将它们全部传递给表单提交者,可以ValidationError构造函数传递错误列表。

其中包括一个示例:

<blockquote><pre><code># 好的做法
raise ValidationError([
ValidationError(('错误 1'), code='error1'),
ValidationError(
('错误 2'), code='error2'),
])</code></pre></blockquote>

因此,您可以使用以下方式实现此类验证:

<pre><code>def clean(self):
data = super().clean()
errors = []
if condition<sub>1</sub>:
errors.append(ValidationError('错误<sub>1</sub>', code='error<sub>1</sub>')
if condition<sub>2</sub>:
errors.append(ValidationError('错误<sub>2</sub>', code='error<sub>2</sub>'))
# &vellip;
if condition<sub>n</sub>:
errors.append(ValidationError('错误<sub>n</sub>', code='error<sub>n</sub>'))
if errors:
raise ValidationError(errors)
return data</code></pre>

请注意,对于特定字段的清理,您应该实现一个<code>clean_<i>fieldname</i></code>方法。有关更多信息,请参阅cleaning a specific field attribute 部分

英文:

This is covered in the documentation in the raising multiple errors section [Django-doc].

> If you detect multiple errors during a cleaning method and wish to signal all of them to the form submitter, it is possible to pass a list of errors to the ValidationError constructor.

They include an example:

<blockquote><pre><code># Good
raise ValidationError([
ValidationError(('Error 1'), code='error1'),
ValidationError(
('Error 2'), code='error2'),
])</code></pre></blockquote>

You thus can implement such validation with:

<pre><code>def clean(self):
data = super().clean()
errors = []
if condition<sub>1</sub>:
errors.append(ValidationError('Error<sub>1</sub>', code='error<sub>1</sub>')
if condition<sub>2</sub>:
errors.append(ValidationError('Error<sub>2</sub>', code='error<sub>2</sub>'))
# &vellip;
if condition<sub>n</sub>:
errors.append(ValidationError('Error<sub>n</sub>', code='error<sub>n</sub>'))
if errors:
raise ValidationError(errors)
return data</code></pre>

Note that for field-specific cleaning, you should implement a <code>clean_<i>fieldname</i></code> method. See the cleaning a specific field attribute section for more information.

huangapple
  • 本文由 发表于 2020年1月3日 19:32:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577883.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定