Django:重写表单中的 clean() 方法 - 关于引发错误的问题

发布于 2024-08-19 00:00:48 字数 901 浏览 7 评论 0 原文

我一直在 clean 方法中做这样的事情:

if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']:
      raise forms.ValidationError('The type and organization do not match.')
if self.cleaned_data['start'] > self.cleaned_data['end']:
      raise forms.ValidationError('The start date cannot be later than the end date.')

但这意味着表单一次只能引发这些错误之一。有没有办法让表单引发这两个错误?

编辑#1: 上述任何解决方案都很棒,但希望能够在以下场景中工作:

if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']:
      raise forms.ValidationError('The type and organization do not match.')
if self.cleaned_data['start'] > self.cleaned_data['end']:
      raise forms.ValidationError('The start date cannot be later than the end date.')
super(FooAddForm, self).clean()

其中 FooAddForm 是 ModelForm 并且具有也可能导致错误的独特约束。如果有人知道类似的事情,那就太好了......

I've been doing things like this in the clean method:

if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']:
      raise forms.ValidationError('The type and organization do not match.')
if self.cleaned_data['start'] > self.cleaned_data['end']:
      raise forms.ValidationError('The start date cannot be later than the end date.')

But then that means that the form can only raise one of these errors at a time. Is there a way for the form to raise both of these errors?

EDIT #1:
Any solutions for the above are great, but would love something that would also work in a scenario like:

if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']:
      raise forms.ValidationError('The type and organization do not match.')
if self.cleaned_data['start'] > self.cleaned_data['end']:
      raise forms.ValidationError('The start date cannot be later than the end date.')
super(FooAddForm, self).clean()

Where FooAddForm is a ModelForm and has unique constraints that might also cause errors. If anyone knows of something like that, that would be great...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

深海夜未眠 2024-08-26 00:00:48

来自文档:

https://docs.djangoproject.com/en/1.7/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

from django.forms.util import ErrorList

def clean(self):

  if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']:
    msg = 'The type and organization do not match.'
    self._errors['type'] = ErrorList([msg])
    del self.cleaned_data['type']

  if self.cleaned_data['start'] > self.cleaned_data['end']:
    msg = 'The start date cannot be later than the end date.'
    self._errors['start'] = ErrorList([msg])
    del self.cleaned_data['start']

  return self.cleaned_data

From the docs:

https://docs.djangoproject.com/en/1.7/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

from django.forms.util import ErrorList

def clean(self):

  if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']:
    msg = 'The type and organization do not match.'
    self._errors['type'] = ErrorList([msg])
    del self.cleaned_data['type']

  if self.cleaned_data['start'] > self.cleaned_data['end']:
    msg = 'The start date cannot be later than the end date.'
    self._errors['start'] = ErrorList([msg])
    del self.cleaned_data['start']

  return self.cleaned_data
橘寄 2024-08-26 00:00:48
errors = []
if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']:
      errors.append('The type and organization do not match.')
if self.cleaned_data['start'] > self.cleaned_data['end']:
     errors.append('The start date cannot be later than the end date.')

if errors:
    raise forms.ValidationError(errors)
errors = []
if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']:
      errors.append('The type and organization do not match.')
if self.cleaned_data['start'] > self.cleaned_data['end']:
     errors.append('The start date cannot be later than the end date.')

if errors:
    raise forms.ValidationError(errors)
蓝海似她心 2024-08-26 00:00:48

虽然是旧帖子,但如果您想要更少的代码,您可以使用 add_error() 方法来添加错误消息。我正在扩展@kemar的答案以显示使用的情况:

add_error()自动从cleaned_data字典中删除该字段,您不必手动删除它。
此外,您无需导入任何内容即可使用它。

文档在这里

def clean(self):

  if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']:
    msg = 'The type and organization do not match.'
    self.add_error('type', msg)

  if self.cleaned_data['start'] > self.cleaned_data['end']:
    msg = 'The start date cannot be later than the end date.'
    self.add_error('start', msg)

  return self.cleaned_data

Although its old post, if you want less code you can use add_error() method to add error messages. I am extending the @kemar's answer to show the used case:

add_error() automatically removes the field from cleaned_data dictionary, you dont have to delete it manually.
Also you dont have to import anything to use this.

documentation is here

def clean(self):

  if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']:
    msg = 'The type and organization do not match.'
    self.add_error('type', msg)

  if self.cleaned_data['start'] > self.cleaned_data['end']:
    msg = 'The start date cannot be later than the end date.'
    self.add_error('start', msg)

  return self.cleaned_data
毁我热情 2024-08-26 00:00:48

如果您希望将错误消息附加到表单而不是特定字段,您可以使用键“__all__”,如下所示:

msg = 'The type and organization do not match.'
self._errors['__all__'] = ErrorList([msg])

另外,正如 Django 文档所解释的:“如果您想要要向特定字段添加新错误,您应该检查该键是否已存在于 self._errors 中,如果不存在,则为给定键创建一个新条目,并保存一个空的 。无论哪种情况,您都可以将错误消息附加到相关字段名称的列表中,并在显示表单时显示该消息。”

If you'd prefer that the error messages be attached to the form rather than to specific fields, you can use the key "__all__" like this:

msg = 'The type and organization do not match.'
self._errors['__all__'] = ErrorList([msg])

Also, as the Django docs explain: "if you want to add a new error to a particular field, you should check whether the key already exists in self._errors or not. If not, create a new entry for the given key, holding an empty ErrorList instance. In either case, you can then append your error message to the list for the field name in question and it will be displayed when the form is displayed."

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文