利用Django实现的功能如下:
- 添加archives视图类和tag视图类
- 优化模板,显示分类帖子数量
具体实现过程如下
1.添加archives视图类和tag视图类:
archives显示档案类,tag显示标签云。
class ArchivesView(ListView):
model = Post
template_name = 'blog/index.html'
context_object_name = 'post_list'
def get_queryset(self):
#获得URL中的参数,利用关键字参数
year = self.kwargs.get('year')
month = self.kwargs.get('month')
#返回当前年月的帖子,按时间倒序排序。
return super(ArchivesView,self).get_queryset().filter(created_time__year=year, created_time__month=month).order_by('-created_time')
class TagView(ListView):
model = Post
template_name = 'blog/index.html'
context_object_name = 'post_list'
def get_queryset(self):
#通过url传入的pk,获得当前的标签对象
tag = get_object_or_404(Tag, pk=self.kwargs.get('pk'))
#返回所有该标签的帖子
return super(TagView,self).get_queryset().filter(tags=tag)
url的添加:
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.PostDetailView.as_view(), name='detail'),
url(r'^category/(?P<pk>[0-9]+)/$', views.CategoryView.as_view(), name='category'),
url(r'^tag/(?P<pk>[0-9]+)/$', views.TagView.as_view(), name='tag'),
url(r'^archives/(?P<year>[0-9]{4})/(?P<month>[0-9]{1,2})/$', views.ArchivesView.as_view(), name='archives'),
]
base模板:
增加标签云的模板显示
<div class="widget widget-tag-cloud">
<h3 class="widget-title">标签云</h3>
{% get_tags as tag_list %}
<ul>
{% for tag in tag_list %}
<li>
<a href="{% url 'blog:tag' tag.pk %}">{{ tag.name }}</a>
</li>
{% empty %}
暂无标签!
{% endfor %}
</ul>
</div>
注册模板标签:
from ..models import Post, Category,Tag
from django.db.models.aggregates import Count
...
@register.simple_tag
def get_categories():
#annotate有很高的效率
#添加annotate注释,功能与添加字段类似
return Category.objects.annotate(num_posts=Count('post')).filter(num_posts__gt=0)
@register.simple_tag
def get_tags():
#标签中帖子大于0的标签才会返回
return Tag.objects.annotate(num_posts=Count('post')).filter(num_posts__gt=0)
2.优化模板:
类别可以显示相应的帖子数量。
<div class="widget widget-category">
<h3 class="widget-title">分类</h3>
{% get_categories as category_list %}
<ul>
{% for category in category_list %}
<li>
<a href="{% url 'blog:category' category.pk %}">{{ category.name }} <span
class="post-count">({{ category.num_posts }})</span></a>
</li>
{% empty %}
暂无分类!
{% endfor %}
</ul>
</div>