Django FileField with upload_to determined at runtime

You’ve probably read the documentation, so here’s an easy example to make it make sense:

def content_file_name(instance, filename):
    return "https://stackoverflow.com/".join(['content', instance.user.username, filename])

class Content(models.Model):
    name = models.CharField(max_length=200)
    user = models.ForeignKey(User)
    file = models.FileField(upload_to=content_file_name)

As you can see, you don’t even need to use the filename given – you could override that in your upload_to callable too if you liked.

Leave a Comment