我的 django (1.9.2) 项目中有一个简单的视图、表单和 2 个模板 传递视图的模板就像一个魅力,迭代并毫无问题地显示想要的值。
然而,当我想将此模板包含到另一个模板中时,不会发生迭代。我试过使用{% include with %}
,但也许我做得不对。
作为主页的模板放在项目模板文件夹中,而要包含的模板在应用程序内
新闻/models.py:
class News(models.Model):
title = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True)
body = models.TextField()
posted = models.DateField(db_index=True, auto_now_add=True)
def __unicode__(self):
return '%s' % self.title
新闻/views.py:
from news.models import News
from django.shortcuts import render
from django.template import RequestContext
def news(request):
posts = News.objects.all()
return render(request, 'news.html',{'posts':posts })
新闻/模板/news.html:
{% load i18n %}
{% block content %}
<h2>News</h2>
:D
{% for post in posts %}
{{ post.title }}
{{ post.body }}
{% endfor %}
{% endblock content %}
模板/home.html:
{% extends "base.html" %}
{% load i18n %}
{% block content %}
<section id="portfolio">
<div class="container">
{% include "news.html" with posts=posts %}
</div>
</section>
{% include "footer.html" %}
{% endblock content %}
在http://127.0.0.1:8000/news/检查时一切正常,但在http://127.0.0.1:8000/仅显示 :D
不知道如何解决这个谢谢:^)
编辑:
对于 Home,我实际上只使用模板,在 url 中它看起来像这样:
url(r'^$', TemplateView.as_view(template_name='pages/home.html') , name="home")
同样对于基础,我使用来自 cookiecutter-django 的 cookie-cutter django
我也应该在家里的某个地方定义视图吗?