Django Admin model.clean() 检查上传文件的属性
Django Admin model.clean() check properties of an uploaded file
我有一个允许上传图像的 Django 模型,但在保存到 Django 管理之前,我需要验证上传的图像是否符合其尺寸的特定标准,如果不符合则显示验证错误。
到目前为止我有什么(不多!)...
class CertificateTemplate(models.Model):
...
image_file = models.FileField(
upload_to="certificate/templates",
help_text=_(u"We recommend a .png image of 842px by 595px"))
...
def clean(self):
print("cleaning")
img = Image.open(self.image_file.path)
w,h = img.size
print(w)
print(h)
当然,这会抛出一个 FileNotFound 错误,因为我假设文件此时在代码中实际上还没有保存到 upload_to 路径中。
请注意,这里没有自定义表单,因为这一切都将直接在 Django 管理页面中进行管理。
如何在 model.clean() 方法中获取 FileField 文件的 dimensions/properties?
我想这将与使用 TemporaryUploadedFile 类似?
非常感谢任何帮助,并且对此持开放态度methods/approaches。
编辑:以防万一,我使用的是 Django 2.2
这里有你需要的
def validate_image(image):
img = Image.open(image.file)
width, height = img.size
# check height and width
if "does not meet requirements":
raise ValidationError("Error - your message")
image_file = models.ImageField('Image', upload_to=image_upload_path, validators=[validate_image])
我有一个允许上传图像的 Django 模型,但在保存到 Django 管理之前,我需要验证上传的图像是否符合其尺寸的特定标准,如果不符合则显示验证错误。
到目前为止我有什么(不多!)...
class CertificateTemplate(models.Model):
...
image_file = models.FileField(
upload_to="certificate/templates",
help_text=_(u"We recommend a .png image of 842px by 595px"))
...
def clean(self):
print("cleaning")
img = Image.open(self.image_file.path)
w,h = img.size
print(w)
print(h)
当然,这会抛出一个 FileNotFound 错误,因为我假设文件此时在代码中实际上还没有保存到 upload_to 路径中。
请注意,这里没有自定义表单,因为这一切都将直接在 Django 管理页面中进行管理。
如何在 model.clean() 方法中获取 FileField 文件的 dimensions/properties?
我想这将与使用 TemporaryUploadedFile 类似?
非常感谢任何帮助,并且对此持开放态度methods/approaches。
编辑:以防万一,我使用的是 Django 2.2
这里有你需要的
def validate_image(image):
img = Image.open(image.file)
width, height = img.size
# check height and width
if "does not meet requirements":
raise ValidationError("Error - your message")
image_file = models.ImageField('Image', upload_to=image_upload_path, validators=[validate_image])