1

Whenever I create Cloth Model with cloth_image, the image uploads to upload_location.

My problem is instance.id returns None because the instance is not yet created. What can be the best upload_location for ImageField?

def upload_location(instance, filename):
    new_id = instance.id
    ext = filename.split('.')[-1]
    return "clothes/%s/%s.%s" % (instance.user.id, new_id, ext) #  <- Right Here!

class Cloth(models.Model):
    cloth_image = models.ImageField(upload_to=upload_location,
                                null=True,
                                blank=True)

I'm using AWS S3.

Brown Bear
  • 19,655
  • 10
  • 58
  • 76
merry-go-round
  • 4,533
  • 10
  • 54
  • 102

2 Answers2

1

Just use the filename and not the id, e.g.

os.path.join('clothes', instance.user.id, filename)

Don't worry if filename already exists, Django automatically appends random strings at the end to avoid file replacements.

dirkgroten
  • 20,112
  • 2
  • 29
  • 42
1

if you want unique filename, i think you can use uuid for it, for example

import uuid
import os

def get_file_path(instance, filename):
    base_dir = 'clothes'
    user.id = str(instance.user.id)
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    return os.path.join(base_dir, user_id, filename)
Brown Bear
  • 19,655
  • 10
  • 58
  • 76