Django 自定义过滤器

1,编写自定义过滤器并注册

创建目录

Test/app5/templatetags

分别创建文件

Test/app5/templatetags/init.py

Test/app5/templatetags/myfilter.py

添加过滤器脚本

Test/app5/templatetags/myfilter.py

复制代码
from django import template
register = template.Library()
@register.filter
def show_title(value, n):
    if len(value) > n:
        return f'{value[:n]}...'
    else:
        return value

2,添加视图函数

Test/app5/views.py

复制代码
from django.shortcuts import render

# Create your views here.
import datetime

def filter(request):
    str1 = 'abcdefg'
    str2 = 'ABCDEFGHIJKLMNO'
    str3 = '123456789'

    time_str = datetime.datetime.now()
    return render(request, '5/filter.html', {'str1':str1, 'str2':str2, 'str3':str3, 'time_str':time_str})


def html_filter(request):
    html_addr = """
        <table border='2'>
            <tr>
                <td>
                这是表格A
                </td>
                <td>
                这是表格B
                </td>
            </tr>
        </table>
    """

    html_script = """
        <script language='JavaScript'>
            document.write('非法执行');
        </script>
    """

    return render(request, '5/html_filter.html', {"html_addr":html_addr, "html_script":html_script})


def diy_filter(request):
    dict1 = {'标题': '学习Django天天加班,熬到深夜,沉迷学习无法自拔!'}
    dict2 = {'标题': '学习java天天加班,熬到深夜,沉迷学习无法自拔!'}
    dict3 = {'标题': '学习C++天天加班,熬到深夜,沉迷学习无法自拔!'}
    lists = [dict1, dict2, dict3]
    return render(request, '5/diy_filter.html', {"lists":lists})

3,添加路由

Test/app5/urls.py

复制代码
from django.urls import path
from . import views


urlpatterns = [
    path('filter', views.filter, name='filter'),
    path('html_filter', views.html_filter, name='html_filter'),
    path('diy_filter', views.diy_filter, name='diy_filter'),
]

4,添加HTML代码

Test/templates/5/diy_filter.html

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

{% load myfilter %} <!-- 使用半角字符 -->
<table border="1" style="width: 300px">
    {% for list in lists %}
    <tr>
        <td>
            {{ list.标题|show_title:10 }} <!-- 假设 show_title 过滤器接收一个参数 -->
        </td>
    </tr>
    {% endfor %}
</table>

</body>
</html>

5,访问页面

http://127.0.0.1:8000/app5/diy_filter

相关推荐
兔子的洋葱圈10 小时前
【django】3 (django路由) 路由配置和反向解析
后端·python·django
零一先生【Z】11 小时前
一、简单的 Django 服务
后端·python·django
月小水长15 小时前
Django 使用 matplotlib 遇到 RuntimeError: main thread is not in main loop 解决办法
python·django·matplotlib·thread·anr
南城猿2 天前
Pycharm中Django框架使用{% load static %}模板,HTML报错
ide·pycharm·django
唐古乌梁海2 天前
【Django】教程-10-ajax请求Demo,结合使用
django
强化生物科研小助手3 天前
CAS:47623-98-3,DiSBAC2(3)一种慢反应的膜电位敏感探针
django·html·pygame
橘猫云计算机设计3 天前
基于springboot的考研成绩查询系统(源码+lw+部署文档+讲解),源码可白嫖!
java·spring boot·后端·python·考研·django·毕业设计
程序员一诺3 天前
【Django开发】前后端分离django美多商城项目第15篇:商品搜索,1. Haystack介绍和安装配置【附代码文档】
后端·python·django·框架
小狗很可爱3 天前
视图函数的应用
django
麦麦大数据4 天前
neo4j+django+deepseek知识图谱学习系统对接前后端分离前端vue
vue.js·django·知识图谱·neo4j·deepseek·在线学习系统