Source

gnocchi-gallery / gnocchi_gallery / templatetags / gallery.py

from django import template
from django.db.models import Q
from django.utils.html import escape

from gnocchi_gallery.models import Gallery, ThumbnailConfig
from gnocchi_tools.template import parse_args

import re
from easy_thumbnails.files import get_thumbnailer

register = template.Library()

class LoadGalleryNode(template.Node):
    def __init__(self, gallery, var):
        self.gallery = gallery
        self.var = var

    def render(self, context):
        name = self.gallery.resolve(context)
        varname = self.var
        if not isinstance(varname, basestring):
            varname = varname.resolve(context)
        try:
            context[varname] = Gallery.objects.get(Q(name=name)|Q(slug=name))
        except Gallery.DoesNotExist:
            context[varname] = None
        return ''

@register.tag
def load_gallery(parser, token):
    args, kwargs, varname = parse_args(parser, token, 'gallery')
    if len(args) != 1 or kwargs:
        raise template.TemplateSyntaxError, \
            'load_gallery requires one position, and no keyword, argument.' % args[0]
    return LoadGalleryNode(args[0], varname)

RE_SIZE = re.compile(r'(\d+)x(\d+)$')

@register.filter
def config_thumbnail(source, name):
    '''Turns an image field or image path into a URL to a thumbnail, made using
    the named config.

    '''

    try:
        config = ThumbnailConfig.objects.get(name=name)
    except ThumbnailConfig.DoesNotExist:
        return ''
    config._load_cache()
    opts = config._attributes
    if 'size' in opts:
        m = RE_SIZE.match(opts['size'])
        if m:
            opts['size'] = (int(m.group(1)), int(m.group(2)))
        else:
            return ''
    thumbnail = get_thumbnailer(source).get_thumbnail(config._attributes)
    return escape(thumbnail.url)