Alb
Alb

Reputation: 1125

Can I specify an upload-folder in the django models that's derived from a certain value?

I've got a model in Django which has a field specified as following:

file = models.FileField(upload_to='data')

I want to specify a folder based on a foreign key that another field that this instance has. Is this possible? Can I, for example, use something like

file = models.FileField(upload_to='{}/uploads/'.format(self.category.upper()))

I haven't tried anything yet.

Upvotes: 2

Views: 469

Answers (1)

Sanip
Sanip

Reputation: 1810

Instead of directly passing the name, you can define a function that generates the path name as:

def generate_filename(self, filename):
    name = "%s/uploads/%s" % (self.category.upper(), filename)
    return name

Then you can change the upload_to field as:

file = models.FileField(upload_to=generate_filename)

Upvotes: 2

Related Questions