Tip - Dynamic Path For FileField

In a recent project I needed to save a file to a dynamic directory.

My model was something like this:

from django.db import models

class MyDoc(models.Model):  
    name = models.CharField()
    document = models.FileField(upload_to='uploads/documents')

with this code each document will be uploaded to MEDIA_ROOT/uploads/documents.
In order to upload the file to a dynamic dir like this: MEDIA_ROOT/uploads/documents/id/ I used this code:

from django.db import models

class MyDoc(models.Model):  
    upload_to = 'uploads/documents/%d/%s'

    def _get_upload_to(self, filename):
        return self.upload_to % (self.pk, filename)

    name = models.CharField()
    document = models.FileField(upload_to=_get_upload_to)

That's all (Thats's Django!), now this code will upload each document into a separated dir for each object.

UPDATE The code I posted before doesn't work properly in fact the first time we save the model the pk is None so this code can't get the correct path.

If you have any question, please feel free to ask.

Share Comment on Twitter