Image upload with custom path django

20 April, 2016
Python Django

Image or file upload can be painful. I am writing this on how to setup your upload to a specific path dynamically.

Let's say you have a FooModel model with category and file

class FooModel:
    image = models.ImageField( upload_to=get_file_path, max_length=256)
    category = models.CharField(max_length=120)

There are two fields defined in this model. Let's say we have 10000 FooModel entries with 5 unique categories as shoes, jeans, mobile, shirts and laptops.

In order to uniquely create paths such all images are uniquely uploaded to different directory by their categories.

I have defined image field upload_to=get_file_path . This method get_file_path needs to be defined and takes the instance and filename, returns the new file path accordingly.

import uuid
def get_file_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    base_path = 'images/%s/' % instance.category
    return os.path.join(base_path, filename)

This sample also renames the file to accordingly create a unique uuid everytime a image is uploaded.

Thank you for taking the time to read this post. If you're considering using Digital Ocean, the hosting provider this blog is hosted on, please consider using this link to sign up.