views:

177

answers:

1

In my UserProfile model I would like to have a function which returns either the user's ImageFileField object or a default image if the user has not uploaded their own.

For example:

class UserProfile(models.Model):
    pic = models.ImageField('Headshot',blank=True,
                             upload_to=get_path_and_filename)

    def get_pic(self):
        if self.pic:
            return self.pic
        else:
            # return ImageFileField with a default value

I want to return an equivalent ImageFileField because I have filters that work with this object type (so I can't just pass it a string, easily) ... I tried looking at the source code but I can't quite figure out how to do it myself.

Is there an easy way to initialize a new ImageFileField object by passing it a path to an image file and then return it?

PS: I had thought about using a default setting for the ImageField, however, it seems less flexible because the file is stored at model creation ... and if I later want to change the default file, I would have to update all the database entries that had the old file.

+1  A: 

It was probably a typo, but what you actually want to return is an ImageFieldFile.

The ImageField makes the property of the model instance actually aa ImageFileDescriptor. When you access the property, it returns an ImageFieldFile instance.

As long as you don't call the save() or delete() methods of the ImageFieldFile, you can instanciate one reasonably easily:

from django.db.models.fields.files import ImageFieldFile, FileField

class UserProfile(models.Model):
    # ...

    def get_pic(self):
        if self.pic:
            return self.pic
        return ImageFieldFile(instance=None, field=FileField(),
                              name='pictures/default.jpg')
SmileyChris
You are right, that was a dyslexic typo on my part (consistent, though, I might add). I am just going to use the `get_pic` function in my templates ... hopefully this won't be too "unsafe". I am going to give this a try tomorrow. Looks like it will do what I want though. I didn't realize that individual fields could be `save()` or `delete()` ... learn something every day! Thank you.
thornomad
That looks like it should work, but I am getting an error: File "/usr/lib/python2.5/site-packages/django/db/models/fields/files.py", line 23, in __init__ self.storage = field.storage AttributeError: 'NoneType' object has no attribute 'storage'If I change this to `field=self.pic` then it works okay; I tried to pass it an empty ImageField object but that didn't work. Not sure if this is good, but it is working.
thornomad
Oh, that's right. I lied, you can't use an ImageFieldFile just like that. Editing my answer...
SmileyChris