Django:更改可选 ImageField 的 url

发布于 2024-10-10 09:40:21 字数 576 浏览 0 评论 0原文

通过信号我检查我的模型是否属于一个类别。如果是,我想将可选的 ImageField 更改为特定的 url。

如何才能实现这一目标?下面的代码不起作用,我收到“无法设置属性”错误,因为它是可选字段,并且在保存时它是空白的。

这是我的示例模型

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 

Via signals I check if my model belongs to a category. If it is, I want to change my optional ImageField to a specific url.

How can this be achieved? Code below doesnt work, I get "cannot set attribute" error as it is an optional field and it was blank as I saved it.

Here is my sample model

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

and my post save signal:

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 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

莫多说 2024-10-17 09:40:21

您没有说出您遇到的问题(该代码可以工作吗?),因此您的代码中有两个问题。首先,您可能不想保存在保存后信号中(无限循环,有人吗?)。 其次,您遇到了缩进问题(您需要在 if 之后缩进)。

您可能想要执行此操作的方法是使用 Model.clean()

在模型上定义一个 clean 方法,如下所示:

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

You don't say what problem you're having (does that code work?), so there are two problems in your code. Firstly, you probably don't want to be saving in a post-save signal (infinite loop, anyone?). Secondly, you've got an indentation issue (you need to indent after the if).

The way you probably want to do this is with Model.clean().

Define a clean method on your model like this:

def clean(self):
  if instance.category == 1 #a specific category
    instance.poster.url = u'/media/special_image_for_1.png'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文