首页 > 解决方案 > 如何在保存到磁盘之前验证 ImageField?

问题描述

我正在尝试从某个外部 url 将图像放到 ImageField 中。

这是我的模型:

class MyModel(models.Model):
    id = models.AutoField(primary_key=True)
    photo = models.ImageField(
        upload_to=_upload_path,
        validators=[...]
    )

这就是我从 url 接收文件的方式:

from io import BytesIO
import requests
from django.core.files import File

fp = BytesIO()
fp.write(requests.get(url).content)
file = File(fp)

现在我需要将此文件附加到 MyModel,如果我愿意的话:

mymodel = MyModel()
mymodel.photo.save("some_filename.jpg", file)

我可以看到该文件已保存到upload_path/some_filename.jpg 没有任何验证(MyModel.photo 字段的所有验证器都被忽略)

是否可以执行以下操作:

mymodel.photo = ???
mymodel.full_clean()
mymodel.save()

所以some_filename.jpg只有在需要的验证后才会出现在磁盘上?我只需要通过 ImageField 验证器验证文件,然后将其保存到磁盘。

标签: django

解决方案


不要将 imagen 保存到DB中,存在文件夹media的目的,但也许您可以使用此BinaryFieldBinaryField

模型.py

class ExampleModel(model.Model):
    image = models.BinaryField(blank=True)

视图.py

def uploadImageIntoDb(request):
    image_file = request.FILES['image'].file.read()
    ExampleModel.objects.create(image=image_file)

推荐阅读