I
I
Ilya2017-10-03 12:29:33
Django
Ilya, 2017-10-03 12:29:33

How to properly save image from url to django models.ImageField?

django 1.11
Code snippet from admin.py

def save_model(self, request, obj, form, change):
    r = requests.get(url, stream=True)
    r.raw.decode_content = True
    obj.image.save(os.path.join('img/', slugify(unidecode(obj.title)), '.jpg'), r.raw)
    obj.save()

And it even works, except that it removes the dot from the filename: i.e. I get something like "imagejpg" instead of "image.jpg"
Perhaps I'm not saving the image correctly at all and it needs to be done in a different way.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Kuzmichev, 2017-10-03
@Quirel

Saving the image works, but the formation of the path is done with an error

def save_model(self, request, obj, form, change):
    r = requests.get(url, stream=True)
    r.raw.decode_content = True
    obj.image.save(os.path.join('img', '{}.jpg'.format(slugify(unidecode(obj.title)))), r.raw)
    obj.save()

os.path.joinforms a path from directories and a file name, but they do not need to form the name of a single folder or file.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question