Create and return the default ImageFieldFile from inside the function

In my UserProfile model, I would like to have a function that returns a user object ImageFileFieldor default image if the user has not loaded 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 the equivalent ImageFileField, because I have filters that work with this type of object (so I can’t just pass a string to it, easily) ... I tried to look at the source code , but I can’t figure out how to do it myself.

Is there an easy way to initialize a new object ImageFileFieldby passing it the path to the image file and then returning it?

PS: ImageField, , ... , , .

+5
1

, , , , - ImageFieldFile.

ImageField aa ImageFileDescriptor. , ImageFieldFile.

save() delete() ImageFieldFile, :

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')
+11

All Articles