已经尝试了许多以前发布在这里的相关解决方案,但没有效果。我显然错过了一些东西。我正在使用 Django 1.4。我有一个生成随机数量的 jpeg 文件的过程。我正在尝试创建视图/模板/模板标签的组合,让我动态显示图像。不涉及模型。使用了Lois Di Qual的模板标签过滤器的想法
settings.py 文件安装了正确的 TEMPLATE_CONTEXT_PROCESSORS。提前致谢。
这就是我所拥有的:
模板:
{% load mytemplatetags %}
{% for fn in jpg_names %}
{{ fn|absolute_img_uri:request }}
{% endfor %}
模板标签
from django import template
from django.template.loader import render_to_string
from django.core.urlresolvers import reverse
register = template.Library()
'''
Usage: {{ fn|absolute_media_url:request }}
'''
@register.filter
def absolute_img_uri(fn, request):
return request.build_absolute_uri(reverse("returnImage", kwargs={'fn':fn}))
看法:
def returnImage(request,**kwargs):
path = "/opt/local/var/media/facstool/"
fn = kwargs['fn']
img = open(str(path)+fn,'rb').read()
response = HttpResponse(img,mimetype='image/jpeg')
return response
网址:
import ri.tools.views as rv
urlpatterns = patterns('ri.tools.views',
url(r'^$', 'index', name="index"),
url(r'defineParameters','defineParameters',name='defineParameters'),
url(r'downloadcsv','downloadcsv',name='downloadcsv'),
url(r'downloadpdf','downloadpdf',name='downloadpdf'),
url(r'downloadZipFile','downloadZipFile',name='downloadZipFile'),
url(r'returnImage/(?P<fn>.*)',rv.returnImage,name='returnImage'),
)
*-编辑-*
追溯:
NoReverseMatch at /tools/defineParameters
Reverse for 'returnImage' with arguments '()' and keyword arguments '{'fn': u'Lep-_Clone12_Median__ss_293F_Median__ss_293F_H8_graph.jpg'}' not found.
Request Method: POST
Request URL: http://localhost:8000/tools/defineParameters
Django Version: 1.4
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'returnImage' with arguments '()' and keyword arguments '{'fn': u'Lep-_Clone12_Median__ss_293F_Median__ss_293F_H8_graph.jpg'}' not found.
Exception Location: /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/urlresolvers.py in _reverse_with_prefix, line 396
Python Executable: /opt/local/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
Python Version: 2.7.2