Skip to content Skip to sidebar Skip to footer

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. How can this be achieved? Code below doesnt work, I get

Solution 1:

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'

Post a Comment for "Django: Changing The Url Of An Optional ImageField"