26.Django模板语言和分页

继承 extends

 子版只能继承一个父模板

1.父模板 master.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %} {% endblock %}</title>
    <link rel="stylesheet" href="/static/common.css">
    <style>
        .pg-header{
            height: 50px;
            background-color: red;
            color:blue
        }
        {% block css %} {% endblock %}
    </style>
</head>
<body>
    <div class="pg-header">小男孩管理</div>

    {% block content %} {% endblock %}

    <div class="pg-footer"></div>

    <script src="/static/jquery-1.12.4.js"></script>

    {% block js %} {% endblock %}
</body>
</html>

2.子版继承方法

{% extends 'master.html' %}     #引用母版

{% block title %}用户管理{% endblock %}

{% block content %}
    <h1>用户管理</h1>
    <ul>
        {% for i in u %}
        <li>{{ i }}</li>
        {% endfor %}
    </ul>
{% endblock %}

{% block css %}
    <style>
        body{
            background-color: black;
        }
    </style>
{% endblock %}

{% block js %}
    <script>

    </script>
{% endblock %}

导入定制的组件 include

 创建tag.html

在index.html中导入tag.html,可以导入很多个

{% include 'tag.html' %}

tag.html

form>
    <input type="text" name="user"/>
    <input type="submit" value="提交"/>
</form>

index.html

