Django 快速搭建博客 第八节(自定义模板,归档,分类页面)

来源:互联网 发布:linux boot repair 编辑:程序博客网 时间:2024/06/06 03:57
距离上一节已经过去了一两天了,上一节我们学到了markdown高亮文章详情页,这次学习使用自定义模板标签,把右边的最新,归档,分类给写一下

1 自定义模板标签

1, 博客右边有最新文章,归档,分类和标签云,这四项内容在每个页面,不管是首页还是文章详情页都会进行显示,so,我们统一一下一套模板标签进行数据的显示

类似于一开始的模板标签{% static %} 这个就是模板标签,我们自定义的模板标签需要遵循Django的规范,以下是步骤:

1, 在blog应用下新建一个templatetags包,注意以下包是有init.py文件的,然后再在templatetags目录下创建一个blog_tags.py文件,这个文件存放自定义模板的代码

snakeson@snakeson-Inspiron-5421:~/developer/django/djangoblog/blogproject/blog$ tree.├── admin.py├── apps.py├── __init__.py├── migrations│   ├── 0001_initial.py│   ├── __init__.py│   └── __pycache__│       ├── 0001_initial.cpython-35.pyc│       └── __init__.cpython-35.pyc├── models.py├── __pycache__│   ├── admin.cpython-35.pyc│   ├── __init__.cpython-35.pyc│   ├── models.cpython-35.pyc│   ├── urls.cpython-35.pyc│   └── views.cpython-35.pyc├── static│   └── blog│       ├── css│       │   ├── bootstrap.min.css│       │   ├── custom.css│       │   ├── highlights│       │   │   ├── autumn.css│       │   │   ├── borland.css│       │   │   ├── bw.css│       │   │   ├── colorful.css│       │   │   ├── default.css│       │   │   ├── emacs.css│       │   │   ├── friendly.css│       │   │   ├── fruity.css│       │   │   ├── github.css│       │   │   ├── manni.css│       │   │   ├── monokai.css│       │   │   ├── murphy.css│       │   │   ├── native.css│       │   │   ├── pastie.css│       │   │   ├── perldoc.css│       │   │   ├── tango.css│       │   │   ├── trac.css│       │   │   ├── vim.css│       │   │   ├── vs.css│       │   │   └── zenburn.css│       │   └── pace.css│       └── js│           ├── bootstrap.min.js│           ├── jquery-2.1.3.min.js│           ├── modernizr.custom.js│           ├── pace.min.js│           └── script.js├── templatetags│   ├── blog_tags.py│   ├── __init__.py│   └── __pycache__│       ├── blog_tags.cpython-35.pyc│       └── __init__.cpython-35.pyc├── tests.py├── urls.py└── views.py

这时候显示的应该是上面的tree结构

2 ,下面我们开始编写模板代码:

/blog/templatetags/blog_tags.py


from django import templatefrom ..models import Post,Category# 注册模板register = template.Library()#1. 最新模板:查找最新的五条文章(装饰)@register.simple_tagdef get_recent_posts(num=5):    return Post.objects.all().order_by('-created_time')[:num]#2. 归档模板:精确到月份降序排序@register.simple_tagdef archives():    return Post.objects.all().dates('created_time','month',order='DESC')#3. 分类模板@register.simple_tagdef get_categories():    return Category.objects.all()

导入template这个模块,实例化template.Library类,并装饰三个方法,这样,我们就可以在模板中使用语法{% get_recent_posts %}这样子的语法了。 simple_tag是在1.9之后才会生效的。

3, 打开base.html

{% load staticfiles %}{% load blog_tags %}<!DOCTYPE html><html><head>    <title>Black &amp; White</title>    <!-- meta -->    <meta charset="UTF-8">

加入{% load blog_tags %}

