姜戈。在自定义 clean() 方法中向 Form.errors 添加字段
我有一个事件模型,我想在模型上的自定义 def clean(self):
方法中放置以下验证规则:
def clean(self):
from django.core.exceptions import ValidationError
if self.end_date is not None and self.start_date is not None:
if self.end_date < self.start_date:
raise ValidationError('Event end date should not occur before start date.')
效果很好,只是我想通过以某种方式将其指定为有错误的字段,突出显示管理 UI 中的 self.end_date 字段。否则,我只会收到更改表单顶部出现的错误消息。
I have an Event model that I'd like to place the following validation rule on, in a custom def clean(self):
method on the Model:
def clean(self):
from django.core.exceptions import ValidationError
if self.end_date is not None and self.start_date is not None:
if self.end_date < self.start_date:
raise ValidationError('Event end date should not occur before start date.')
Which works fine, except that I'd like to highlight the self.end_date
field in the admin UI, by somehow nominating it as the field that has errors. Otherwise I only get the error message that occurs at the top of the change form.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从 Django 1.7 开始,您可以使用
add_error
方法直接向特定字段添加错误。 Django 文档表单.add_error('field_name', 'error_msg 或 ValidationError 实例')
如果
field_name
为None
,错误将添加到non_field_errors
中。From Django 1.7 you can directly add error to the particular field by using
add_error
method. Django docsform.add_error('field_name', 'error_msg or ValidationError instance')
If the
field_name
isNone
the error will be added tonon_field_errors
.docs
在底部解释如何执行此操作。提供的示例:
您的代码:
The
docs
explain how to do this at the bottom.provided example:
for your code: