Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if image exists - Django (1.3)

I have a template to display images according to some variable {{var}}.jpg If somehow for a particular value of var, there is not corresponding image, I want to display a fallback image for aesthetic purposes.

How do I achieve this?

I have defined a static path and I'm using

{% load static %}

<img src="{% get_static_prefix %}img/{{var}}.jpg"> 

to display my images.

like image 888
user1265125 Avatar asked Jan 20 '26 21:01

user1265125


1 Answers

Write a Custom filter for that.

{% if var|image_exists %}
   <img src="{% get_static_prefix %}img/{{var}}.jpg"> 
{% else %}
   <img src="{% get_static_prefix %}img/fallback.jpg"> 
{% endif %}

image_exists is custom filter. There is a simple line will work for you.

from django.core.files.storage import default_storage

default_storage.exists(your_image_path)
like image 177
Ahsan Avatar answered Jan 22 '26 14:01

Ahsan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!