【问题标题】:object has no attribute '_committed' error对象没有属性“_committed”错误
【发布时间】:2021-05-01 10:41:03
【问题描述】:

我希望 django 自动从 image_url 下载并在本地保存图像并与 image_file “连接”它

如何使用 Django 从 URL 上传图片 我有错误 对象没有属性 '_committed' 错误

from PIL import Image
import requests

url = 'https://i.stack.imgur.com/0jot2.png'
respone = requests.get(url, stream= True).raw
img = Image.open(respone)
img.save()

def home(request):
    Topic(title='hjb',content='vf',slug='fvrs',image=img,
            author=User.objects.first() )
            .save()

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    要将文件/图像手动保存到实例中,您应该使用 FileField.save() 方法,您可以使用 ContentFile 将原始数据转换为 Django 文件对象

    import requests
    
    def home(request):
        response = requests.get('https://i.stack.imgur.com/0jot2.png', stream=True)
        topic = Topic(
            title='hjb',
            content='vf',
            slug='fvrs',
            author=User.objects.first()
        )
        topic.image.save('0jot2.png', ContentFile(response.content))
        topic.save()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-19
      • 2016-08-05
      • 1970-01-01
      • 1970-01-01
      • 2012-04-26
      • 2013-05-09
      • 1970-01-01
      相关资源
      最近更新 更多