将可迭代对象发送到基本模板(例如:'menus = Menu.objects.all()')

时间:2016-06-22 07:57:23

标签: python django html5

当我发送

  

menus = Menu.objects.all()

通过渲染

  

渲染(请求,'index.html',{'菜单':菜单})

它没有给我任何东西,只是空页 但其他变量如

  

info = Info.objects.last()

正常运作

这是view.py

'''这里有一些代码'''

def home(request):
    slides = Slide.objects.order_by('created')[:3]
    main_articles = MainArticle.objects.order_by('created')[:5]
    last_news = News.objects.all()[:4]
    info = OtherInfo.objects.last()
    promo = Promo.objects.last()
    menus = Menu.objects.all()

    return render(request, 'index.html', {'slides': slides,
                                        'main_articles': main_articles,
                                        'last_news': last_news,
                                        'info': info,
                                        'promo': promo,
                                        'menus': menus
                                        })

这是models.py

class Menu(models.Model):
    name = models.CharField(max_length=100)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('created',)


class SubMenu(models.Model):
    menu = models.ForeignKey(Menu, related_name='sub_menu')
    name = models.CharField(max_length=100)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '{} -> {}'.format(self.menu, self.name)

    class Meta:
        ordering = ('created',)

'''其他一些模特在这里'''

这是index.html

{% extends 'base.html' %}  

{% block nav_bar %}
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
    <ul class="nav navbar-nav">
    {% for m in menus.all %}
     {% if m.sub_menu %}
       <li class="dropdown">
       <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">{{ m.name }}<span class="caret"></span></a>
         <ul class="dropdown-menu">
         {% for sub in m.sub_menu.all %}
         <li><a href="{% url 'info-ms' menu=m.name submenu=sub.name %}">{{ sub.name }}</a></li>
          {% endfor %}
         </ul>
       </li>
     {% else %}
       <li>
       <a href="{% url 'info-m' menu=m.name %}">{{ m.name }}</a>
       </li>
     {% endif %}
   {% endfor %}
  </ul>
</div><!-- /.navbar-collapse -->
{% endblock %}

1 个答案:

答案 0 :(得分:1)

如果你通过:

menus = Menu.objects.all()

您可以在模板中使用:

{% for menu in menus %}
...

    {% if menu.sub_menu.exists %}
        {% for submenu in menu.sub_menu.all %}
        ....

您确实已在视图中致电.all()