【发布时间】:2019-12-14 19:33:20
【问题描述】:
为什么 Django 的 ImageField 没有在这里抛出验证错误?
# field in model
image_mobile = ImageField(
upload_to='static/images/',
blank=True,
null=True
)
# in test
from django.core.files.uploadedfile import SimpleUploadedFile
attachment = SimpleUploadedFile("file.mp4", b"file_content", content_type="text/plain")
obj.image_mobile = attachment
obj.save()
self.assertEqual(obj.image_mobile, '')
输出这个:
AssertionError: <ImageFieldFile: static/images/file_7wanB5P.mp4> != ''
来自文档:
从 FileField 继承所有属性和方法,但也验证上传的对象是有效的图像。
【问题讨论】:
-
Django 不会急切地验证。您应该调用
obj.full_clean()来运行所有验证。这主要是出于性能原因。 -
@WillemVanOnsem 但是当你调用
save()时它不应该验证它吗? -
不,这正是重点。出于性能原因,验证器不使用
.save()运行。但是,ModelForm将调用清理函数(当然,除非您覆盖它)。 -
@WillemVanOnsem
full_clean()什么都不做。仍然没有验证错误。