django 自定义过滤器(filter)处理较为复杂的变量方法

yipeiwu_com6年前Python基础

简述:django 在views中有数据需要通过字典(dict)的方式传递给template,该字典中又包含了字典,而且字典中的键值还是一个对象,在template中处理传递过来的数据的时候,字典不能通过键值的方式取出原有数据,对象不能通过(.)的方式直接取出数据,通过大量地查阅资料,最终通过过滤器(filter)的方式解决!

1、需要传递到template的数据,在 views.py 中的index函数中

latest_article_list 是一个Article对象的列表,包含文章ID、作者、发布时间、分类等各种信息

dic['tag_list'] 为一个列表(文章标签列表)

articles_info是一个以字典为元素的列表,而且该字典中 键'article'对应的不是普通变量,而是一个Article对象

view.py

def index(request):
  latest_article_list = Article.objects.query_by_time()
  articles_info = []
  dic = {}
  for article in latest_article_list:
    taginfo = Article.objects.get(id=article.id)
    dic['tag_list'] = taginfo.tags.all()
    dic['article'] = article;
    articles_info.append(dic)
    dic = {}

  loginform = LoginForm()
  context = {'articles_info':articles_info, 'loginform':loginform}
  return render(request, 'index.html', context)

2、template如何引用views传递过来的变量值?

在index.html中,可以先遍历列表,得到每一个字典变量;

 {% for article_info in articles_info %}

遍历 articles_info 之后的article_info 为一个字典,通过前面的views可以知道里面包含了一个article对象和一个tag_list列表;

对于article_info这个字典变量,在模板中却不能通过键值对获取对应的值,更别说获取Article对象中ID、作者、发布时间等属性值了,为了解决这一问题,这里就需要过滤器才能实现;

3、自定义过滤器

1)、在app目录下建立templagetags文件夹,在此目录下建立空文件 __init__.py和过滤器文件articleinfo.py;

2)、编辑 articleinfo.py,添加过滤器 get_key 和get_attr,get_key获取字典不同键对应的值,get_attr获取Article对象中不同字段对应的值;

articleinfo.py

from django import template
register = template.Library()

@register.filter
def get_key(d, key_name):
  return d.get(key_name)

@register.filter
def get_attr(d, m):
  if hasattr(d, m):
    return getattr(d, m)

4、模板中使用过滤器,获取各种变量值;

index.html中,首先需要通过标签加载上面定义的过滤器文件 articleinfo.py,然后就是index.html模板中调用过滤器了,具体的使用方法见下面的index.html文件;

{% load articleinfo %}

下面的index.html中变量使用的部分代码,使用了双重过滤器提取出了所需要的变量;

比如第4行中

{{ article_info|get_key:"article"|get_attr:"id" }}

首先通过 article_info|get_key:"article" 获取到字典中的article对象,但此处需要的是article对象中的ID属性,由于并不能通过{{ article_info|get_key:"article".id }} 获取到对应的ID值,所以只好双重过滤器来实现了。

index.html

{% for article_info in articles_info %}
  <div class="row">
    <article class="col-xs-12">
      <h3><a id="article_title", href="/focus/{{ article_info|get_key:" rel="external nofollow" article"|get_attr:"id" }}">{{ article_info|get_key:"article"|get_attr:"title" }}</a></h3>
      <div class="article_info">
        <span class="">{{ article_info|get_key:"article"|get_attr:"author" }}</span>
        <span class="">{{ article_info|get_key:"article"|get_attr:"create_time"|date:"Y-m-d H:i" }}</span>
      </div>
      <div class="category">
        分类:
         <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class>{{ article_info|get_key:"article"|get_attr:"category" }}</a>
      </div>
      <div class="category">
        标签:
        {% for tag in article_info|get_key:"tag_list" %}
          <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{{ tag }}</a>
        {% endfor %}
      </div>
      <p>{{ article_info|get_key:"article"|get_attr:"content"|truncatechars_html:80 | safe }}</p>
      <p><button class="btn btn-default" onclick="window.location.href='/focus/{{ article_info|get_key:"article"|get_attr:"id" }}' ">Read More</button></p>
      <ul class="list-inline">
        <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><span class="glyphicon glyphicon-comment"></span>{{ article_info|get_key:"article"|get_attr:"comment_num" }} Comments</a></li>
        <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><span class="glyphicon glyphicon-thumbs-up"></span>{{ article_info|get_key:"article"|get_attr:"like_num" }} Likes</a></li>
      </ul>
    </article>
  </div>      
  <hr>
{% endfor %}

以上这篇django 自定义过滤器(filter)处理较为复杂的变量方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python列表生成式与列表生成器的使用

列表生成式:会将所有的结果全部计算出来,把结果存放到内存中,如果列表中数据比较多,就会占用过多的内存空间,可能会导致MemoryError内存错误或者导致程序在运行时出现卡顿的情况 列表...

python 多线程串行和并行的实例

如下所示: #coding=utf-8 import threading import time import cx_Oracle from pprint import pprint...

Python通过select实现异步IO的方法

本文实例讲述了Python通过select实现异步IO的方法。分享给大家供大家参考。具体如下: 在Python中使用select与poll比起在C中使用简单得多。select函数的参数是...

Python开启线程,在函数中开线程的实例

逻辑处理上分成了多个模块,为了提高效率,前一个模块处理完调用后一个模块操作时使用多线程 我这里遇到的情形是前面取数据后面存到mysql,发现单线程效率很低,改为取数据后开线程存到mysq...

用python处理图片之打开\显示\保存图像的方法

用python处理图片之打开\显示\保存图像的方法

一提到数字图像处理,可能大多数人就会想到matlab,但matlab也有自身的缺点: 1、不开源,价格贵 2、软件容量大。一般3G以上,高版本甚至达5G以上。 3、只能做研究,不易转化成...