Django ImageField rename file on upload

By default Django keeps the original name of the uploaded file but more than likely you will want to rename it to something else (like the object's id). Luckily, with ImageField or FileField of Django forms, you can assign a callable function to the upload_to parameter to do the renaming. For example:


from django.db import models
from django.utils import timezone
import os
from uuid import uuid4

def path_and_rename(instance, filename):
    upload_to = 'photos'
    ext = filename.split('.')[-1]
    # get filename
    if instance.pk:
        filename = '{}.{}'.format(instance.pk, ext)
    else:
        # set filename as random string
        filename = '{}.{}'.format(uuid4().hex, ext)
    # return the whole path to the file
    return os.path.join(upload_to, filename)


class CardInfo(models.Model):
    id_number = models.CharField(max_length=6, primary_key=True)
    name = models.CharField(max_length=255)
    photo = models.ImageField(upload_to=path_and_rename, max_length=255, null=True, blank=True)

In this example, every image that is uploaded will be rename to the CardInfo object's primary key which is id_number.


Reference: http://stackoverflow.com/questions/15140942/django-imagefield-change-file-name-on-upload