Django:更改可选ImageField的url [英] Django: Changing the url of an optional ImageField

查看:124
本文介绍了Django:更改可选ImageField的url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



如何实现?下面的代码不工作,我得到无法设置属性错误,因为它是一个可选字段,它是空白的,因为我保存。



这是我的示例模型



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

和我的帖子保存信号: p>

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


解决方案

你不说你有什么问题(代码是否有效?),所以有你的代码中有两个问题。首先,你可能不想保存在一个后保存信号(无限循环,任何人?)。 其次,您有缩进问题(如果,则需要缩进)。



您可能想要这样做的方式是使用 Model.clean()



定义一个

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


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 

解决方案

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'

这篇关于Django:更改可选ImageField的url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