创建&从函数内返回默认的ImageFieldFile [英] Create & return a default ImageFieldFile from inside a function
问题描述
在我的UserProfile模型中,我希望有一个函数返回用户的 ImageFileField
对象或默认图像,如果用户没有上传自己的。
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.
例如:
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
我想要返回一个等价的 ImageFileField
,因为我有过滤器可以使用此对象类型(因此我不能简单地传递一个字符串)...我试着查看源代码但是我不太清楚自己如何去做。
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.
有没有一个简单的方法来初始化一个新的 ImageFileField $ c $通过将一个路径传递给一个图像文件,然后返回它?
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:我曾经想过使用ImageField的默认设置,但是,似乎较不灵活,因为该文件存储在模型创建...如果我以后想要更改默认文件,我将不得不更新所有具有旧文件的数据库条目。
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.
推荐答案
这可能是一个打字错误,但是您实际想要返回的是 ImageFieldFile
。
It was probably a typo, but what you actually want to return is an ImageFieldFile
.
ImageField
使模型的属性实例aa ImageFileDescriptor
。当您访问该属性时,它返回一个 ImageFieldFile
实例。
The ImageField
makes the property of the model instance actually aa ImageFileDescriptor
. When you access the property, it returns an ImageFieldFile
instance.
只要不调用 save()
或 delete()
ImageFieldFile的方法,你可以很容易地组织一个:
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')
这篇关于创建&从函数内返回默认的ImageFieldFile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!