Django - a custom filter to check if a file exists

I made this custom filter to check if the image exists:

from django import template from django.core.files.storage import default_storage register = template.Library() @register.filter(name='file_exists') def file_exists(filepath): if default_storage.exists(filepath): return filepath else: index = filepath.rfind('/') new_filepath = filepath[:index] + '/image.png' return new_filepath 

And I used this in the template as follows:

 <img src="{{ STATIC_URL }}images/{{ book.imageurl }}|file_exists" alt="{{book.title}} Cover Photo"> 

But that will not work. And I have no idea why.

+6
source share
1 answer

You do not apply a filter because |file_exists is outside of {{}} . Try the following:

 <img src="{{ STATIC_URL }}images/{{ book.imageurl|file_exists }}" alt="{{book.title}} Cover Photo"> 

Or, if you want to apply file_exists to the entire image URL, try the following:

 <img src="{{ STATIC_URL|add:'images/'|add:book.imageurl|file_exists }}" alt="{{book.title}} Cover Photo"> 
+5
source

Source: https://habr.com/ru/post/952228/


All Articles