gpt4 book ai didi

python - AttributeError : 'file' object has no attribute '_committed' . 重命名图像 django 模型

转载 作者:搜寻专家 更新时间:2023-10-30 23:33:21 24 4
gpt4 key购买 nike

我正在使用 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'

Google 了一会儿,了解到用 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)

最佳答案

你应该看看FieldFile.save()但基本上您可以执行以下操作:

from django.core.files import File
...
event.image.save(f.name, File(f))

关于python - AttributeError : 'file' object has no attribute '_committed' . 重命名图像 django 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45972667/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com