Skip to content

Instantly share code, notes, and snippets.

@soukiassianb
Last active August 29, 2015 14:13
Show Gist options
  • Save soukiassianb/57eb911bcabac09f4871 to your computer and use it in GitHub Desktop.
Save soukiassianb/57eb911bcabac09f4871 to your computer and use it in GitHub Desktop.
Check if image field has the URL attribute associated with
class Products(models.Model):
# [....]
picture = models.ImageField(upload_to='products', blank=True, null=True)
picture_2 = models.ImageField(upload_to='products', blank=True, null=True)
picture_3 = models.ImageField(upload_to='products', blank=True, null=True)
# [....]
@property
def image_url_1(self):
if self.picture and hasattr(self.picture, 'url'):
return self.picture.url
@property
def image_url_2(self):
if self.picture_2 and hasattr(self.picture_2, 'url'):
return self.picture_2.url
@property
def image_url_3(self):
if self.picture_3 and hasattr(self.picture_3, 'url'):
return self.picture_3.url
# Then in templates
{{ product.image_url_1|default_if_none:'#'}}
{{ product.image_url_2|default_if_none:'#'}}
{{ product.image_url_3|default_if_none:'#'}}
@soukiassianb
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment