Generic function to use as upload_to

Posted on Sat 11 October 2014 in Programming

FileFields in Django need an upload_to function that determines where the file will be uploaded. I usually have a generic function in utils.py that leaves them in a subfolder with the model name.

import os

def generic_upload_to(instance, filename):
    """
    Generic `upload_to` function for models.FileField and models.ImageField
    which uploads files to `<app_label>/<model_name>/<file_name>`.
    """
    return os.path.join(instance._meta.app_label, instance._meta.model_name, filename)

The usage is predictable:

featured_image = ImageField(upload_to=generic_upload_to,
                            verbose_name='Featured Image (770x490)',
                            max_length=250, blank=True, null=True)