Created
February 11, 2018 09:43
-
-
Save matthiask/3272f6b73ea6ddad411db0265211ec98 to your computer and use it in GitHub Desktop.
Minimal template tag for avoiding django-versatileimagefield crashes with invalid images
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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