If you’re wondering how to override a name of a file you’re uploading to ImageField/FileField in Django, here’s one of the possible solutions:

Add this to your models.py

Python [Show Plain Code]:
  1. from django.dispatch import dispatcher
  2. import shutil, os, settings, re
  3.  
  4. class CustomImageField(models.ImageField):
  5.     """
  6.     Model class should have a method like:
  7.  
  8.         def personalize_name(self, field_attname):
  9.             return "path/to/file/%d.jpg" % self.id
  10.  
  11.     """
  12.     def contribute_to_class(self, cls, name):
  13.             super(CustomImageField, self).contribute_to_class(cls, name)
  14.             dispatcher.connect(self._save, models.signals.pre_save, sender=cls)
  15.  
  16.     def _save(self, instance):
  17.         oldname = getattr(instance, self.attname)
  18.         extension = re.findall(r\.[\w\d]+$’, oldname)
  19.         if len(extension)>0:
  20.             extension = extension[0]
  21.         else: extension = ""
  22.         filename = instance.personalize_name(self.attname)
  23.         filename = self.upload_to + ‘_’.join(re.findall(r‘[a-zA-Z0-9]+’, filename)) + extension # leave only alphanum characters and add extension and add extension
  24.         try:
  25.             shutil.move(os.path.join(settings.MEDIA_ROOT, oldname), os.path.join(settings.MEDIA_ROOT, filename))
  26.         except IOError:
  27.             filename = oldname
  28.         setattr(instance, self.attname, filename)
  29.        
  30.     def db_type(self):
  31.         """Required by Django for ORM."""
  32.         return ‘varchar(100)’

And to your class definition you need to add something like this:

Python [Show Plain Code]:
  1. class MyPhoto(models.Model):
  2.     photo = CustomImageField(upload_to="photos/")
  3.     owner = models.CharField(max_length=32)
  4.     uploaded = models.DateTimeField(auto_add_now=True)
  5.    
  6.     def personalize_name(self, field_attname):
  7.         return "%s %s" % ( self.owner, self.uploaded ) # don’t worry about the non-alphanum characters

Assuming that the owner will be Bartosz Ptaszynski and the uploaded date 08-11-2007 13:06:00 and the file is photo.jpg the saved file will be:

photos/Bartosz_Ptaszynski_08_11_2007_13_06_00.jpg

Inspired by this blog. Thanks Scott.

Leave a Reply