Django---过滤器的使用

一、统计博客数量:

法一:使用{{list|length}}方法统计:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    <div><h2>个人博客网站</h2></div>
    <hr>
    {#别名需要用引号#}
    {%for arcile in list%}
        <a href = "{%url 'blogdetail' arcile.pk%}">
            <h3>{{arcile.title}}</h3>

        </a>
        <p>{{arcile.content|truncatechars:10}}</p>
    {%empty%}
        --暂无博客--
    {%endfor%}
    <p>一共有{{list|length}}博客</p>{{count}}(object.all.count()方法:){#显示文章博客数量#}
</body>
</html>

法二:使用视图函数中的objets.all().count()方法统计:

def bloglist(request):
    contenx = {}
    contenx['list'] = Blog.objects.all()#获取所有的文章
    contenx['count'] = Blog.objects.all().count()
    return render_to_response('list.html',contenx)

二、截取博客首页的字数显示使用truncatechars(字数数量),字母使用:truncatewords()截取:

<p>{{arcile.content|truncatechars:10}}</p>

三、没有博客时提示使用{%empty%}标签间隔提示内容:

{%empty%}
        --暂无博客--
    {%endfor%}

四、创建时间格式的调整:使用|date:"时间格式"

<p>作者:{{detail.author}}  创建时间:{{detail.create_time|date:"Y-m-d  H:n:s"}}</p>

五、实现分类页跳转:

实现的逻辑:首先我们要从数据库中取得符合分类的标签页的文章,因此我们通过Blog.objects.filter()的方式筛选出符合分类标签条件的文章,筛选的条件是什么呢?是我们传入的一个条件值,这个值如何获得呢?是通过我们的分类标签中的数据获得,通过get_object_or_404(Blogtype,pk=?)的方法,需要传入一个条件值,那这个值是什么呢?这个值就是我们通过点击而获得的<a href="{%url "blog_with_type"  dtalie.blogname.pk%}">通过选择的标签的对应的id,url------->(发送请求)------->view(处理请求)。

view部分:

from django.shortcuts import render_to_response,get_object_or_404
from .models import Blog,Blogtype
# Create your views here.
def blogdetail(request,aricle_id):
    contenx = {}
    contenx['detail'] = get_object_or_404(Blog,pk = aricle_id)
    return render_to_response('detail.html',contenx)
def bloglist(request):
    contenx = {}
    contenx['list'] = Blog.objects.all()#获取所有的文章
    # contenx['count'] = Blog.objects.all().count()
    return render_to_response('list.html',contenx)

def blog_with_type(request,typename_pk):
    contenx ={}
    typename = get_object_or_404(Blogtype,pk = typename_pk)#拿到传入的类型参数
    contenx['blogs'] = Blog.objects.filter(typename=typename)#筛选出符合类型的博客
    contenx['typename'] = typename#显示分类项目名
    return render_to_response('blog_with_type.html',contenx)

url部分(注意!这个url前面我们加type的原因是让他和前面的那个链接分开一下!不要重复向url 发送请求!)

path('type/<int:typename_pk>',blog_with_type, name='blog_with_type'),

这个部分多回顾几遍!

posted @ 2018-01-31 21:41  jeep-鹏  阅读(420)  评论(0编辑  收藏  举报