Menu Close

How to set a dynamic File Path in Python Django?

To set a dynamic File Path in Python Django, we can create a function that returns the file path we want.

For instance, we write

import os

def get_upload_path(instance, filename):
    return os.path.join(
      "user_%d" %, "car_%s" % instance.slug, filename)

to create the get_upload_path function to return the file path we want given the filename and the model instance.

Then we set that as the upload_to argument of the model field by writing

photo = models.ImageField(upload_to=get_upload_path)

to create the photo ImageField with upload_to set to get_upload_path.

Posted in Python, Python Answers