当我运行我的 django 服务器时它显示错误但我找不到它。它显示模板语法错误
Unclosed tag on line 2: 'if'. Looking for one of: elif, else, endif.
Request Method: GET
Request URL: http://127.0.0.1:8000/tag/django/
Django Version: 2.0.5
Exception Type: TemplateSyntaxError
Exception Value:
Unclosed tag on line 2: 'if'. Looking for one of: elif, else, endif.
Exception Location: C:\Users\user\Anaconda3\envs\amirdjango\lib\site-packages\django\template\base.py in unclosed_block_tag, line 549
Python Executable: C:\Users\user\Anaconda3\envs\amirdjango\python.exe
Python Version: 3.6.5
Python Path:
['H:\\Amir\\Django\\myDjangostuff\\suorganizer',
'C:\\Users\\user\\Anaconda3\\envs\\amirdjango\\python36.zip',
'C:\\Users\\user\\Anaconda3\\envs\\amirdjango\\DLLs',
'C:\\Users\\user\\Anaconda3\\envs\\amirdjango\\lib',
'C:\\Users\\user\\Anaconda3\\envs\\amirdjango',
'C:\\Users\\user\\Anaconda3\\envs\\amirdjango\\lib\\site-packages']
Server time: Tue, 28 Aug 2018 15:59:01 +0000
-Error: Unclosed tag on line 2: 'if'. Looking for one of: elif, else, endif.
django 模板在这里:-
<h2> {{ tag.name|title }} </h2>
{% if tag.startup_set.all %}
<section>
<h3>Startup {{ tag.startup_set.count|pluralize }}</h3>
<p>
Tag is associated with
{{ tag.startup_set.count }}
startup {{ tag.startup_set.count|pluralize }}
</p>
<ul>
{ % for startup in tag.startup_set.all % }
<li><a href="">
{ { startup.name } }
</a></li>
{ % endfor % }
</ul>
</section>
{ % endif % }
{ % if tag.blog_posts.all % }
<section>
<h3>Blog Post { { tag.blog_posts.count|pluralize } } </h3>
<ul>
{ % for post in tag.blog_posts.all % }
<li><a href="">
{ { post.title|title } }
</a></li>
{ % endfor % }
</ul>
</section>
{ % endif % }
{ % if not tag.startup_set.all and not tag.blog_posts.all % }
<p>This tag is not related to any content.</p>
{ % endif % }
最佳答案
Django 标签被 {%
和 %}
包围(变量带有 {{
和 }}
但是让我们暂时忽略它)。
但在您的代码中,除了第一个 {% if ... %}
语句外,您始终这样写:
<s>{ %</s> endif <s>% }</s>
注意 {
和 %
之间的空格,Django 不会将其解析为 Django 标签。因此,您应该删除空格,使标签显示为:
<b>{%</b> endif <b>%}</b>
因此您应该将标签固定为:
<h2> {{ tag.name|title }} </h2>
{% if tag.startup_set.all %}
<section>
<h3>Startup {{ tag.startup_set.count|pluralize }}</h3>
<p>
Tag is associated with
{{ tag.startup_set.count }}
startup {{ tag.startup_set.count|pluralize }}
</p>
<ul>
<b>{% for startup in tag.startup_set.all %}</b>
<li><a href="">
{ { startup.name } }
</a></li>
<b>{% endfor %}</b>
</ul>
</section>
<b>{% endif %}</b>
<b>{% if tag.blog_posts.all %}</b>
<section>
<h3>Blog Post { { tag.blog_posts.count|pluralize } } </h3>
<ul>
<b>{% for post in tag.blog_posts.all %}</b>
<li><a href="">
{ { post.title|title } }
</a></li>
<b>{% endfor %}</b>
</ul>
</section>
<b>{% endif %}</b>
<b>{% if not tag.startup_set.all and not tag.blog_posts.all %}</b>
<p>This tag is not related to any content.</p>
<b>{% endif %}</b>
我还建议避免将查询(和其他业务逻辑)写入模板。通常这更多是 View 的任务。
关于python - Django 模板语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52062691/