[Django]-Checking if image exists – Django (1.3)

2👍

If there is only image url in {{var}}. Then you can simply do this:

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

or if there is ‘image’ field of {{var}} then:

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

8👍

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)
👤Ahsan

2👍

If the variable is not an instance of an object with a picture associated to it (meaning {{ var.image }} would not work), but instead {{ var }} simply indicates the name of the static image:

Instead of using

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

do

<div id="my_image" style="background: url({% get_static_prefix %}img/{{var}}.jpg)"></div>

and then add a wrapping div with the backup image, resulting in:

<div id="my_backup_image" style="background: url({% get_static_prefix %}img/backup.jpg)">
	<div id="my_image" style="background: url({% get_static_prefix %}img/{{var}}.jpg)"></div>
</div>

This way, both backgrounds are active, but when the inner fails only the outer is seen.

1👍

One idea is to check if var_x.jpg exists in the view (I’m assuming you can do this).
If var_x.jpg does not exist, just add it to a dictionary:
“missing_images” of the form {“var_x”:”missing”,”var_y”:”missing”} etc
and pass the dictionary to your view
then in the template you just need:

{% if missing_images.var_x %} display fallback
{% else %} display var_x.jpg
{% endif %}

Leave a comment