Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching exceptions in django templates

I'm using a template tag in a Django template (the tag is thumbnail) and it's throwing an exception that makes the template fail with a 500 error. I would like to stop this from happening, as I don't have complete control over the source images that sporadically trigger this exception, and use a blank/placeholder image instead in those cases. This is the current template code:

{% thumbnail video.image_url "50x74" crop="center" as im %}
<img src="{% cdn_images im.url %}" />
{% empty %}
<img src="/media/img/noimage_thumb.png" alt="" />
{% endthumbnail %}

This is the exception (PIL throws it):

TemplateSyntaxError at /

Caught IOError while rendering: cannot identify image file

I searched for solutions and came up with silent_variable_failure which is a property that, if defined, makes an Exception be quiet. I guess this may point in the right direction but as far as I can tell any solution using this would mean I'd have to modify the template tag code itself, which is an external library - I'd prefer not to do that,

Ideally I would like to replace the third line in my code with something like {% empty or exception_raised %}.

Does anything like that exist? Do you know of any alternatives?

like image 787
Eduardo Ivanec Avatar asked Dec 15 '11 17:12

Eduardo Ivanec


1 Answers

The way I've always handled this is to push it up to the model layer. So in your model:

  class MyImageModel(model.Model):
       # model fields go here..

       def get_url(self):
            try:
                 # or whatever causes the exception
                 return self.url
            except IOError:
                 return None

And in your template:

{% thumbnail video.image_url "50x74" crop="center" as im %}

{% if im.get_url %}
    <img src="{% cdn_images im.get_url %}" />
{% else %}
    <img src="/media/img/noimage_thumb.png" alt="" />
{% endif %}

{% endthumbnail %}
like image 102
Sam Dolan Avatar answered Oct 05 '22 23:10

Sam Dolan