3

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

我也应该在家里的某个地方定义视图吗?

4

2 回答 2

2

看来,当你使用

url(r'^$', TemplateView.as_view(template_name='pages/home.html') ,  name="home")

你根本没有定义posts。要使其正常工作,您必须将 context with 传递posts给此name="home"视图,但您使用的 defaultas_view未传递posts

我会这样:

新闻/urls.py:

url(r'^$', views.home,  name="home")

新闻/views.py:

from news.models import News
from django.shortcuts import render
from django.template import RequestContext

def home(request):
   posts = News.objects.all()
   return render(request, 'home.html', {'posts':posts })

新闻/模板/news.html:

{% load i18n %} 
{% block inner_content %}
<h2>News</h2>
    :D
    {% for post in posts %}
    {{ post.title }}
    {{ post.body }}
    {% endfor %}
{% endblock inner_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 %}
于 2016-03-18T10:19:06.323 回答
-1

您是否在调用 http://127.0.0.1:8000时在请求上下文中传递帖子

于 2016-03-18T10:17:17.853 回答