{# 指定继承的模板 #}
{% extends 'master.html' %}
 
{# 指定替换的位置 #}
{% block title %}
    tp1
{% endblock %}
 
{# 指定替换的位置 #}
{% block content %}
    <p>tp1</p>
 
    {# 导入单独组件 #}
    {% include 'tag.html' %}
{% endblock %}

simple_tag and filter

 1.django默认自带方法

{{ item.event_start|date:"Y-m-d H:i:s"}}    #日期格式进行转换
{{ bio|truncatewords:"30" }}                  #取字符串前30位
{{ my_list|first|upper }}                     #第一个字符大写             
{{ name|lower }}                                #所有字符小写

 2.simple_tag

第一步: 在app01下面创建templatetags(必须是这个名字)文件夹

第二步:在templatetags下面创建test1.py文件

第三步:模板中   首先在开头要先导入  {%  load test1 %} 

第四步: 模板中使用方法   {%  函数名 参数1  参数2  %}

test1.py

from django import template
from django.utils.safestring import mark_safe
# 必须是register对象
register = template.Library()
@register.simple_tag

def func(a1,a2):
    return a1 + a2

index.py

{% load test1 %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {{ name }}
    {{ name|lower }}

    {% func 2 5 %}
</body>
</html>

3.filter

test1.py

from django import template
from django.utils.safestring import mark_safe
# 必须是register对象
register = template.Library()
@register.simple_tag

def func(a1,a2):
    return a1 + a2

@register.filter()
def func1(b1,b2):
    return b1 + b2

index.py

{% load test1 %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {{ name }}
    {{ name|lower }}

{#    simpletag#}
    {% func 2 5 %}

{#    filter#}
    {{ 'zhang'|func1:'derek' }}


</body>
</html>

 总结:

simple:

优点:参数任意

缺点:不能作为if条件

filter

优点:最多两个参数

缺点:可以作为if条件

 分页

 1.简单分页

 涉及xss攻击,需要用到mark_safe方法,使用此方法字符串传输到后端后,已html形式显示,而非字符串

HTML文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .pagination .page{
            display: inline-block;
            padding: 5px;
            background-color: cyan;
            margin: 5px;
        }
        .pagination .page.active{
            background-color: brown;
            color: white;
        }
    </style>
</head>
<body>
    <ul>
        {% for item in li %}
            <li>{{ item }}</li>
        {% endfor %}
    </ul>
    <div class="pagination">
        {{ page_str }}
    </div>
</body>
</html>

views.py

from django.shortcuts import render,HttpResponse
from django.core.handlers.wsgi import WSGIRequest
from django.utils.safestring import mark_safe

LIST = []
for i in range(109):
    LIST.append(i)

from django.utils.safestring import  mark_safe
def user_list(request):
    current_page = request.GET.get('p',1)
    current_page = int(current_page)

    start = (current_page-1)*10
    end = current_page*10
    data = LIST[start:end]

    all_count = len(LIST)
    count,y = divmod(all_count,10)
    if y :
        count +=1

    page_list = []
    for i in range(1,count+1):
        if i == current_page:
            temp = '<a class="page active" href="/user_list/?p=%s">%s</a>'%(i,i)
        else:
            temp = '<a class="page" href="/user_list/?p=%s">%s</a>'%(i,i)

        page_list.append(temp)

    page_str = mark_safe(''.join(page_list))

    return render(request,'user_list.html',{'li':data,'page_str':page_str})

浏览器访问地址

浏览器访问地址:http://127.0.0.1:8000/user_list/?p=3

2.增加功能

分页数进行定制,添加上一页、下一页,增加跳转功能,实现分页的完整功能

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .pagination .page{
            display: inline-block;
            padding: 5px;
            background-color: cyan;
            margin: 5px;
        }
        .pagination .page.active{
            background-color: brown;
            color: white;
        }
    </style>
</head>
<body>
    <ul>
        {% for item in li %}
            <li>{{ item }}</li>
        {% endfor %}
    </ul>
    <div class="pagination">
        {{ page_str }}
    </div>
</body>
</html>

user_list.html

views.py

LIST = []
for i in range(199):
    LIST.append(i)

from django.utils.safestring import  mark_safe
def user_list(request):
    current_page = request.GET.get('p',1)
    current_page = int(current_page)

    start = (current_page-1)*10
    end = current_page*10
    data = LIST[start:end]

    all_count = len(LIST)
    total_count,y = divmod(all_count,10)
    if y :
        total_count +=1
    pager_num = 11                          #页码数

    page_list = []
    if total_count < pager_num :            #总页面小于页码数
        start_index = 1
        end_index = total_count + 1
    else:
        if current_page <= pager_num/2:     #开头
            start_index = 1
            end_index = pager_num + 1
        elif current_page + (pager_num-1)/2 >= total_count:         #中间
            start_index = total_count - (pager_num-1)
            end_index = total_count + 1
        else:                               #结尾
            start_index = current_page - (pager_num-1)/2
            end_index = current_page + (pager_num-1)/2 + 1

    # 上下页码
    if current_page == 1:
        prev = '<a class="page" href="javascript:void(0)">上一页</a>'  # 什么都不干
    else:
        prev =  '<a class="page" href="/user_list/?p=%s">上一页</a>'%(current_page-1)
    page_list.append(prev)
    for i in range(int(start_index),int(end_index)):
        if i == current_page:
            temp = '<a class="page active" href="/user_list/?p=%s">%s</a>'%(i,i)
        else:
            temp = '<a class="page" href="/user_list/?p=%s">%s</a>'%(i,i)

        page_list.append(temp)
    if current_page == total_count:
        nex = '<a class="page" href="javascript:void(0)">下一页</a>'  # 什么都不干
    else:
        nex = '<a class="page" href="/user_list/?p=%s">下一页</a>'%(current_page+1)
    page_list.append(nex)

    # 跳转 可以写到前端
    jump = '''
    <input type="text" /><a onclick="jumpTo(this,'/user_list/?p=');">GO</a>
    <script>
        function jumpTo(ths,base) {
            var val = ths.previousSibling.value;
            location.href = base + val;
        }
    </script>
    '''
    page_list.append(jump)

    page_str = mark_safe(''.join(page_list))

    return render(request,'user_list.html',{'li':data,'page_str':page_str})

3.优化完善

页码代码跟业务代码分开,创建class类,然后views导入进去

app01下面创建 utils文件夹,里面创建pagination.py

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .pagination .page{
            display: inline-block;
            padding: 5px;
            background-color: cyan;
            margin: 5px;
        }
        .pagination .page.active{
            background-color: brown;
            color: white;
        }
    </style>
</head>
<body>
    <ul>
        {% for item in li %}
            <li>{{ item }}</li>
        {% endfor %}
    </ul>
    <div class="pagination">
        {{ page_str }}
    </div>
</body>
</html>

user_list.html

views.py

LIST = []
for i in range(199):
    LIST.append(i)

class Page:
    def __init__(self, current_page, data_count, per_page_count=10, pager_num=7):
        self.current_page = current_page
        self.data_count = data_count
        self.per_page_count = per_page_count
        self.pager_num = pager_num

    @property
    def start(self):
        return (self.current_page - 1) * self.per_page_count

    @property
    def end(self):
        return self.current_page * self.per_page_count

    @property
    def total_count(self):
        v, y = divmod(self.data_count, self.per_page_count)
        if y:
            v += 1
        return v

    def page_str(self, base_url):
        page_list = []

        if self.total_count < self.pager_num:
            start_index = 1
            end_index = self.total_count + 1
        else:
            if self.current_page <= (self.pager_num + 1) / 2:
                start_index = 1
                end_index = self.pager_num + 1
            else:
                start_index = self.current_page - (self.pager_num - 1) / 2
                end_index = self.current_page + (self.pager_num + 1) / 2
                if (self.current_page + (self.pager_num - 1) / 2) > self.total_count:
                    end_index = self.total_count + 1
                    start_index = self.total_count - self.pager_num + 1

        if self.current_page == 1:
            prev = '<a class="page" href="javascript:void(0);">上一页</a>'
        else:
            prev = '<a class="page" href="%s?p=%s">上一页</a>' % (base_url, self.current_page - 1,)
        page_list.append(prev)

        for i in range(int(start_index), int(end_index)):
            if i == self.current_page:
                temp = '<a class="page active" href="%s?p=%s">%s</a>' % (base_url, i, i)
            else:
                temp = '<a class="page" href="%s?p=%s">%s</a>' % (base_url, i, i)
            page_list.append(temp)

        if self.current_page == self.total_count:
            nex = '<a class="page" href="javascript:void(0);">下一页</a>'
        else:
            nex = '<a class="page" href="%s?p=%s">下一页</a>' % (base_url, self.current_page + 1,)
        page_list.append(nex)

        jump = """
        <input type='text'  /><a onclick='jumpTo(this, "%s?p=");'>GO</a>
        <script>
            function jumpTo(ths,base){
                var val = ths.previousSibling.value;
                location.href = base + val;
            }
        </script>
        """ % (base_url,)

        page_list.append(jump)

        page_str = mark_safe("".join(page_list))

        return page_str

from django.utils.safestring import  mark_safe
def user_list(request):
    current_page = request.GET.get('p', 1)
    current_page = int(current_page)
    page_obj = Page(current_page,len(LIST))

    data = LIST[page_obj.start:page_obj.end]

    page_str = page_obj.page_str("/user_list/")

    return render(request, 'user_list.html', {'li': data,'page_str': page_str})

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏Python爬虫与算法进阶

快速写一个爬虫

今天下班前,老板让我帮忙爬一个数据,简单看了下,需要登录,看起来应该不难。回到家,注册一个账号,复制url,然后用postman转代码,简单暴力,直接撸。

20010
来自专栏about云

日志分析实战之清洗日志小实例4:统计网站相关信息

问题导读 1.如何统计网站总的点击量? 2.如何实现统计不能访问网页的个数? 3.文章中如何定义和使用Scala函数的? 导入之后,我们创建Acces...

29430
来自专栏Golang语言社区

golang-xorm库快速学习

xorm xorm是一个Go语言ORM库. 通过它可以使数据库操作非常简便. 全部文档点我 用法入门: 前提:定义本文中用到的struct和基本代码如下 // ...

96580
来自专栏闻道于事

Hibternate框架笔记

Hibernate框架 配置 配置文件: 1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibe...

29260
来自专栏ml

------------数据库的加锁操作(上)

       从事一个项目,需要考虑数据的安全性,之前对于数据库这部分的数据操作学习的比较零散,由于手头的项目,于是系统的 学习了下数据库操作加锁的知识: --...

576100
来自专栏大内老A

在Entity Framework中使用存储过程(四):如何为Delete存储过程参数赋上Current值?

继续讨论EF中使用存储过程的问题,这回着重讨论的是为存储过程的参数进行赋值的问题。说得更加具体一点,是如何为实体映射的Delete存储过程参数进行赋值的问题。关...

23590
来自专栏Java学习网

Java开发之使用Java 8 Streams 对数据库进行 CRUD 操作

Speedment 是一个开放源代码的工具集,它可以被用来生成 Java 实体,并且能将我们同数据库的通信过程管理起来。你可以利用一个图形工具连接到数据库并生成...

13230
来自专栏数据处理

Delete Duplicate Emails

19440
来自专栏程序员的SOD蜜

PDF.NET(PWMIS数据开发框架)之SQL-MAP目标和规范

SQL-MAP的目标: 集中管理SQL语句,所有SQL语句放在专门的配置文件中进行管理; 通过替换SQL配置文件,达到平滑切换数据库到另外一个数据库,比如从O...

27980
来自专栏iOS开发随笔

iOS Swift 读取本地json文件

26650

扫码关注云+社区

领取腾讯云代金券