简体   繁体   English

Django Admin model.clean() 检查上传文件的属性

[英]Django Admin model.clean() check properties of an uploaded file

I have a Django model which allows an image to be uploaded, but before saving in the Django Admin, I need to verify that the uploaded image meets specific criteria for its dimensions, and show a validation error if not.我有一个 Django model 允许上传图像,但在保存到 Django 管理员之前,我需要验证上传的图像是否符合其尺寸的特定标准,并且是否符合特定标准。

What I have so far (not much.)...到目前为止我所拥有的(不多。)...

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)

Of course, this throws a FileNotFound error, as I assume the file hasn't actually been saved into the upload_to path at this point in the code.当然,这会引发 FileNotFound 错误,因为我假设在代码中此时该文件实际上并未保存到 upload_to 路径中。

Note that there's no custom form for this, since this will all be managed directly in the Django Admin pages.请注意,这里没有自定义表单,因为这一切都将直接在 Django 管理页面中进行管理。

How can I get the dimensions/properties of an FileField file in the model.clean() method?如何在 model.clean() 方法中获取 FileField 文件的尺寸/属性?

I presume it will be something along the lines of using TemporaryUploadedFile?我认为这将类似于使用 TemporaryUploadedFile?

Any help much appreciated, and am open to alternative methods/approaches for this.非常感谢任何帮助,并愿意为此提供替代方法/方法。

Edit: in case it makes any difference, I'm on Django 2.2编辑:如果有什么不同,我在 Django 2.2

Here what you need这里有你需要的

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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM