通过 simple_tag 向 Django 模板发送数据
Posted
技术标签:
【中文标题】通过 simple_tag 向 Django 模板发送数据【英文标题】:Send data to Django template via simple_tag 【发布时间】:2018-07-13 19:15:17 【问题描述】:我的目标是使用 Echart 库与我的主视图分开绘制绘图。这就是我创建自定义模板以将图表数据发送到模板 html 文件的原因。如果我使用渲染方法执行此操作,则数据发送正常。我附上了我的工作渲染视图和自定义视图(这将是我的目标)。
工作视图和模板:
查看:
def chart(request):
data=Test.objects.all()
data=[i['data'] for i in data]
attr=[i['attr'] for i in data]
bar = Bar("Teszt Chart")
bar.add("Tropo",attr, data, is_stack=True)
bar_chart = bar
context = dict(
myechart=bar_chart.render_embed(),
host=DEFAULT_HOST,
script_list=bar_chart.get_js_dependencies()
)
return render(request, 'test/chart.html', context)
模板
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test chart</title>
% for jsfile_name in script_list %
<script src="host/jsfile_name.js"></script>
% endfor %
</head>
<body>
myechart|safe
</body>
</html>
我的自定义模板:(不工作)
查看:
注册=模板.库() @register.simple_tag(takes_context=True)
def chart():
data=Test.objects.all()
data=[i['data'] for i in data]
attr=[i['attr'] for i in data]
bar = Bar("Teszt Chart")
bar.add("Tropo",attr, data, is_stack=True)
bar_chart = bar
myechart=bar_chart.render_embed()
host=DEFAULT_HOST
script_list=bar_chart.get_js_dependencies()
data=
'myechart':myechart,
'host':host,
'script_list': script_list,
return data
模板:
<!DOCTYPE html>
<html>
%load chart%
<head>
<meta charset="utf-8">
<title>Proudly presented by PycCharts</title>
% for i in chart %
<script src="i.host/i.jsfile_name.js"></script>
% endfor %
</head>
<body>
%for i in chart%
i.myechart
%endfor%
</body>
</html>
我的主要问题:如何从 simple_tag 视图传递数据?如果我使用这个 :% chart %
我的数据会出现,但我想彼此分开显示。提前感谢您的回答!
我的回溯:
Environment:
Request Method: GET
Request URL: http://192.168.1.190:800/chart/
Django Version: 2.0
Python Version: 3.4.2
Installed Applications:
['monitor.apps.MonitorConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mathfilters',
'django_echarts']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template error:
In template /gnss_monitor/scr/monitor/templates/monitor/chart.html, error at line 10
list index out of range
1 : <!DOCTYPE html>
2 : <html>
3 : %load chart%
4 : <head>
5 : <meta charset="utf-8">
6 : <title>Proudly presented by PycCharts</title>
7 : </head>
8 :
9 : <body>
10 : % chart as variable %
11 : variable.myechart
12 :
13 :
14 : </body>
15 :
16 : </html>
17 :
Traceback:
File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/gnss_monitor/scr/monitor/views.py" in test
66. return render(request,'monitor/chart.html')
File "/usr/local/lib/python3.4/dist-packages/django/shortcuts.py" in render
36. content = loader.render_to_string(template_name, context, request, using=using)
File "/usr/local/lib/python3.4/dist-packages/django/template/loader.py" in render_to_string
61. template = get_template(template_name, using=using)
File "/usr/local/lib/python3.4/dist-packages/django/template/loader.py" in get_template
15. return engine.get_template(template_name)
File "/usr/local/lib/python3.4/dist-packages/django/template/backends/django.py" in get_template
34. return Template(self.engine.get_template(template_name), self)
File "/usr/local/lib/python3.4/dist-packages/django/template/engine.py" in get_template
144. template, origin = self.find_template(template_name)
File "/usr/local/lib/python3.4/dist-packages/django/template/engine.py" in find_template
126. template = loader.get_template(name, skip=skip)
File "/usr/local/lib/python3.4/dist-packages/django/template/loaders/base.py" in get_template
30. contents, origin, origin.template_name, self.engine,
File "/usr/local/lib/python3.4/dist-packages/django/template/base.py" in __init__
160. self.nodelist = self.compile_nodelist()
File "/usr/local/lib/python3.4/dist-packages/django/template/base.py" in compile_nodelist
198. return parser.parse()
File "/usr/local/lib/python3.4/dist-packages/django/template/base.py" in parse
483. raise self.error(token, e)
File "/usr/local/lib/python3.4/dist-packages/django/template/base.py" in parse
481. compiled_result = compile_func(self, token)
File "/usr/local/lib/python3.4/dist-packages/django/template/library.py" in compile_func
121. kwonly, kwonly_defaults, takes_context, function_name,
File "/usr/local/lib/python3.4/dist-packages/django/template/library.py" in parse_bits
245. if params[0] == 'context':
Exception Type: IndexError at /chart/
Exception Value: list index out of range
【问题讨论】:
【参考方案1】:您可以使用as
语法将标签的结果分配给模板变量,然后通过.
访问变量的每个元素:
% chart as variable %
variable.myechart
variable.host
variable.script_list
【讨论】:
如果我使用它,我会收到列表索引超出范围错误消息。我忘了提到我使用的是 Django 2.0 @bummm26 添加完整的跟踪确认 我将我的回溯添加到我的问题中。 @bummm26 由于您使用的是takes_context
,因此您的自定义标签应至少采用一个参数:context
:def chart(context)
。或者你可以删除takes_context
。以上是关于通过 simple_tag 向 Django 模板发送数据的主要内容,如果未能解决你的问题,请参考以下文章
自定义模板方法(类似django中的simple_tag) | Tornado