在学习有这样一个程序要求实现单个投票项的总投票数和项数
使用一般方法过于复杂,最优法是使用自定义模板标签。
<div class="panel panel-default">
    <div class="panel-heading">Panel heading</div>
    <ul class="list-group">{% for poll in all_polls %}
        <li class="list-group-item">
<a href="{% url 'poll_detail' poll.id %}"><span class="glyphicon glyphicon-check" aria-hidden="true"></span>  
<span>总票数:{{ poll.id|show_votes }}    
项数:{{ poll.id|show_items }} {{ poll.name }} add by {{ poll.user }},created at {{ poll.created }}</span>  
</a> 
        </li>{% endfor %}</ul>
</div>
其中,总票数:{{ poll.id|show_votes }}和项数:{{ poll.id|show_items }}中的show_votes,show_items 属于自定义模板标签。其实show_votes属于函数,poll.id是它的参数,多个参数使用:连接。
创建自定义模板标签,在APP目录下新建一个文件夹templates,在新建一个.py文件,templates下要建一个__init__.py文件,
from django import template  
from pollitem import models
register = template.Library()  
@register.filter(name='show_items')  
def show_items(value):  
    try:  
        poll = models.Poll.objects.get(id=int(value))  
        items = models.PollItem.objects.filter(poll=poll).count()  
    except:  
        items = 0  
    return items  
@register.filter(name='show_votes')  
def show_votes(value):  
    try:  
        poll = models.Poll.objects.get(id=int(value))  
        votes = 0  
        pollitems = models.PollItem.objects.filter(poll=poll)  
        for pollitem in pollitems:  
            votes = votes + pollitem.vote  
    except:  
        votes = 0  
    return votes  
重点:
第一处:导入template,使用template.Library()产生注册对象register 
第二处:使用修饰词@register.filter(name='show_votes')把自定义模板标签注册成模板语言得一部分。
第三使用:在使用的文件前加上
评论列表
已有0条评论