一、Django实现归档的几种方式
1、简单的实现
视图:
#views.py
defarchives(request,year,month):
"""返回点击归档后对应的文章"""
post_list=Post.objects.filter(created_time__year=year,
created_time__month=month
).order_by('-created_time')
returnrender(request,'blog/index.html',context={'post_list':post_list})
路由:
#urls.py
url(r'^archives/(?P[0-9]{4})/(?P[0-9]{1,2})/$',views.archives,name='archives'),
自定义标签模板
#templatetags/blog_tags.py
@register.simple_tag
defarchives():
"""注册一个自定义标签"""
returnPost.objects.dates('created_time','month',order='DESC')
#这里讲一下dates
#可以根据时间赛选返回一个去重后的时间的Queryset
在模板中使用
#index.html
<divclass="widgetwidget-archives">
<h3class="widget-title">归档</h3
{{%archivesasdate_list%}
<ul>
{%fordateindate_list%}
<li>
<ahref="/archives/{{date.year}}/{{date.month}}">{{date.year}}年{{date.month}}月</a>
</li>
{%empty%}
暂无归档!
{%endfor%}
</ul>
</div>
2、使用django自带的regroup标签
regroup标签的相文档:
https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#regroup
视图函数:
#views.py
defarchives(request):
"""
文章归档
:paramrequest:
:return:
"""
dates=Blog.objects.all().order_by('-create_time')
data={
'title':'文章归档',
'dates':dates
}
returnrender(request,'blog/archives.html',context=data)
模板:
#html使用的layui
<h2>文章归档</h2>
<hrclass="layui-bg-red">
<ulclass="layui-timeline">
{%regroupdatesbycreate_time.yearasyear_blog_group%}
{%foryearinyear_blog_group%}
<liclass="layui-timeline-item">
<iclass="layui-iconlayui-timeline-axis"></i>
<divclass="layui-timeline-contentlayui-textyear-ul-list">
<h3class="layui-timeline-title">{{year.grouper}}年</h3>
<ulclass="layui-timeline">
{%regroupyear.listbycreate_time.monthasmonth_blog_group%}
{%formonthinmonth_blog_group%}
<liclass="layui-timeline-item">
<iclass="layui-iconlayui-timeline-axis"></i>
<divclass="layui-timeline-contentlayui-text">
<h3class="layui-timeline-title">{{month.grouper}}月</h3>
<ul>
{%forbloginmonth.list%}
<li>
<ahref="{%url'blog:read_blog'%}?blogid={{blog.id}}"target="_blank">
{{blog.create_time|date:'m-d'}}--{{blog.title}}</a>
</li>
{%endfor%}
</ul>
</div>
</li>
{%endfor%}
</ul>
</div>
</li>
{%empty%}
<h3"color:red;">暂无归档</h3>
{%endfor%}
</ul>
其中样式我使用了layui带的 效果图:
网友评论