About Downloading Images to an Image Field

Assign a downloaded image to an image field with SimpleUploadedFile:

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