Django:修改可选ImageField的URL

2 投票
1 回答
2906 浏览
提问于 2025-04-16 09:20

通过信号,我检查我的模型是否属于某个类别。如果属于,我想把我的可选图片字段改成一个特定的链接。

我该怎么做呢?下面的代码不行,我收到“无法设置属性”的错误,因为这是一个可选字段,保存时它是空的。

这是我的示例模型:

class Foo(models.Model):
    category = models.IntegerField(max_length=1)
    poster = models.ImageField(u"Poster", blank=True)

还有我保存后的信号:

def post_poster(instance, **kwargs):
        if instance.category == 1 #a specific category
            instance.poster.url = u'/media/special_image_for_1.png'
            instance.save()
    except MovieCat.DoesNotExist:
        pass 

1 个回答

1

你没有说明你遇到了什么问题(那段代码能正常工作吗?),所以在你的代码里有两个问题。首先,你可能不想在保存后信号中进行保存操作(这样会导致无限循环,懂吗?)。其次,你的缩进有问题(在if后面需要缩进)。

你可能想要的做法是使用 Model.clean()

在你的模型中定义一个 clean 方法,像这样:

def clean(self):
  if instance.category == 1 #a specific category
    instance.poster.url = u'/media/special_image_for_1.png'

撰写回答