tôi đã thực hiện bộ lọc tùy chỉnh này để kiểm tra xem một hình ảnh tồn tại hay không:Django - bộ lọc tùy chỉnh để kiểm tra nếu tập tin tồn tại
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
Và tôi đã sử dụng này trong các mẫu như thế này:
<img src="{{ STATIC_URL }}images/{{ book.imageurl }}|file_exists" alt="{{book.title}} Cover Photo">
Nhưng nó không hoạt động. Và tôi không biết tại sao.
gì bạn có nghĩa là nó "không hoạt động"? Nó quay trở lại cái gì? –
Tôi nhận được 'http: // localhost: 8000/static/images/ios.png | file_exists' trong url của hình ảnh – Sourabh