Tom
Tom

Reputation: 2661

how to specify a directory and a function with upload_to in django

I have 2 models cars and profiles:

class Car(models.Model):
    name = models.CharField(max_length=200)
    image_file = models.ImageField(upload_to=naming, null=True, blank=True)

class Profile(models.Model):
    name = models.CharField(max_length=200)
    image_file = models.ImageField(upload_to='profiles', null=True, blank=True)

I need the naming function but I also want the uploaded files to be in the folder cars instead of just in the media directory.

Is there any way to upload them into that folder AND call that function? In the doc I could only find one way but not both ways.

Thanks in advance!

Upvotes: 1

Views: 318

Answers (1)

Shang Wang
Shang Wang

Reputation: 25539

I don't understand what do you mean upload & call the function at the same time, but the function is indeed called, otherwise it won't produce any paths. For your first question, you could do the following:

def naming(instance, file_name):                                                 
    model_name = instance.__class__.__name__
    return os.path.join(model_name, file_name)

Upvotes: 1

Related Questions