当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代码段(\ 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
提前致谢!
答案 0 :(得分:1)
您似乎没有充分命名@register.inclusion_tag('blog/index_table.html', takes_context=True)
模板。
请改为尝试:
{{1}}