我在Django项目的URL /about/
和/work/
处有一个页面。每个页面都有导航,需要显示top_level_nav=True
的所有页面。每个页面都需要在每个页面上显示text
。
我已成功获得导航中列出的所有网页,但/about/
和/work/
页面上的内容显示所有网页中的text
。
# nav
-About
–Work
# text
<p>This is the about page.</p>
# nav
-About
–Work
# text
<p>This is the Work page.</p>
/about/
和/work/
页面都显示为:#nav
–About
–Work
<p>This is the about page.</p>
<p>This is the Work page.</p>
基本上,所有文字内容都显示在所有页面上。
from django.shortcuts import render, get_object_or_404
from site_2015.models import Page
from site_2015.models import Home
def home(request):
home = get_object_or_404(Home)
# now return the rendered template
return render(request, 'site_2015/home.html', {'home': home})
def page(request, slug):
# get the Page object
pages = Page.objects.filter(top_level_nav=True).order_by('-pub_date')
page = get_object_or_404(Page, slug=slug)
# now return the rendered template
return render(request, 'site_2015/page.html', {'page': pages})
return render(request, 'site_2015/page.html', {'content': page})
from django.db import models
from django.core.urlresolvers import reverse
class Home(models.Model):
title = models.CharField(max_length=200)
text = models.TextField()
header_image = models.FileField(upload_to='page/%Y/%m/%d', null=True, blank=True)
def __unicode__(self):
return u'%s' % self.title
def get_absolute_url(self):
return reverse('site_2015.views.home')
class Page(models.Model):
title = models.CharField(max_length=200)
nav_text = models.CharField(max_length=30, null=True, blank=True)
slug = models.SlugField(unique=True, max_length=255, null=True, blank=True)
text = models.TextField()
header_image = models.FileField(upload_to='page/%Y/%m/%d', null=True, blank=True)
pub_date = models.DateTimeField(null=True, blank=True)
top_level_nav = models.BooleanField(default=False)
def __unicode__(self):
return u'%s' % self.title
def get_absolute_url(self):
return reverse('site_2015.views.page', args=[self.slug])
class HomeImg(models.Model):
home = models.ForeignKey('Home', related_name='images')
image = models.FileField(upload_to='page/%Y/%m/%d', null=True, blank=True)
class PageImg(models.Model):
page = models.ForeignKey('Page', related_name='images')
image = models.FileField(upload_to='page/%Y/%m/%d', null=True, blank=True)
<nav>
<ul>
<li><a href="/">Home</a></li>
{% for page in page %}
<li><a href="/{{ page.slug }}">{{ page.nav_text }}</a></li>
{% endfor %}
</ul>
</nav>
<div class="content">
{% for content in page %}
{{ content.text }}
{% endfor %}
</div>
我知道我for
周围不应该context.text
阻止,但我不确定该怎么做。
答案 0 :(得分:1)
您的问题是尝试使用两个return
语句:
return render(request, 'site_2015/page.html', {'page': pages})
#The second will not get rendered, and content will not be available
return render(request, 'site_2015/page.html', {'content': page})
相反,您希望将字典呈现为一个整体
return render(request, 'site_2015/page.html', {'page': pages, 'content' : page })
然后在你的模板中
<div class="content">
{{ content.text }}
</div>
现在,您可以在模板中直接使用上下文变量content
。