python - How to check if Django ValidationError subclass was raised?
问题描述
Let's assume I have a Django model:
class MyDjangoModel(models.Model):
name = models.CharField(max_length=200)
attribute = models.IntegerField()
class CustomValidationError(ValidationError):
pass
def clean(self):
if self.attribute < 1:
raise CustomValidationError("Attribute should be > 1!")
if len(self.name) > 20:
raise ValidationError("Name too long!")
I would like to create model instance and validate it:
inst = MyDjangoModel(name="Foo", attribute=0)
try:
inst.full_clean()
except CustomValidationError:
print("Hello!")
except ValidationError:
print("Bye!")
But the code above will never print "Hello!"
because full_clean
method is raising only ValidationError
.
Can anyone suggest, how to call full_clean
and check if ValidationError
subclass exception was raised?
解决方案
该full_clean
方法收集了几个阶段引发的所有错误。
你可以在这里查看它是如何调用你的clean
方法的:https ://github.com/django/django/blob/master/django/db/models/base.py#L1150
幸运的是,原始异常保存在error_dict
.
你可以试试这个:
inst = MyDjangoModel(name="Foo", attribute=0)
try:
inst.full_clean()
except ValidationError as exc:
for original_exc in exc.error_dict['__all__']:
if isinstance(original_exc, MyDjangoModel.CustomValidationError):
print("Hello!")
elif isinstance(original_exc, ValidationError):
print("Bye!")
假设这CustomValidationError
只是从clean
方法中提出的。否则,您还需要检查error_dict
.
请注意,if
s 的顺序很重要:如果第一个为 True,则第二个也为 True。
推荐阅读
- swift - 当语言环境设置为德语时,日期格式化程序日期函数返回 nil
- python - 如何使用输入来引用特定对象
- django - 错误:该端口已被使用(Ubuntu 18.04 服务器,不是本地开发)
- php - 如何在 ec2 aws 中为另一个项目创建另一个虚拟主机以部署 laravel
- azure - Azure 应用服务和 HttpContext.RequestAborted 取消令牌
- r - 使用 ggplot2,如何在网格图中显示多条线?
- java - 隐藏 Canvas 时丢失 AWT DrawingSurface
- jsf - DataTable 中的每一行都有复选框。如何在选中新复选框时取消选中前一个复选框
- regex - 如何替换电子邮件域名
- javascript - 使用 JavaScript 从键中访问值