我的问题是,当我尝试使用 Django shell 将图像保存到我的模型时,我收到此错误,我找不到任何解决方案。
模型.py
class AdImage(models.Model):
ad = models.ForeignKey(Ad)
full_photo = models.ImageField(upload_to='uploads/', blank=True)
我导入模型创建 AdImage 实例添加“广告”并尝试
imagead.full_photo.save("NowHiring.jpg",open("C:\\NowHiring.jpg", "rb"))
但是我得到一个错误
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\hp\Envs\platform\lib\site-packages\django\db\models\fields\file
s.py", line 106, in save
self._size = content.size
AttributeError: '_io.BufferedReader' object has no attribute 'size'
使用:Python 3.5、Django 1.9
我能做什么?
最佳答案
FieldFile.save
方法需要使用 django.core.files.File
的实例调用,而不是内置的 python 文件句柄。将保存调用更改为:
from django.core.files import File
imagead.full_photo.save("NowHiring.jpg", File(open("C:\\NowHiring.jpg", "rb")))
FieldFile.save
的 Django 文档引用.
关于python - Django Shell 图片上传_io.BufferedReader 无属性大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35732150/