简体   繁体   English

Django:更改可选ImageField的网址

[英]Django: Changing the url of an optional ImageField

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. 如果是这样,我想将可选的ImageField更改为特定的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 ). 其次,您遇到了缩进问题(您需要在if之后缩进)。

The way you probably want to do this is with Model.clean() . 您可能想要执行此操作的方法是使用Model.clean()

Define a clean method on your model like this: 在模型上定义一个clean方法,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM