django实现文章归档

一,编写视图,返回文章列表

    class ArchiveView(generic.ListView):
        model = Article
        template_name = 'blog/archive.html'
        context_object_name = 'articles'
        paginate_by = 200

二,前端

{% cache 3600 'cache_archive_html_tag' %}
        <div class="col-lg-8">
            <div class="card border-0 rounded-0 mb-3">
                <div class="card-body f-16 archive">
                    {% regroup articles by create_date.year as year_list %}
                    <ul class="pl-4">
                        {% for article in year_list %}
                        <li>{{ article.grouper }} 年
                            {% regroup article.list by create_date.month as month_list %}
                            <ul class="pl-4">
                                {% for each in month_list %}
                                <li>{{ each.grouper }} 月 (共 {{ each.list|length }} 篇)
                                    <ul class="pl-4">
                                        {% for item in each.list %}
                                        <li class="text-info">{{ item.create_date|date:'m-d' }}&nbsp;&nbsp;<a href="{{ item.get_absolute_url }}">{{ item.title }}</a></li>
                                        {% endfor %}
                                    </ul>
                                </li>
                                {% endfor %}
                            </ul>
                        </li>
                        {% endfor %}
                    </ul>
                </div>
            </div>
        </div>
        {% endcache %}

三,用到的内置标签

1,cache
我们可以用cache模板标签来缓存模板的一个片段,要是用这个标签,首先要在模板的顶部位置添加{% load cache %}
模板标签{% cache %}将在设定的时间内,缓存标签块中包含的内容。它最少需要两个参数:缓存时间(以秒为单位)以及给缓存片段起的名称
{% load cache %}
{% cache 500 sidebar %}
… sidebar …
{% endcache %}

2,regroup
用对象间共有的属性重组列表
{% regroup %}有三个参数: 要重组的列表、用来分组的属性、结果列表的名字
eg:
可以使用{% regroup %}标签来给每个国家的城市分组:
{% regroup cities by country as country_list %}

  • {% for country in country_list %}
  • {{ country.grouper }}
    • {% for city in country.list %}
    • {{ city.name }}: {{ city.population }}
    • {% endfor %}
  • {% endfor %}
grouper - 分组的项目(例如,字符串“India”或“Japan”)

list - 此群组中所有项目的列表(例如,所有城市的列表,其中country =‘India’)

3,length
length:返回值的长度,适合于字符串和列表

4,date:根据给定的格式格式化日期。

{{ date|date:“Y-m-d H:i:s w” }}

四,效果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值