Categories
Python Answers

How to set a dynamic File Path in Python Django?

Spread the love

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" % instance.owner.id, "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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *