首页 文章

对于django模板中的语句不起作用

提问于
浏览
0

我的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>

而且's doesn' t工作 . 请问你能帮帮我吗?我知道如果我改变 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” . 因此所有这些陈述都被忽略了 .

2 回答

  • 1

    好的,我解决了这个问题 . 我没有't know I can' t使两个函数与同一个模板相关 . 现在 views.py 看起来:

    def country(request, country_id):
            return render(request, 'country/country.html', {'country' : Country.objects.get(id=country_id), 'nodes' : Nodes.objects.all()})
    
  • 0

    如果你试图去 example.com/country/country_id ,你在视图函数的上下文中赢得了't be able to print the nodes, since they aren' . 尝试这样做:

    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,我可以在你的模板中看到你想要获得国家 Headers . 最好的办法是,因为您正在尝试获取特定 country_id 的页面,所以当您尝试查询Country模型时,必须使用 filter . 并且不要忘记 urls.py . 看起来应该是这样的

    url(r'^country/(?P<country_id>\d+)/$', views.country, name='country'),

    尝试一下,让我知道,如果它仍然不起作用,你会得到什么样的错误 .

相关问题