码迷,mamicode.com
首页 > 其他好文 > 详细

Django之便签生成

时间:2016-04-20 11:13:57      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

 

myblog_tag.py

#coding:utf-8
__author__ = ‘similarface‘
from django import template

register=template.Library()

from ..models import Post

@register.simple_tag
def total_posts():
‘‘‘
文章总数
:return:返回发布的文章总篇数
‘‘‘
return Post.published.count()

 模版:

{% load blog_tags %}
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}{% endblock %}</title>
    <link href="{% static "css/blog.css" %}" rel="stylesheet">
</head>
<body>
    <div id="content">
        {% block content %}
        {% endblock %}
    </div>
    <div id="siderbar">
        <h2>我的博客</h2>
        <p>目前已写文章总数 {% total_posts %} .</p>
    </div>
</body>
</html>

看下面,哦,还是挺丑的 

技术分享

 纳尼 这也太low了

go on add myblog_tag.py here:

@register.inclusion_tag(‘myblog/post/latest_posts.html‘)
def show_latest_posts(count=5):
    ‘‘‘
    最新count篇文章
    :param count: 文章的篇数 默认5篇
    :return:最新count篇文章的对象
    ‘‘‘
    latest_posts=Post.published.order_by(‘-publish‘)[:count]
    return {‘latest_posts‘:latest_posts}
#myblog/post/latest_posts.html:
<ul>
    {% for post in latest_posts %}
        <li>
            <a href="{{ post.get_absolute_url }}">{{ post.title }}</a>
        </li>
    {% endfor %}
</ul>

 模版修改下:

<div id="siderbar">
        <h2>我的博客</h2>
        <p>目前已写文章总数 {% total_posts %} .</p>
        <h3>最新文章</h3>
        {% show_latest_posts 3 %}
    </div>

 技术分享

 哦 原来是个??。。。

 哦 你再改改试试

#coding:utf-8
__author__ = similarface
from django import template
from django.db.models import Count
register=template.Library()
from  ..models import Post

@register.simple_tag()
def total_posts():
    ‘‘‘
    文章总数
    :return:返回发布的文章总篇数
    ‘‘‘
    return Post.published.count()


@register.inclusion_tag(myblog/post/latest_posts.html)
def show_latest_posts(count=5):
    ‘‘‘
    最新count篇文章
    :param count: 文章的篇数 默认5篇
    :return:最新count篇文章的对象
    ‘‘‘
    latest_posts=Post.published.order_by(-publish)[:count]
    return {latest_posts:latest_posts}

@register.assignment_tag
def get_most_commented_posts(count=5):
    ‘‘‘
    返回评论最多的前count篇文章
    :param count:默认为5
    :return:返回评论最多的前count篇文章
    ‘‘‘
    return Post.published.annotate(total_comments=Count(comments)).order_by(-total_comments)[:count]

模版:

<div id="siderbar">
        <h2>我的博客</h2>
        <p>目前已写文章总数 {% total_posts %} .</p>
        <h3>最新文章</h3>
        {% show_latest_posts 3 %}
        <h3>最受欢迎的文章</h3>
        {% get_most_commented_posts as most_commented_posts %}
        <ul>
            {% for post in most_commented_posts %}
            <li>
                <a href="{{ post.get_absoulte_url }}">{{ post.title }}</a>
            </li>
            {% endfor %}
        </ul>
    </div>

 尼玛这。。。感觉记不住

技术分享

Django之便签生成

标签:

原文地址:http://www.cnblogs.com/similarface/p/5411539.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!