Sunday, 15 June 2014

python - Accessing static files from custom template tag -



python - Accessing static files from custom template tag -

in template i'm trying add together custom tag takes image input, outputs image , class describing whether tall or wide.

my code follows.

the template:

{% load custom_tags %} {% image_size_class "management/image.jpg" %}

the custom tag:

from django import template pil import image django.templatetags.static import static register = template.library() @register.simple_tag def image_size_class(pattern): pattern_url = static(pattern) img = image.open(pattern_url) width, height = img.size if width > height: class_tag = "wide" else: class_tag = "tall" homecoming '<img src="' + pattern_url + '"' + ' class="' + class_tag + '">'

the desired outcome:

<img src="/static/management/image.jpg" class="wide">

what happens error pil:

[errno 2] no such file or directory: u'/static/management/image.jpg'

it seems pil can't find file want to, i'm not sure looking! help appreciated, thanks.

the problem pil seek access "/static/" folder on disk. should give real path file, this:

import os django.conf import settings ... @register.simple_tag def image_size_class(pattern): pattern_url = static(pattern) file_path = os.join(settings.static_root, pattern) img = image.open(file_path) width, height = img.size if width > height: class_tag = "wide" else: class_tag = "tall" homecoming '<img src="' + pattern_url + '"' + ' class="' + class_tag + '">'

python django

No comments:

Post a Comment