Skip to content

Instantly share code, notes, and snippets.

@matthiask
Created February 11, 2018 09:43
Show Gist options
  • Save matthiask/3272f6b73ea6ddad411db0265211ec98 to your computer and use it in GitHub Desktop.
Save matthiask/3272f6b73ea6ddad411db0265211ec98 to your computer and use it in GitHub Desktop.
Minimal template tag for avoiding django-versatileimagefield crashes with invalid images
from django import template
from django.template.base import Variable
register = template.Library()
@register.simple_tag(takes_context=True)
def safeimage(context, imagefile, spec):
"""
Usage::
{% load safeimage %}
{% safeimage instance.image 'thumbnail.900x900' %}
{# Instead of {{ instance.image.thumbnail.900x900 }} #}
"""
var = Variable('imagefile.%s' % spec)
with context.push({'imagefile': imagefile}):
try:
return var.resolve(context)
except Exception as exc:
# TODO Add logging here.
print(exc)
return imagefile.url
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment