django学习模板篇

本篇博客是Django学习中的模板篇

1.最简单的返回一个页面

settings.py中的设置

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,"templates")],
        'APP_DIRS':True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
#使用绝对路径
#'DIRS':[r"C:\templates"]

urls.py

path("index111/",index111),

views.py

from django.shortcuts import render
def index111(request):
    return render(request,"denglu.html")
2.如果settings.py中APP—DIRS=True,则可以从app中的templates中寻找文件,并且注册此app,app中的templates文件夹的名字固定,否则找不到

views.py

def index222(request):
    return render(request,"index222.html")

urls.py

path("index222/",index222),

在这里插入图片描述
在这里插入图片描述

3.测试从数据库中拿到数据

views.py

from user.models import User
def test(request):
    username=User.objects.all()
    usrss=username[0]
    print(usrss)
    return render(request,"test.html",context={"username":usrss})

urls.py

path("test/",test),

models.py

from django.db import models
class User(models.Model):
    name = models.CharField(max_length=50, null=False, verbose_name="姓名")
4.从views中设定一个类,从类的字典中读取数据,模型或者类使用key.value来获取

viesw.py

class Person(object):
    def __init__(self,username11):
        self.username11=username11
def test3(request):
    p=Person("王总")
    context={
        "username11":p
    }
    return render(request,"test.html",context)

urls.py

path("test3/",test3),

test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>2020年4月3号的一个测试文件</title>
</head>
<body>
这个是一个测试文件,测试数据中拿到数据
{{ username11.username11}}
</body>
</html>

在这里插入图片描述

5.如果是一个字典

views.py

def test3(request):
    # p=Person("王总")
    context={
        "persons":[
            '鲁班一号',
            '程咬金',
            '后羿',
        ]
    }
    return render(request,"test.html",context)

test.html

{{ persons.0}}

在这里插入图片描述

6.总结笔记

1.在模板中如果要使用变量,则使用{{变量}}访问
2.在模板中如果要访问对象的属性,则使用{{对象.属性名}}来进行访问

class Person(object):
    def __init__(self,username11):
        self.username11=username11
def test3(request):
    p=Person("王总")
    context={
        "username11":p
    }
    return render(request,"test.html",context)

访问

{{ persons.username}}

3.如果要访问字典key对应的value,则使用{{字典.key}}的方式进行访问,不能通过有[]的形式进行访问。

    context = {
        "person":{
            "username":"zhihu",
        }
    }
{{ person.username}}

4.因为在访问字典key也是使用·点·的方式,因此不能在字典中定义字典本身就有的属性名当做key,否则字典中的属性就变成字典中的key

    context = {
        "person":{
            "username":"zhihu",
            "keys":"asd"
        }
    }

以上因为将keys作为Python字典的key,如果使用person.keys返回的是key对应的值
5.如果想要访问字典或者元组,那么通过·点·的方式进行访问 ,不能通过【】进行访问,如:

{{ persons.0}}
7.if标签的使用

可以使用{% elif %}和{% else %}

{%  if "张三" in persons %}
<p>张三</p>
{% else %}
<p>李四</p>
{% endif %}

views.py

def test3(request):
    context={
        "persons":[
            '鲁班一号',
            '程咬金',
            '后羿',
        ]
    }
    return render(request,"test.html",context)

在这里插入图片描述

8.for标签
<ul>
{% for person in  persons%}
{{ person }}
{% endfor %}
</ul>
<ul>
{% for person in  persons%}
<li>
{{ person }}
</li>
{% endfor %}
</ul>

在这里插入图片描述
反向遍历

<ul>
{% for person in  persons reversed %}
<li>
{{ person }}
</li>
{% endfor %}
</ul>
9.for循环读取key

keys可以改为value,items

<ul>
    {% for foo in book.keys %}        
        <li>{{ foo }}</li>
    {% endfor %}
 </ul>

views.py

def test3(request):
    # p=Person("王总")
    context={
        "persons":[
            '鲁班一号',
            '程咬金',
            '后羿',
        ],
        "book":{
            "name":"shuji",
            "prices":"21",
        }
    }
    return render(request,"test.html",context)

改为items时

<ul>
    {% for key,value in book.items %}        
        <li>{{ key }}/{{ value }}</li>
    {% endfor %}
 </ul>

10.

views.py

class Person(object):
    def __init__(self,username11):
        self.username11=username11
def test3(request):
    # p=Person("王总")
    context={
        "persons":[
            '鲁班一号',
            '程咬金',
            '后羿',
        ],
        "book":{
            "name":"shuji",
            "prices":"21",
        },
        "movies":[
            {
               "name":"西游记",
               "author":"施耐庵",
                "price":100,
            },
            {
                "name":"水浒传",
                "author":"罗贯中",
                "price":900,
            },
            {
                "name": "西you",
                "author": "施耐",
                "price": 10,
            },
            {
                "name": "西",
                "author": "施",
                "price": 1,
            },
        ],
    }

    return render(request,"test.html",context)

html

<table>
    <thead>
    <tr>
        <td>书籍名</td>
        <td>作者</td>
        <td>价格</td>
    </tr>
    </thead>
    <tbody>
    {% for movie in movies %}
        <tr>
        <td>{{ movie.name }}</td>
        <td>{{ movie.author }}</td>
        <td>{{ movie.price }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>

在这里插入图片描述
加个 {{ forloop.counter }},效果为在前面加了序号,forloop.counter0则序号是从0开始,recounter是反向的,recounter0则最后一个是0,first为是否是第一次遍历,last为是否是最后一次遍历
html

<table>
    <thead>
    <tr>
        <td>书籍名</td>
        <td>作者</td>
        <td>价格</td>
    </tr>
    </thead>
    <tbody>
    {% for movie in movies %}
        <tr>
         <td>{{ forloop.counter }}</td>,
        <td>{{ movie.name }}</td>
        <td>{{ movie.author }}</td>
        <td>{{ movie.price }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>

在这里插入图片描述
实现表格中的不同颜色

<table>
    <thead>
    <tr>
        <td>书籍名</td>
        <td>作者</td>
        <td>价格</td>
    </tr>
    </thead>
    <tbody>
    {% for movie in movies %}
        {% if forloop.first %}
        <tr style="background: red;">
            {% elif forloop.last %}
            <tr style="background: black;">
            {% else %}
            <tr style="background: pink;">
        {% endif %}
        <td>{{ forloop.first }}</td>
        <td>{{ movie.name }}</td>
        <td>{{ movie.author }}</td>
        <td>{{ movie.price }}</td>
        </tr>
    {% endfor %}

    </tbody>
</table>

在这里插入图片描述
views.py

def test3(request):
    # p=Person("王总")
    context={
        "persons":[
            '鲁班一号',
            '程咬金',
            '后羿',
        ],
        "book":{
            "name":"shuji",
            "prices":"21",
        },
        "movies":[
            {
               "name":"西游记",
               "author":"施耐庵",
                "price":100,
            },
            {
                "name":"水浒传",
                "author":"罗贯中",
                "price":900,
            },
            {
                "name": "西you",
                "author": "施耐",
                "price": 10,
            },
            {
                "name": "西",
                "author": "施",
                "price": 1,
            },
        ],
        "comments":[
            "文章真好",
            "不错",
            "还行"
        ],
    }

    return render(request,"test.html",context)
<ul>
    {% for foo in comments %}
        <li>{{ foo }}</li>
        {% empty %}
        <li>没有任何评论</li>
    {% endfor %}
</ul>

在这里插入图片描述
若为空,则显示:没有任何评论

11.with标签

with相当于取了一个别名

{% with zs=persons.0  %}
{{ zs }}{{ zs }}
{% endwith %}

使用as的话,应该反过来写

{% with persons.0 as zs  %}
{{ zs }}{{ zs }}
{% endwith %}
12.url标签
<a href="{% static 'index.html'  %}">首页</a>
<a href="{% url 'denglu' %}">登录</a>
<a href="{% url 'tushu' tushu_id='1' %}">图书的页面</a>

views.py

def tushu(request,tushu_id):
    text = "您的图书的id为:%s" % tushu_id
    return HttpResponse(text)
def denglu(request):
    return render(request,"denglu.html")
13.自动转义

views.py

def tiaozhuan(request):
    context={
        "info":"<a href='http://www.baidu.com'>百度</a>"
    }
    return render(request,"test.html",context=context)
{% autoescape off %}
    {{ info }}
{% endautoescape %}

在这里插入图片描述

14.verbatim
{% verbatim %}
{{ hello }}
{% endverbatim %}

显示时不会自动转义,将显示原字符{{hello}}

15.返回函数值

views.py

def greet():
    return "你好"
def tiaozhuan(request):
    context={
        "greet":greet
    }
    return render(request,"test.html",context=context)
{{ greet }}
16.DTL过滤器add:添加

单独在html文件中这样写

#返回结果为3
{{"1"|add "2"}}
#返回结果是个字符串
{{ "1" |add:"2sdasdsa" }}

传递参数时:

#views.py
def tiaozhuan(request):
    context={
        "value1":"value1",
        "value2":"value2",
    }
    return render(request,"test.html",context=context)
#或者:
def tiaozhuan(request):
    context={
        "value1":["1",2,3],
        "value2":["4","5",6]
    }
    return render(request,"test.html",context=context)
{{ value1 |add:value2 }}
#第一种情况显示 value1 value2
#第二种情况显示  ['1', 2, 3, '4', '5', 6]
17.DTL过滤器cut:剪掉
{{value|cut:"被剪掉的字符串"}}
##例如
{{"hello word"|cut:" "}}
#显示 helloword

显示日期

def tiaozhuan(request):
    context={
        "birthday":datetime.now()
    }
    return render(request,"test.html",context=context)
{{ birthday|date:"Y-m-d H:i:s"  }}
18.DTL过滤器defalut:若判断为false,则使用后面的值代替

default:

def tiaozhuan(request):
    context={
        "a":0
    }
    return render(request,"test.html",context=context)
{{ a|default:"传入的参数错误" }}
#显示为传入的参数错误

default_if_none:

def tiaozhuan(request):
    context={
        "a":None
    }
    return render(request,"test.html",context=context)
#显示为nothing
{{ a|default_if_none:"nothing" }}
19.DTL过滤器last:显示最后一个值。first:显示第一个值
def tiaozhuan(request):
    context={
        "a":"asdfg"
    }
    return render(request,"test.html",context=context)
#以下代码显示为g
{{ a|last }}
#以下代码显示a
{{a|first}}
20.DTL过滤器floatformat

无参数时,显示一位小数,若四舍五入后小数点后面全为0,则默认省去小数点后面的值(用途:对评分等进行格式化)

def tiaozhuan(request):
    context={
        "a":"90.8927655
    }
    return render(request,"test.html",context=context)
#以下代码显示为90.9
{{ a|floatformat }}
#以下代码显示3位小数
{{ a|floatformat:3 }}
21.DTL过滤器join

join,对给定的参数进行分割

def tiaozhuan(request):
    context={
        "a":"jjjj"
    }
    return render(request,"test.html",context=context)
#以下代码显示为j/j/j/j
{{ a|join:"/" }}
22.DTL过滤器length

lower,将全部转换为小写,upper全部转换为大写
length:统计字典,数组,字符串的长度
random从字典,数组,字符中随机选择一个值(点名系统)
safe:关闭自动转义,可以用来执行写好的js代码

def tiaozhuan(request):
    context={
        "a":"JJJJ",
        "b":["a","2",""3],
        "c":{
        	"a":"s",
        	"d":"f"
        },
        "d":"<script>alert('这是一个警示框')</script>"
    }
    return render(request,"test.html",context=context)
#以下代码显示为4,3,2,jjjj,弹出警示框
{{ a|length }}
{{ b|length }}
{{ c|length }}
{{a|lower}}
{{b|random}}
{{d|safe}}
23.DTL过滤器slice,切片过滤器

striptags,清除所有html标签
truncatechars,超过制定数字,则进行切割,并显示…(用于做摘要),算上…一共的字符
truncatechars_html:切割html中的字符

def tiaozhuan(request):
    context={
        "a":[1,2,3,4,5,6,7],
        "b":"<script>alert('这是一个警示框')</script>",
        "c":"asdfghjkl""d":"<p>北京欢迎你</p>",
    }
    return render(request,"test.html",context=context)
#以下代码显示为[1] [2, 3, 4, 5, 6, 7] [2, 3, 4] [2, 4, 6],alert('这是一个警示框'),
{{a|slice:"1"}}
{{a|slice:"1:"}}
{{a|slice:"1:4"}}
{{a|slice:"1:2"}}
{{b|striptags}}
#as...
{{a|truncatechars:5}}
#<p>北...</p>
{{ d|truncatechars_html:4}}

查看Django中有哪些默认的标签

from django.template import defaultfilters,defaulttags
24.自定义过滤器

在app下新建Python package包,名字叫templatetags,在此文件夹下新建my_filter.py,并注册此app

#indexs.html
{% load my_filter %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{{ value |greet:"word"}}
</body>
</html>
#my_fliter.py
#过滤器最多有两个参数
#过滤器的第一个参数永远为被过滤的参数,也就是|左边的值
from django import template
register=template.Library()
def greet(value,word):
    return value+word
register.filter("greet",greet)
#或者可以写成这样,效果是一样的
from django import template
register=template.Library()
@register.filter
def greet(value,word):
    return value+word
register.filter("greet",greet)
#当在@register.filter传入参数时,如:@register.filter("my_greet"),则在html文件中也应该使用这个名字
#views.py
def index(request):
    context ={
        "value":"张三",
    }
    return render(request,"indexs.html",context=context)
25.自定义过滤器实战:时间过滤器
#views.py
from django.shortcuts import render
from datetime import datetime
def index(request):
    context ={
        "value":"张三",
        "mytime":datetime(year=2020,month=3,day=8,hour=13,minute=34)
    }
    return render(request,"indexs.html",context=context)
#my_filter.py
@register.filter
def time_since(value):
    if not isinstance(value,datetime):
        return value
    now= datetime.now()
    #timedelay.total_seconds
    timestamp=(now - value).total_seconds()
    if timestamp<60:
        return "刚刚"
    elif timestamp>=60 and timestamp <60*60:
        minutes=int(timestamp/60)
        return "%s分钟前" %minutes
    elif timestamp>=60*60 and timestamp<24*60*60:
        hour=int(timestamp/60/60)
        return "%s小时前" %hour
    elif timestamp>=60*60*24 and timestamp<24*60*60*30:
        days=int(timestamp/60/60/24)
        return "%s天前" %days
    else:
        return value.strftime("%Y/%m/%d %H:%M")
{{ mytime|time_since }}
26.模板中的include详解
#views.py
def indexsss(request):
    context={
        "username":"用户名"
    }
    return render(request,"indexsss.html",context=context)
def company(request):
    return render(request,"company.html")
def xiaoyuan(request):
    return render(request,"xiaoyuan.html")
#indexsss.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% include "header.html" with username="用户名2"%}
<div class="content">
    这是中间的部分{{ username }}
</div>
{% include "footer.html"  %}
</body>
</html>
#header.html
<header>
    <ul>
        <li><a href="/">首页</a></li>
        <li><a href="{% url "company" %}">公司</a></li>
        <li><a href="{% url "xiaoyuan" %}">校园</a></li>
        <li>{{ username }}</li>
    </ul>
</header>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>这是公司的首页</title>
</head>
<body>
{% include "header.html" %}
这是公司的页面
{% include "footer.html" %}
</body>
</html>
27.继承父模板
#必须放在第一行
{% extends "base.html" %}

在base.html中开个口子

#base.html
    {% block content %}
    想要继承这一段,需要在index.html中添加相关内容
    {% endblock %}

同时在index.html中填充口子

#index.html
    {% block content %}
    这是首页啊
    {{ block .super}}
    {% endblock %}
18.加载静态文件
#开头加上这个标签
{% load staticfiles %}
src="{% static 'js/echarts.min.js' %}"

在settings.py中设置如下

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),  # 用于存放静态文件
]

在settiings.py中若设置为如下,则在html文件中可以不用加载{% load staticfiles %},把static设置为一个内置的标签,如if

#settings.py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,"templates")],
        'APP_DIRS':True,#如果为True,则也可以到app中寻找htnl文件
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
            'builtins':['django.templatetags.static'],
        },
    },
]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值