Dynamic File Path for image in Django

2.5k Views Asked by At

I'm trying to generate dynamic file paths in django. I want to make a file system like this

hierarchy:
 --user_12
  --channel_14
   --program 2
    --image1.jpg
    --image2.jpg
   --program 1
    --image1.jpg
    --image2.jpg
 --user_14
  --channel_13
   --program 1
    --image1.jpg
    --image2.jpg

When a user want to upload image it will upload the image to the corresponding program folder.if program folder does not create it will automatically create a folder and store image..

my image path will look like this: media/images/john/johnchannel/birthday/img1.jpg ( where john=user,johnchannel=channel,birthday=program,images is the pre created folder where all image file should be stored) I am very new in django. urgent help needed.

2

There are 2 best solutions below

1
On

Are you looking for something like this?

misc.py

def get_upload_path(instance, filename):
    """ creates unique-Path & filename for upload """
    ext = filename.split('.')[-1]
    filename = "%s%s.%s" % ('img', instance.pk, ext)

    return os.path.join(
        'images', instance.user.username, instance.channel, instance.something, filename
        #images/     john/                johnchannel/       birthday/          img1.jpg
    )

models.py

from misc import get_upload_path

class MyThing(models.Model):
    user = models.ForeignKey(User)
    channel = models.CharField(max_length=100) # johnchannel
    something = models.CharField(max_length=100) # birthday
    img = models.ImageField(upload_to=get_upload_path)
0
On

When using an ImageField in a Django model, you can specify a callable in the upload_to keyword argument: See the FileField docs here

So create a function that you'll point upload_to at, which can generate all your subdirectories as needed.