I'd like to base the filename on the id field of the model, but the
only way I've found to get that is to use dispatch mechanism and hope
to grab the id when the object is saved to the database. The skeleton
of my code looks roughly like this:
class MyField(models.ImageField):
def __init__(self, verbose_name=None, name=None, parent_pk=None, **kwargs):
super(MyField, self).__init__(verbose_name, name, **kwargs)
self.parent_pk = parent_pk or "UNDEFINED"
def _update_parent_pk(self, instance=None):
self.parent_pk = instance._get_pk_val()
def contribute_to_class(self, cls, name):
super(MyField, self).contribute_to_class(cls, name)
dispatcher.connect(self._update_parent_pk, signals.post_save,
sender=cls)
And then I use self.parent_pk in save_file to override the filename.
But this seems like a bit of a hack, to me -- is there a standard
method of accessing the model from the field that I'm just missing? Or
is this this really the easiest way to do this?
Regards,
Ian Clelland
<clel...@gmail.com>
def save(self):
if self.image:
import shutil
from os import path
from django.conf import settings
pathname, filename = path.split(self.image)
extension = path.splitext(filename)[1]
new_image = path.join(pathname, '%s%s' % (self.slug,
extension))
new_location = path.join(settings.MEDIA_ROOT, new_image)
old_location = path.join(settings.MEDIA_ROOT, self.image)
if new_location != old_location:
shutil.move(old_location, new_location)
self.image = new_image
super(Image, self).save()
Rudolph