Accessing a model from its fields

13 views
Skip to first unread message

Ian Clelland

unread,
Apr 2, 2006, 5:34:00 PM4/2/06
to django...@googlegroups.com
So, I've been working in m-r for just a couple of days now, and of
course, one of the first things I needed to do was to create a custom
model field -- in this case, ImageField, to get better control over
the filenames that are generated.

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>

Rudolph

unread,
Apr 2, 2006, 5:51:41 PM4/2/06
to Django users
I solved this another way, today. I move the file to it's new filename
in the save method of the model. It's not fully tested but seems to
work. In my case I use a slug field to create nice filenames.

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

Reply all
Reply to author
Forward
0 new messages