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中的列表推导浅析
Apr 26 Python
python进阶教程之模块(module)介绍
Aug 30 Python
讲解Python中if语句的嵌套用法
May 14 Python
Python的re模块正则表达式操作
May 25 Python
python爬虫中get和post方法介绍以及cookie作用
Feb 08 Python
python3爬取数据至mysql的方法
Jun 26 Python
python之cv2与图像的载入、显示和保存实例
Dec 05 Python
python爬虫之自制英汉字典
Jun 24 Python
python爬虫实现中英翻译词典
Jun 25 Python
浅析python表达式4+0.5值的数据类型
Feb 26 Python
keras在构建LSTM模型时对变长序列的处理操作
Jun 29 Python
如何使用python包中的sched事件调度器
Apr 30 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
php2html php生成静态页函数
2008/12/08 PHP
PHP检查URL包含特定字符串实例方法
2019/02/11 PHP
通用JS事件写法实现代码
2009/01/07 Javascript
DOM基础教程之使用DOM控制表格
2015/01/20 Javascript
JavaScript生成二维码图片小结
2015/12/27 Javascript
jQuery插件HighCharts实现2D柱状图、折线图的组合多轴图效果示例【附demo源码下载】
2017/03/09 Javascript
Angular.js 4.x中表单Template-Driven Forms详解
2017/04/25 Javascript
利用Jasmine对Angular进行单元测试的方法详解
2017/06/12 Javascript
three.js中文文档学习之如何本地运行详解
2017/11/20 Javascript
JavaScript实现简单轮播图效果
2018/12/01 Javascript
JS获取今天是本月第几周、本月共几周、本月有多少天、是今年的第几周、是今年的第几天的示例代码
2018/12/05 Javascript
详解webpack引入第三方库的方式以及注意事项
2019/01/15 Javascript
vue el-upload上传文件的示例代码
2020/12/21 Vue.js
[43:47]DOTA2上海特级锦标赛主赛事日 - 4 败者组第四轮#2 MVP.Phx VS Fnatic第一局
2016/03/05 DOTA
Python聚类算法之凝聚层次聚类实例分析
2015/11/20 Python
Python使用wxPython实现计算器
2018/01/30 Python
python单例模式实例解析
2018/08/28 Python
numpy.meshgrid()理解(小结)
2019/08/01 Python
django 框架实现的用户注册、登录、退出功能示例
2019/11/28 Python
numpy.linalg.eig() 计算矩阵特征向量方式
2019/11/29 Python
解决python web项目意外关闭,但占用端口的问题
2019/12/17 Python
python dataframe NaN处理方式
2019/12/26 Python
如何使用Python破解ZIP或RAR压缩文件密码
2020/01/09 Python
python 实现超级玛丽游戏
2020/11/25 Python
如何使用python-opencv批量生成带噪点噪线的数字验证码
2020/12/21 Python
举例讲解Python装饰器
2020/12/24 Python
php优化查询foreach代码实例讲解
2021/03/24 PHP
企业管理部经理岗位职责
2013/12/24 职场文书
给领导的致歉信范文
2014/01/13 职场文书
总经理的岗位职责
2014/02/23 职场文书
2014年乡镇植树节活动方案
2014/02/28 职场文书
财务审计整改报告
2014/11/06 职场文书
2014流动人口计划生育工作总结
2014/12/20 职场文书
给领导的感谢信范文
2015/01/23 职场文书
关于销售人员的年终工作总结要点
2019/08/15 职场文书
Java 超详细讲解数据结构中的堆的应用
2022/04/02 Java/Android