我的django模板中有{%for%}循环问题。
models.py:
-*- coding: utf-8 -*- from django.db import models class Country(models.Model): title = models.CharField(max_length=100, verbose_name="Country") published = models.DateTimeField(verbose_name="Date") def __unicode__(self): return self.title class Nodes(models.Model): node = models.CharField(max_length=150, verbose_name="Node") panelists = models.IntegerField() def __unicode__(self): return self.node
views.py:
from django.shortcuts import render from countries.models import Country from countries.models import Nodes def nodes(request): return render(request, 'country/country.html', {'nodes' : Nodes.objects.all()}) def countries(request): return render(request, 'countries/countries.html', {'countries' : Country.objects.all()}) def country(request, country_id): return render(request, 'country/country.html', {'country' : Country.objects.get(id=country_id)})
在我的模板 country.html 中,我有:
<h2 class="title">{{ country.title }}</h2>
<nav>
<ul>
{% for n in nodes %}
<li>{{ n.node }}</li>
{% endfor %}
</ul>
</nav>
这不起作用。请问你能帮帮我吗? 我知道如果我更改 country.html 文件:
<h2 class="title">{{ country.title }}</h2>
<nav>
<ul>
{% for n in nodes %}
<h2>TEST</h2>
<li>{{ n.node }}</li>
{% endfor %}
</ul>
</nav>
我也看不到“TEST”。因此,所有这些陈述都被忽略了。
答案 0 :(得分:1)
如果您要尝试example.com/country/country_id
,则无法打印节点,因为它们不在视图功能的上下文中。
尝试这样做:
def country(request, country_id):
context_dict = {}
try:
nodes = Nodes.objects.all()
context_dict['username'] = nodes
country = Country.objects.filter(id=country_id)
context_dict['posts'] = country
except Country.DoesNotExist:
return redirect('index')
return render(request, 'country/country.html', context_dict, )
我认为您犯的错误之一是Country.objects.get(id=country_id)
,因为您只是获取了ID,我可以在您的模板中看到您正在尝试获取国家/地区标题。最好的办法是,由于您尝试获取特定country_id
的页面,因此在尝试查询Country模型时必须使用filter
。不要忘记urls.py
。
它应该看起来像这样
url(r'^country/(?P<country_id>\d+)/$', views.country, name='country'),
尝试一下,让我知道,如果它仍然不起作用,你会得到什么样的错误。
答案 1 :(得分:0)
def country(request, country_id): return render(request, 'country/country.html', {'country' : Country.objects.get(id=country_id), 'nodes' : Nodes.objects.all()})