[Fixed]-Catching exceptions in django templates

17👍

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 %}

0👍

Your template should not be raising an exception as a normal course of action. If there’s an error in the template, you fix it. Otherwise, anything that could potentially raise an exception should be handled in the model or the view. There’s no tag like you mention for a reason.

Leave a comment