django - 如何在保存到磁盘之前验证 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 验证器验证文件,然后将其保存到磁盘。
解决方案
不要将 imagen 保存到DB中,存在文件夹media的目的,但也许您可以使用此BinaryField:BinaryField
模型.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)
推荐阅读
- tomcat - 无法启动上下文路径 [/ords] 处带有 Tomcat 9.X 应用程序的 Oracle ORDS (19.x):java.nio.file.AccessDeniedException
- python - Python中的颜色编码数字类似于Excel条件格式
- ttl - 具体化列上的 ClickHouse TTL
- java - Optaplanner - drools 使用旧的阴影变量
- python - 从现有的 Google 电子表格中获取响应、追加行和更新
- android - Android Studio 汽车 API
- c++ - 编写程序,导入三个浮点数a、b和c。按升序排序
- css - 如何更改 laravel 中的标准字体?字体松鼠
- mvvm - 为每个 Blazor 电路创建一次对象 (ViewModel)
- apache-spark - Google Cloud Storage 存储分区副本