About Downloading Images to an Image Field

Assign a downloaded image to an image field with SimpleUploadedFile:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import requests
from django.core.files.uploadedfile import SimpleUploadedFile

url = "https://aidas.bendoraitis.lt/images/django-tricks.png"
response = requests.get(url)
post = Post.objects.create(
    image=SimpleUploadedFile(
        name="logo.png",
        content=response.content,
        content_type="image/png",
        ),
    ),
    # …
)

Tips and Tricks Programming Django 4.2 Django 3.2 Django 2.2 Django 1.11 Django 1.8 Python 3 requests