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


Posted in Python onAugust 12, 2019

简述: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操作CouchDB的方法
Oct 08 Python
Python与shell的3种交互方式介绍
Apr 11 Python
在Python中使用SimpleParse模块进行解析的教程
Apr 11 Python
Python使用struct处理二进制的实例详解
Sep 11 Python
Python_LDA实现方法详解
Oct 25 Python
python Tkinter版学生管理系统
Feb 20 Python
python树的同构学习笔记
Sep 14 Python
Python大数据之网络爬虫的post请求、get请求区别实例分析
Nov 16 Python
利用Tensorflow的队列多线程读取数据方式
Feb 05 Python
如何基于python3和Vue实现AES数据加密
Mar 27 Python
解决python对齐错误的方法
Jul 16 Python
五种Python转义表示法
Nov 27 Python
django-filter和普通查询的例子
Aug 12 #Python
利用python实现汉字转拼音的2种方法
Aug 12 #Python
python面向对象 反射原理解析
Aug 12 #Python
Python中正反斜杠(‘/’和‘\’)的意义与用法
Aug 12 #Python
Django 查询数据库并返回页面的例子
Aug 12 #Python
python3 深浅copy对比详解
Aug 12 #Python
Django获取该数据的上一条和下一条方法
Aug 12 #Python
You might like
php file_get_contents函数轻松采集html数据
2010/04/22 PHP
yii框架中的Url生产问题小结
2012/01/16 PHP
php打开远程文件的方法和风险及解决方法
2013/11/12 PHP
destoon安全设置中需要设置可写权限的目录及文件
2014/06/21 PHP
PHP中类属性与类静态变量的访问方法示例
2016/07/13 PHP
老生常谈PHP面向对象之解释器模式
2017/05/17 PHP
Thinkphp5 如何隐藏入口文件index.php(URL重写)
2019/10/16 PHP
jquery常用技巧及常用方法列表集合
2011/04/06 Javascript
jquery用offset()方法获得元素的xy坐标
2014/09/06 Javascript
js+html5操作sqlite数据库的方法
2016/02/02 Javascript
AngularJS  $modal弹出框实例代码
2016/08/24 Javascript
JS中用childNodes获取子元素换行会产生一个子元素
2016/12/08 Javascript
ionic开发中点击input时键盘自动弹出
2016/12/23 Javascript
Angular.js中定时器循环的3种方法总结
2017/04/27 Javascript
Express之get,pos请求参数的获取
2017/05/02 Javascript
简单实现js进度条加载效果
2020/03/25 Javascript
JS验证输入的是否是数字及保留几位小数问题
2018/05/09 Javascript
Vue 后台管理类项目兼容IE9+的方法示例
2019/02/20 Javascript
原生js实现的移动端可拖动进度条插件功能详解
2019/08/15 Javascript
Vue使用vue-recoure + http-proxy-middleware + vuex配合promise实现基本的跨域请求封装
2019/10/21 Javascript
js实现验证码干扰(静态)
2021/02/22 Javascript
详解Python使用simplejson模块解析JSON的方法
2016/03/24 Python
python中list列表的高级函数
2016/05/17 Python
对python中的xlsxwriter库简单分析
2018/05/04 Python
Python使用Slider组件实现调整曲线参数功能示例
2019/09/06 Python
使用python+poco+夜神模拟器进行自动化测试实例
2020/04/23 Python
Python super()函数使用及多重继承
2020/05/06 Python
丝芙兰新加坡官网:Sephora新加坡
2018/12/04 全球购物
Linux中如何用命令创建目录
2016/12/02 面试题
校园公益广告语
2014/03/13 职场文书
幼儿教师师德师风自我剖析材料
2014/09/29 职场文书
公务员个人年终总结
2015/02/12 职场文书
高二语文教学反思
2016/02/16 职场文书
教师学期述职自我鉴定
2019/08/16 职场文书
浅谈Redis位图(Bitmap)及Redis二进制中的问题
2021/07/15 Redis
Python四款GUI图形界面库介绍
2022/06/05 Python