我正在使用requests
通过链接下载图片并将其保存到模型
f = open('00000001.jpg','wb')
f.write(requests.get('http://www.gunnerkrigg.com//comics/00000001.jpg').content)
event.image = f
f.close()
event.save()发生错误:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/TheKotik/tick-tock2/denv/lib/python2.7/site-packages/django/db/models/base.py", line 734, in save
force_update=force_update, update_fields=update_fields)
File "/Users/TheKotik/tick-tock2/denv/lib/python2.7/site-packages/django/db/models/base.py", line 762, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/TheKotik/tick-tock2/denv/lib/python2.7/site-packages/django/db/models/base.py", line 824, in _save_table
for f in non_pks]
File "/Users/TheKotik/tick-tock2/denv/lib/python2.7/site-packages/django/db/models/fields/files.py", line 312, in pre_save
if file and not file._committed:
AttributeError: 'file' object has no attribute '_committed'
用谷歌搜索了一段时间,并且明白用id命名图像的方法可能有些错误,但是不能真正理解错误是什么以及为什么
def get_image_path(instance, filename):
return 'event_img/{0}'.format(instance.event.id)
class Event(models.Model):
image = models.ImageField(upload_to=get_image_path)
答案 0 :(得分:1)
您应该查看FieldFile.save()
,但基本上您可以执行以下操作:
from django.core.files import File
...
event.image.save(f.name, File(f))