For statement in django templates doesn't work
我的django模板中的%for%循环有问题。
模型:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | -*- 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 |
查看:
1 2 3 4 5 6 7 8 9 10 11 12 | 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中,我有:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <h2 class="title">{{ country.title }} <nav> <ul> {% for n in nodes %} <li> {{ n.node }} </li> {% endfor %} </ul> </nav> |
这不管用。你能帮我一下吗?我知道如果我像这样更改country.html文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <h2 class="title">{{ country.title }} <nav> <ul> {% for n in nodes %} TEST <li> {{ n.node }} </li> {% endfor %} </ul> </nav> |
我也看不到"测试"。所以所有这些陈述都被忽略了。
如果您尝试使用
1 2 3 4 5 6 7 8 9 10 11 12 | 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, ) |
我认为你犯的一个错误是
试一试,如果它仍然不起作用,告诉我你会犯什么错误。
好的,我解决了这个问题。我不知道我不能使两个函数与同一个模板相关。now views.py外观:
1 2 | def country(request, country_id): return render(request, 'country/country.html', {'country' : Country.objects.get(id=country_id), 'nodes' : Nodes.objects.all()}) |