【发布时间】:2017-06-29 01:35:42
【问题描述】:
当takes_context 与包含标签一起使用时,有人知道如何纠正错误吗?我相信问题可能出在与模板标签输出的 context[] 关联的变量上,但我不确定括号内应该包含什么。 渲染的逻辑在views.py(\mysite\blog\views.py)中:
from django.shortcuts import render
from .models import Post
def DJ_LastDay(request):
p = Post.objects.latest('Day')
posts = Post.objects.filter(Day=p.Day)
return render(request, 'blog/DJ_LastDay.html', {'posts': posts})
包含标签(\mysite\blog\templatetags\index_table.py):
from django import template
from blog.models import Post
register = template.Library()
@register.inclusion_tag('index_table.html', takes_context=True)
def DJ_LastDay(context):
return {'posts': context['posts']}
包含标记的父 HTML sn-p (\mysite\blog\templates\blog\DJ_LastDay.html):
{% block content %}
<div id="section" style="white-space:nowrap;"> <!--Margin added to keep element to the right of aside bar-->
<ul>
<li>Period to display:</li>
<li><a href="{% url 'blog:DJ_LastDay' %}">Last Trading Day</a></li>
<li><a href="{% url 'blog:DJ_LastWk' %}">Last Week</a></li>
<li><a href="{% url 'blog:DJ_LastMnth' %}">Last Month</a></li>
<li><a href="{% url 'blog:DJ_LastQtr' %}">Last Quarter</a></li>
<li><a href="{% url 'blog:DJ_LastYr' %}">Last Year</a></li>
</ul>
</div>
{% load index_table %}
{% DJ_LastDay %}
{% endblock %}
子 HTML 模板 (\mysite\blog\templates\blog\index_table.html):
<table id="myTable" border="8" style="border-collapse: collapse; width:1000px;">
<caption>DJ Index ({{ posts|length }} symbols returned) - Last Day ({% with posts.0 as 1st %} {{ 1st.Day }} {% endwith %})
</caption>
<thead>
<tr style="color:white;background:black;">
<th>Symbol</th>
<th>Price</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{% for post in posts reversed %}
<tr align="center">
<td><a style="text-decoration:none;" href="/results/?q={{ post.Symbol }}">{{ post.Symbol }}</a></td>
<td>{% firstof post.LastPrice "N/A" %}</td>
<td>{% firstof post.Name "N/A" %}</td>
</tr>
{% endfor %}
</tbody>
</table>
错误显示为:
TemplateDoesNotExist at /DJ_LastDay/
index_table.html
提前致谢!
【问题讨论】:
-
也许您需要进一步命名您的
index_table.html模板引用?你试过@register.inclusion_tag('blog/index_table.html', takes_context=True) -
好的,现在可以了,谢谢!
-
我会将我在评论中所说的话作为答案发布。
标签: django