[英]Accessing static files from custom template tag
在我的模板中,我試圖添加一個接受圖像輸入的自定義標簽,然后輸出該圖像以及描述該圖像是高還是寬的類。
我的代碼如下。
模板:
{% load custom_tags %}
{% image_size_class "MANAGEMENT/image.jpg" %}
自定義標簽:
from django import template
from PIL import Image
from 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"
return '<img src="' + pattern_url + '"' + ' class="' + class_tag + '">'
預期的結果:
<img src="/static/MANAGEMENT/image.jpg" class="wide">
實際發生的是我從PIL得到錯誤:
[Errno 2] No such file or directory: u'/static/MANAGEMENT/image.jpg'
看來PIL找不到我想要的文件,但是我不確定它在哪里! 任何幫助將不勝感激,謝謝。
問題是什么PIL嘗試訪問磁盤上的“ / static /”文件夾。 您應該提供文件的真實路徑,如下所示:
import os
from 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"
return '<img src="' + pattern_url + '"' + ' class="' + class_tag + '">'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.