1.任务描述:将博文按照时间月份归档
2.源代码:
views.py
def getPage(request, article_list):
paginator = Paginator(article_list, 2)
try:
page = int(request.GET.get('page', 1))
article_list = paginator.page(page)
except (EmptyPage, InvalidPage, PageNotAnInteger):
article_list = paginator.page(1)
return article_list
def archive(request):
try:
# 先获取客户端提交的信息
year = request.GET.get('year', None)
month = request.GET.get('month', None)
article_list = Article.objects.filter(date_publish__icontains=year+'-'+month)
article_list = getPage(request, article_list)
except Exception as e:
logger.error(e)
return render(request, 'archive.html', locals())
archive.html
{% extends 'base.html' %}
{% load staticfiles %}
{% block left_content %}
{% include 'ad.html' %}
<div class="topnews">
<h2>{{ request.GET.year }}/{{ request.GET.month }}文章归档</h2>
{% for article in article_list %}
<div class="blogs">
<ul>
<h3><a href="/">{{ article.title }}</a></h3>
<p>{{ article.desc }}</p>
<p class="autor"><span class="lm f_l">{% for tag in article.tag.all %}<a href="/">{{ tag.name }}</a>
</span>{% endfor %}<span
class="dtime f_l">{{ article.date_publish | date:'Y-m-d' }}</span><span class="viewnum f_r">浏览(<a
href="/">{{ article.click_count }}</a>)</span><span class="pingl f_r">评论(<a
href="/">{{ article.comment_set.all.count }}</a>)</span></p>
</ul>
</div>
{% endfor %}
</div>
{% include 'pagination.html' %}
{% endblock %}
urls.py
from django.conf.urls import url
from blog.views import *
urlpatterns = [
url(r'^$', index, name='index'),
url(r'^archive/$', archive, name='archive'),
]
base.html
<div class="tuwen">
<h3>文章归档</h3>
<ul>
{% for archive in archive_list %}
<li>
<p><span class="tutime font-size-18"><a
href='{% url 'archive' %}?year={{ archive | slice:":4" }}&month={{ archive | slice:"5:7" }}'>{{ archive }}</a></span>
</p>
</li>
{% endfor %}
</ul>
</div>
3.操作流程
点击“文章归档”->2017/09文章归档,刷新左侧文章列表(指定月份的文章)
4.运行结果