Create & return a default ImageFieldFile from inside a function
django, django-models
Solution
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')
Problem
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.