How to change MEDIA_URL for one FileField

In my Django project I use the following MEDIA_URL inside of settings.py:

MEDIA_URL = "https://ik.imagekit.io/my_org_name/my_project_name/"

This routes all images through ImageKit, which automatically resizes them based on the visitor’s device and resolution, serves big PNG and JPG images as WebP when the browser supports it, and serves as a global CDN which caches the images. It’s pretty nice.

We have a photo_id file field in one of our models:

class VerificationQueue(models.Model):
    photo_id = models.FileField()
    # ... other fields

This is for users to get verified, and once the photo ID has been processed we immediately delete the file. We absolutely do not want this image to go through ImageKit. A simple solution for this is using a custom storage class:

from django.core.files.storage import FileSystemStorage

class NoImageKitStorage(FileSystemStorage):
    def __init__(self, *args, **kwargs):
        kwargs["base_url"] = "/media/"
        super().__init__(*args, **kwargs)
        
class VerificationQueue(models.Model):
    photo_id = models.FileField(storage=NoImageKitStorage())

So now when an admin looks at the photo ID, it doesn’t go through ImageKit, and it doesn’t get cached by them. I love it when a solution is so simple, thanks Django!

Written by

Kevin Renskers

Freelance software developer with over 25 years of experience. Writes articles about Swift, Python, and TypeScript. Builds Critical Notes, and maintains a bunch of open source projects.

No AI was used in writing any of the content on this website.

Related articles

› See all articles