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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With