【问题标题】:Create & return a default ImageFieldFile from inside a function从函数内部创建并返回默认 ImageFieldFile
【发布时间】:2009-10-15 00:27:59
【问题描述】:

在我的 UserProfile 模型中,我希望有一个函数,它返回 either 用户的 ImageFileField 对象或默认图像(如果用户尚未上传自己的图像)。

例如:

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,因为我有适用于这种对象类型的过滤器(所以我不能轻易地传递一个字符串)...我尝试查看source code,但我可以不太清楚自己该怎么做。

有没有一种简单的方法来初始化一个新的ImageFileField 对象,方法是向它传递一个图像文件的路径,然后返回它?

PS:我曾考虑为 ImageField 使用 default 设置,但是,它似乎不太灵活,因为文件存储在模型创建时......如果我以后想更改默认文件,我必须更新所有具有旧文件的数据库条目。

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    这可能是一个错字,但您真正想要返回的是ImageFieldFile

    ImageField 使模型实例的属性实际上是 ImageFileDescriptor。当您访问该属性时,它会返回一个 ImageFieldFile 实例。

    只要不调用 ImageFieldFile 的 save()delete() 方法,就可以相当容易地实例化一个:

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

    【讨论】:

    • 你说得对,这是我的阅读障碍错字(不过,我可能会补充一点)。我将在我的模板中使用get_pic 函数......希望这不会太“不安全”。我明天要试试这个。看起来它会做我想要的。我没有意识到个别领域可能是save()delete() ... 每天都能学到一些东西!谢谢。
    • 看起来它应该可以工作,但我收到一个错误:文件“/usr/lib/python2.5/site-packages/django/db/models/fields/files.py”,第 23 行,在 init self.storage = field.storage AttributeError: 'NoneType' object has no attribute 'storage' 如果我将其更改为 field=self.pic 那么它可以正常工作;我试图将一个空的 ImageField 对象传递给它,但这没有用。不确定这是否很好,但它正在工作。
    • 哦,对了。我撒谎了,你不能像那样使用 ImageFieldFile。正在编辑我的答案...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2019-02-22
    • 2011-08-01
    • 1970-01-01
    • 2020-05-22
    • 1970-01-01
    • 2012-08-03
    相关资源
    最近更新 更多