object has no attribute '_committed' error

Viewed 629

I want django automatically download and locally save image from image_url and "connect" it with image_file

how Upload image from an URL with Django i have error object has no attribute '_committed' error

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()
1 Answers

To save a file/image to an instance manually you should use the FileField.save() method, you can use a ContentFile to convert the raw data to a Django file object

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()
Related