通过信号我检查我的模型是否属于一个类别。如果是,我想将可选的 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
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
).
您可能想要执行此操作的方式是Model.clean() http://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#django.db.models.Model.clean.
定义一个clean
模型上的方法如下:
def clean(self):
if instance.category == 1 #a specific category
instance.poster.url = u'/media/special_image_for_1.png'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)