Django:更改可选 ImageField 的 url
通过信号我检查我的模型是否属于一个类别。如果是,我想将可选的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有说出您遇到的问题(该代码可以工作吗?),因此您的代码中有两个问题。首先,您可能不想保存在保存后信号中(无限循环,有人吗?)。
其次,您遇到了缩进问题(您需要在if
之后缩进)。您可能想要执行此操作的方法是使用
Model.clean()
。在模型上定义一个
clean
方法,如下所示: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 theif
).The way you probably want to do this is with
Model.clean()
.Define a
clean
method on your model like this: