django基础 -- 4. 模板语言 过滤器 模板继承 FBV 和CBV 装饰器 组件

时间:2023-02-26 10:26:06

一.语法 

  两种特殊符号(语法):

     {{  }}和 {% %}

  变量相关的用{{}},逻辑相关的用{%%}。

二.变量

  1. 可直接用  {{ 变量名 }}

   (可调用字符串, 数字 ,列表,字典,对象等)

由 view.py 传到  .html  

1.在 view.py 中
def base(request): ls1 = ['第一页','第二页','第三页']    # return render(request,'tags.html',{'ls1':ls1}) # 直传用到的变量. 可提高效率
   return render(request,'tags.html',locals())       #传所有的变量
2.在 .html  文件中
<p>{{ ls1 }}</p>   #所有传的内容都是以字符串的形式
 

  2.深度查询据点符( . )

  (数字索引查询, 字典查询,属性和方法查询)

在view.py 文件中
def index(request):
import datetime
s = "hello"
l = [111, 222, 333] # 列表
dic = {"name": "yuan", "age": 18} # 字典
date = datetime.date(1993, 5, 2) # 日期对象 class Person(object):
def __init__(self, name):
self.name = name
def dream(self):
return 'dreamer'
person_yuan = Person("chao") # 自定义类对象
person_egon = Person("yantao")
person_alex = Person("jinxin") person_list = [person_yuan, person_egon, person_alex] return render(request, "index.html", {"l": l, "dic": dic, "date": date, "person_list": person_list})
# return render(request,'index.html',locals())
#locals()获取函数内容所有的变量,然后通过render方法给了index.html文件进行模板渲染,
    如果你图省事,你可以用它,但是很多多余的变量也被传进去了,效率低
在 .html 文件中
<h4>{{s}}</h4>
<h4>列表:{{ l.0 }}</h4>
<h4>列表:{{ l.2 }}</h4>
<h4>字典:{{ dic.name }}</h4>
<h4>日期:{{ date.year }}</h4> <!--取列表的第1个对象的name属性的值-->
<h4>类对象列表:{{ person_list.0.name }}</h4>
<!--取列表的第1个对象的dream方法的返回值,如果没有返回值,拿到的是none-->
<h4>类对象列表:{{ person_list.0.dream }}</h4>
注意:
调用对象里面的方法的时候,不需要写括号来执行,并且只能执行不需要传参数的方法,
    如果你的这个方法需要传参数,那么模板语言不支持,不能帮你渲染

三.过滤器

  1.语法

 {{ value|方法:参数 }}

  2.常用方法

  ① lower :将文本全部变成小写  

{{ name|lower }}

  ②join :可以连接一个列表中的元素

{{ list|join:'+' }}

  ③default: 如果一个变量是false或者为空,使用给定的默认值。

           否则,使用变量的值。 

{{ value|default:"nothing"}}

  ④length: 返回值的长度,作用于字符串和列表

{{ value|length }}

  ⑤filesizeformat : 将值 格式化为一个"人类可读的"文件尺寸

    (如果 value 是 123456789,输出将会是 117.7 MB。)

{{ value|filesizeformat }}

  ⑥slice:切片

# value="hello world"

{{value|slice:"2:-1"}}

  ⑦date  格式化

#value=datetime.datetime.now()
{{ value|date:"Y-m-d H:i:s"}}

  ⑧safe : 可识别 标签 等

 #value = "<a href='#'>点我</a>" 
{{ value|safe}}

  ⑨truncatechars:如果 字符串字符 多于指定的 字符 数量,那么会被截断。

            截断的字符串将以可翻译的省略号序列(“...”)结尾。

{{ value|truncatechars:9}} #注意:最后那三个省略号也是9个字符里面的,也就是这个9截断出来的是6个字符+3个省略号,
     参数:截断的字符数

  ⑩truncatewords:在一定数量的字后截断字符串,是截多少个单词。

例如:‘hello girl hi baby yue ma’,
{{ value|truncatewords:3}}  

#上面例子得到的结果是 'hello girl h1...'

  ⑪cut: 移除 参数指定的字符串 

{{ value|cut:' ' }}

四.标签

  1. for 标签

  ①

{% for person in person_list %}
<p>{{ person.name }}</p> <!--凡是变量都要用两个大括号括起来-->
{% endfor %}

  ②

{% for obj in list reversed %}  #反向完成循环。

  ③ 遍历字典

{% for key,val in dic.items %}
<p>{{ key }}:{{ val }}</p>
{% endfor %}

  ④循环序号 (必须在循环内部使用)

forloop.counter            当前循环的索引值(从1开始),forloop是循环器,通过点来使用功能
forloop.counter0 当前循环的索引值(从0开始)
forloop.revcounter 当前循环的倒序索引值(从1开始)
forloop.revcounter0 当前循环的倒序索引值(从0开始)
forloop.first 当前循环是不是第一次循环(布尔值)
forloop.last 当前循环是不是最后一次循环(布尔值)
forloop.parentloop.counter 本层循环的外层循环的对象,再通过上面的几个属性来显示外层循环的计数等

django基础 -- 4.   模板语言  过滤器  模板继承  FBV 和CBV  装饰器   组件

  ⑤ for.....empty

      for 标签带有一个可选的{% empty %} 从句,

      以便在给出的组是空的或者没有被找到时,可以有所操作。

{% for person in person_list %}
<p>{{ person.name }}</p> {% empty %}
<p>sorry,no person here</p>
{% endfor %}

  2. if 标签   

if语句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判断,注意条件两边都有空格。
{% if num > 100 or num < 0 %}
<p>无效</p> <!--不满足条件,不会生成这个标签-->
{% elif num > 80 and num < 100 %}
<p>优秀</p>
{% else %} <!--也是在if标签结构里面的-->
<p>凑活吧</p>
{% endif %}

  3.with 标签

使用一个简单地名字缓存一个复杂的变量,多用于给一个复杂的变量起别名,
  当你需要使用一个“昂贵的”方法(比如访问数据库)很多次的时候是非常有用的
{% with total=business.employees.count %}  #等号 两边没有空格
{{ total }} <!--只能在with语句体内用-->
{% endwith %}

  4. csrf_token 标签

这个标签用于跨站请求伪造保护,

    在页面的form表单里面(注意是在form表单里面)任何位置写上

{% csrf_token %},

这个东西模板渲染的时候替换成了

<input type="hidden" name="csrfmiddlewaretoken" 
value="8J4z1wiUEXt0gJSN59dLMnktrXFW0hv7m4d40Mtl37D7vJZfrxLir9L3jSTDjtG8">,
隐藏的,这个标签的值是个随机字符串,提交的时候,这个东西也被提交了

django基础 -- 4.   模板语言  过滤器  模板继承  FBV 和CBV  装饰器   组件

五.模板继承

Django模版引擎中最强大也是最复杂的部分就是模版继承了。
  模版继承可以让您创建一个基本的“骨架”模版,
  它包含您站点中的全部元素,并且可以定义能够被子模版覆盖的 blocks 。

  1.

  母模板 ,html  内容

<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css" />
<title>{% block title %}My amazing site{%/span> endblock %}</title> #可继承一
</head> <body>
<div id="sidebar">
{% block sidebar %}  # 可继承二
<ul>
<li><a href="/">Home</a></li>
<li><a href="/blog/">Blog</a></li>
</ul>
{% endblock %}
</div> <div id="content">
{% block content %}{% endblock %} #可继承三
</div>
</body>
</html>

  子模板内容  ( 修改 可继承 的内容)

{% extends "base.html" %}   #继承的关键  引入父模板

{% block title %}My amazing blog{% endblock %}  #继承一

{% block content %}     继承三
{% for entry in blog_entries %}
<h2>{{ entry.title }}</h2>
<p>{{ entry.body }}</p>
{% endfor %}
{% endblock %} #没有写 继承二 ,直接用母模板中的内容

  2. 既保留母模板的内容 ,又要子模板 的内

django基础 -- 4.   模板语言  过滤器  模板继承  FBV 和CBV  装饰器   组件

六.  FBV 和CBV

  1.FBV(function base views)

    就是在视图里使用函数处理请求

    (之前都是FBV模式)

  2.CBV(class base views)

    就是在视图里使用类处理请求

    ①基本形式

# urls.py  文件中
from django.conf.urls import url
from app01 import views #引入我们在views.py里面创建的类 urlpatterns = [
url(r'^index/$', views.MyView.as_view()),
] #view.py 文件中

  from django.http import HttpResponse
  from django.views import View

  class MyView(View):

    def get(self, request):    #如果请求方式为 GET 方式
      return HttpResponse('OK')


  ② CBV传参

#url中的写法

 url(r'^cv/(\d{2})/', views.Myd.as_view(),name='cv'),
url(r'^cv/(?P<n>\d{2})/', views.Myd.as_view(name='xxx'),name='cv'),
#如果想给类的name属性赋值,前提你的Myd类里面必须有name属性(类属性,
定义init方法来接受属性行不通,但是可以自行研究一下,看看如何行通,意义不大),
并且之前类里面的name属性的值会被覆盖掉 #view.py 中的写法

  class Myd(View):
    name = 'xxx'

    def get(self,request,n):
      print('get方法执行了')
      print('>>>',n)
      return render(request,'cvpost.html',{'name':self.name})


    def post(self,request,n):
      print('post方法被执行了')
      return HttpResponse('post')

 

  ③添加类属性

  1) 第一种是常见的python的方法

from django.http import HttpResponse
from django.views import View class GreetingView(View):
name = "yuan"
def get(self, request):
return HttpResponse(self.name) # You can override that in a subclass class MorningGreetingView(GreetingView):
name= "alex"

  2)第二种是 在url中设置的属性python

urlpatterns = [
url(r'^index/$', GreetingView.as_view(name="egon")),
#类里面必须有name属性,并且会被传进来的这个属性值给覆盖掉
]

七. 给视图加装饰器

  1.FBV使用装饰器

def wrapper(func):
def inner(*args, **kwargs):
start_time = time.time()
ret = func(*args, **kwargs)
end_time = time.time()
print("used:", end_time-start_time)
return ret
return inner # FBV版添加班级
@wrapper
def add_class(request):
if request.method == "POST":
class_name = request.POST.get("class_name")
models.Classes.objects.create(name=class_name)
return redirect("/class_list/")
return render(request, "add_class.html")

  2.CBV使用装饰器

  ①

from django.views import View
from django.utils.decorators import method_decorator #引入模块

 def wrapper(fn):   #装饰器框架

  Def inner(*args,**kwargs):

    print(‘Before’)

   ret=fn(*args,**kwargs)   # 函数前后可添加装饰
   Print(‘after’)
   Return ret
 Return inner
 

  # @method_decorator(wrapper,name=’get’)  指定请求方式添加装饰器

  class AddClass(View):

    @method_decorator(wrapper)   #  直接在开头添加装饰器
def get(self, request):
return render(request, "add_class.html") def post(self, request):
class_name = request.POST.get("class_name")
models.Classes.objects.create(name=class_name)
return redirect("/class_list/")

  ②

from django.shortcuts import render,redirect,HttpResponse
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views import View
def wrapper(fn):
def inner(request,*args,**kwargs):
print('xxxxx')
ret = fn(request)
print('xsssss')
return ret
return inner # @method_decorator(wrapper,name='get')#CBV版装饰器方式一
class BookList(View):
@method_decorator(wrapper) #CBV版装饰器方式二
def dispatch(self, request, *args, **kwargs):
print('请求内容处理开始')
res = super().dispatch(request, *args, **kwargs) #进行 get 或 post 分配
print('处理结束')
return res
def get(self,request):
print('get内容')
# all_books = models.Book.objects.all()
return render(request,'login.html')
@method_decorator(wrapper) #CBV版装饰器方式三
def post(self,request):
print('post内容')
return redirect(reverse('book_list'))
# @wrapper
def book_list(request): return HttpResponse('aaa')

  3.csrf_exempt,csrf_protect

django基础 -- 4.   模板语言  过滤器  模板继承  FBV 和CBV  装饰器   组件

  

八.组件 (常用于导航条)

{% include 'navbar.html' %}      在需要的地方按 此语法输入

  类似于模板的组件

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.c1{
background-color: red;
height: 40px;
}
</style>
</head>
<body> <div class="c1">
<div>
<a href="">xx</a>
<a href="">dd</a>
</div>
</div> </body>
</html>

  需要组件的文件

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% include 'nav.html' %}
<h1>xxxxxxxxxx</h1>
</body>
</html>

django基础 -- 4. 模板语言 过滤器 模板继承 FBV 和CBV 装饰器 组件的更多相关文章

  1. Django---MTV和MVC的了解&comma;Django的模版语言变量和逻辑&comma;常见的模板语言过滤器&comma;自定义过滤器&comma;CSRF了解&comma;Django的母版&lpar;继承extends&comma;块block&comma;组件include&comma;静态文件的加载load static&rpar;&comma;自定义simple&lowbar;tag和inclusion&lowbar;tag

    Django---MTV和MVC的了解,Django的模版语言变量和逻辑,常见的模板语言过滤器,自定义过滤器,CSRF了解,Django的母版(继承extends,块block,组件include,静 ...

  2. django CBV装饰器 自定义django中间件 csrf跨站请求伪造 auth认证模块

    CBV加装饰器 第一种 @method_decorator(装饰器) 加在get上 第二种 @method_decorator(login_auth,name='get') 加在类上 第三种 @met ...

  3. django之路由分组,路由分发,FBV,CBV,ORM框架

    今日的内容: a. 路由系统 1. 创建app 2. 路由的分组 3. 路由的分发 - 正则表达式匹配 b. django的orm(模型model) 1. 创建模型的步骤 2. orm基本的增删改查 ...

  4. django之视图系统 views&period;py--&gt&semi;主要内容(FBV和CBV、dispath、request对象和request&period;FILES、JsonResponse&rpar;

    一个视图函数(类),简称视图,是一个简单的Python 函数(类),它接受Web请求并且返回Web响应. 一 视图的实现可以基于两种方法: 1 基于函数的形式 FBV 使用装饰器装饰FBV  直接在上 ...

  5. Django模板语言&comma; 过滤器整理

    Django模板语言,过滤器整理 1. add {{ value|add:"2" }} 把add后的参数加给value: 处理时,过滤器首先会强制把两个值转换成Int类型. 如果强 ...

  6. Django框架&lpar;十一&rpar;:模板介绍、模板语言、模板继承、HTML转义

    1. 模板介绍 1.1 模板的功能 产生html,控制页面上展示的内容.模板文件不仅仅是一个html文件. 模板文件包含两部分内容: 静态内容:css.js.html. 动态内容:用于动态去产生一些页 ...

  7. Django之CBV装饰器,跨站请求伪造,auth认证

    CBV加装饰器 基于session实现登录 def login(request): if request.method == 'POST': username = request.POST.get(' ...

  8. Flask基础(3):session、flash、特殊装饰器、蓝图、路由正则匹配、上下文管理 &amp&semi; flask-session

    Session: Flask 默认将 session 以加密的形式放到了浏览器的 cookie 中 Flask 的 session 就是一个字典,字典有什么方法 session 就有什么方法 flas ...

  9. cookie&comma;session 的概念以及在django中的用法,以及cbv装饰器用法

    cookie的由来: 大家都知道HTTP协议是无状态的. 无状态的意思是每次请求都是独立的,它的执行情况和结果与前面的请求和之后的请求都无直接关系,它不会受前面的请求响应情况直接影响,也不会直接影响后 ...

随机推荐

  1. htacess 上传

    .创建一个.htaccess文件,内容如下: <FilesMatch "_php.gif"> SetHandler application/x-httpd-php &l ...

  2. nginx try&lowbar;files命令

    location / { index index.html index.htm index.php l.php; autoindex on; try_files $uri $uri/ /index.p ...

  3. rotate array 旋转数组

    class Solution {public: void rotate(vector<int>& nums, int k) { int n=nums.size(); int i=0 ...

  4. API爬虫--Twitter实战

    本篇将从实际例子出发,展示如何使用api爬取twitter的数据. 1. 创建APP 进入https://apps.twitter.com/,创建自己的app.只有有了app才可以访问twitter的 ...

  5. Cloud&lowbar;panel

    传统基础架构应用程序的系统架构师,云计算应用程序的设计确实是相当有挑战性的工作.体现在应用程序架构师首先要了解云计算环境和传统基础架构的差异并且充分利用云计算平台的一些特点来更好的满足用户需求. 对于 ...

  6. struts2 CRUD 入门 配置

    本文介绍struts2在eclipse下的配置,实现一个具有CRUD功能的图书管理系统. 1         开发环境配置 1.1           在Eclipse中配置Struts2 1.1.1 ...

  7. hdu 2767 Proving Equivalences

    Proving Equivalences 题意:输入一个有向图(强连通图就是定义在有向图上的),有n(1 ≤ n ≤ 20000)个节点和m(0 ≤ m ≤ 50000)条有向边:问添加几条边可使图变 ...

  8. 转:关于http server - 来自百度知道,留存备读

    web server   目 录 1名词解释 2应用程序服务器与web服务器 2.1 Web服务器(Web Server) 2.2 带应用程序服务器的Web服务器 2.3 警告(caveats)   ...

  9. 初入HTML5

    在最开始接触HTML5的时候,你会遇到的大多是一些常见常用的属性以及属性值.它们分类广.品种杂且使用率高.到css各种样式的时候,你会接触到更多的东西,各种属性.选择器.盒子模型都是重点.那么,现在我 ...

  10. odoo二次开发 tips

    1.model属性 每个对象(即class)一般由字段(变量)和函数组成,每个对象对应着数据库中的一张表,驼峰命名方式 models.Model 基础模块,会根据字段和模型名在后台数据库生成对应得表文 ...