4,然后找到base.html里面的最新文章,归档,分类,把里面的内容更新一下:

 <div class="widget widget-recent-posts">                    <h3 class="widget-title">最新文章</h3>                    {% get_recent_posts as recent_post_list %}                    <ul>                        {% for post in recent_post_list %}                        <li>                            <a href="{{ post.get_absolute_url }}">{{ post.title }}</a>                        </li>                        {% empty %}                          暂无文章                        {% endfor %}                    </ul>                </div>                <div class="widget widget-archives">                    <h3 class="widget-title">归档</h3>                    {% archives as date_list %}                    <ul>                        {% for date in date_list %}                        <li>                            <a href="{% url 'blog:archives' date.year date.month %}">                                {{ date.year }}{{ date.month }}</a>                        </li>                        {% empty %}                        暂无归档                        {% endfor %}                    </ul>                </div>                <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">(13)</span>                            </a>                        </li>                        {% empty %}                        暂无分类!                        {% endfor %}                    </ul>                </div>

这样子就把我们博客右边的内容更新完了, 不过这时候是不可以进行点击跳转链接的,上面的代码可以暂时把<a标签下的href的点击事件给去掉。(注意:确保模板标签的语法使用正确,即 {% load blog_tags %},注意 { 和 % 以及 % 和 } 之间没有任何空格)


2 归档,分类点击事件的完整,页面的完善

(1), 归档

1 博客主页显示了全部的文章,使用的函数是Post.objects.all()来获取全部文章,但是归档里面是获取某个月份的文章,当然你也可以获取某日下的文章,因为你可能一天发布好几篇文章, 我们这里使用一个新的函数filter来过滤掉
1.1 写blog/views.py 视图:

# 归档视图def archives(request,year,month):    post_list = Post.objects.filter(created_time__year=year,                                    created_time__month=month                                    ).order_by('-created_time')    return render(request,'blog/index.html',context={'post_list':post_list})

提醒一下,一定要是created_time_year 前面一根线,后面两根线,不然有的是时间找bug,第一次,第二次写的时候,我都呵呵了,说粗心也不是,不过总算是能记住这里了,这里我们按照降序的时间进行归档排序,传入的year和month 是因为我们要根据xx年xx月进行归档

1.2 配置blog/urls.py 规则

    #归档    url(r'^archives/(?P<year>[0-9]{4})/(?P<month>[0-9]{1,2})/$',views.archives,name='archives'),

归档:url(r’^archives/(?P[0-9]{4})/(?P[0-9]{1,2})/$’,views.archives,name=’archives’),

这里的(?P)代表捕获一组,因为传的是year,year四位数,后面传的是month

1.3 修改base.html
我们找到归档

{% for date in date_list %}<li>  <a href="{% url 'blog:archives' date.year date.month %}">    {{ date.year }}{{ date.month }}</a></li>{% endfor %}

这里使用的href双引号的是属于不是硬编码的那种,意思是对应的url为blog下的archives的函数,然后传入的参数是date.year和date.month
具体来说,就是根据created_timeyearmonth属性过滤,筛选出文章发表在对应的 year 年和 month 月的文章。注意这里created_time是 Python 的date对象,其有一个yearmonth属性,我们在 [页面侧边栏:使用自定义模板标签](http://zmrenwu.com/post/12/) 使用过这个属性

这样子归档的代码就写好了,

(2)分类

1.1 视图函数
/blog/views.py

# 分类视图def category(request,pk):    cate = get_object_or_404(Category,pk=pk)    post_list = Post.objects.filter(category=cate).order_by('-created_time')    return render(request,'blog/index.html',context={'post_list':post_list})

1.2 配置blog/urls.py 规则
/blog/urls.py

    # 分类    url(r'^category/(?P<pk>[0-9]+)/$',views.category,name='category')

1.3 修改base.html
我们找到分类

                        {% for category in category_list %}                        <li>                            <a href="{% url 'blog:category' category.pk %}">                                {{ category.name }} <span class="post-count">(13)</span>                            </a>                        </li>                        {% empty %}                        暂无分类!                        {% endfor %}

现在我们点击分类与归档的链接,然后就会跳转到新的页面了。

(这一节,没有粘贴图片的工作,写的有点蛋疼,下一节用图片写上会稍微容易懂一些)

阅读全文
0 0
原创粉丝点击