About Copying an Image from One ImageField to Another

When you want to copy an image from one ImageField to another while respecting the upload_to attribute's value, do this:

1
2
3
4
5
6
7
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage

if magazine.cover and default_storage.exists(magazine.cover.name):
    thumbnail_filename = magazine.cover.name.rsplit("/", 1)[-1]
    thumbnail_data = ContentFile(magazine.cover.read())
    magazine.thumbnail.save(thumbnail_filename, thumbnail_data)

Tips and Tricks Programming Django 4.2 Django 3.2 Django 2.2 Python 3 Pillow