问题:
我试图简单地遍历我的Category模型并显示一个类别列表。我已成功完成帖子,但出于某种原因,我无法使用我的类别模型(它甚至没有通过Sub Sort()
Rows("32:46").EntireRow.Hidden = True
Dim oneRange As Range
Set oneRange = Range("B12:C66")
oneRange.Sort Key1:=Range("C12"), Order1:=xlAscending, Header:=xlNo, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
Rows("32:46").EntireRow.Hidden = False
End Sub
语句)。因此,{% if categories %}
及以下内容根本不会呈现。
我目前在我的数据库中有两个类别(“健身”和“营养”)。它们在我的管理员中,当我通过命令行查询时它们也会出现。我也可以从我的'post_detail'页面成功链接到它们(并显示一个类别中的所有帖子)。但是,我似乎无法迭代模型以将所有类别显示为列表...
代码:
post_list.html
<h2>Categories:</h2>
models.py
<div class="container">
<h2>Categories:</h2>
{% if categories %}
<h2>Categories</h2>
<ul>
{% for category in categories %}
<li>{{ category.name }}</li>
{% endfor %}
</ul>
{% endif %}
</div>
views.py
from django.db import models
from django.utils import timezone
from django.template.defaultfilters import slugify
class Category(models.Model):
name = models.CharField(max_length=255, blank=False, default='')
slug = models.SlugField(max_length=100, default='', unique=True)
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
ordering = ['name']
def __str__(self):
return self.name
def __unicode__(self):
return self.name
urls.py
from .models import Post, Category
from .forms import PostForm
from django.shortcuts import redirect
from django.db.models import Count
def category_detail( request, slug ):
category = get_object_or_404( Category, slug= slug )
context = {
'category': category,
'posts': category.post_set.all()
}
return render( request,'blog/category_detail.html', context )
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
context = {
'categories': getSortedCategories()
}
return render(request, 'blog/post_list.html', {'posts': posts})
答案 0 :(得分:4)
您不在模板上下文中传输类别,您需要重写返回表达式,如下所示:
return render(request, 'blog/post_list.html', {'posts': posts, 'categories': getSortedCategories()})