Django handling Non-Existent urls at Template Level
As the title says. I form image urls in my Template. Sometimes the image is not there. I have a default image to be displayed in such cases.
But how do I handle this case at Template level. Perhaps write a filter? Are there other ways?
So开发者_开发技巧 Far:
...
{% for m in movies %}
<img width="54" height="74" src="/site_media/images/{{ m.id }}.jpg"></img>
{% endfor %}
...
Yes, you could write your own filter which would resolve the media path to an absolute path, then look if there is a file at that location.
However, I would strongly advise against it as in the worst case scenario this would read the disk an unknown number of times, at each request. If you have multiple servers, every server needs to have a copy of all images. If the images are user uploaded or created when the system is running, you need to distribute them. If you do go down this route, you could improve this by caching the result of the lookup with the standard cache mechanism.
Come to think of it, why don't you store the images on the model using an ImageField? From your example, it looks to me like you have one image per primary key, so it would make sense to use an ImageField unless you have some other constraints. If you make this field optional, maybe you can do something like this:
<img src="{{ m.get_image_url|default:"/site_media/images/missing_image.jpg" }}" />
精彩评论