day51:django:dispatch&模板渲染&过滤器&标签&组件&静态文件配置

目录

1.dispatch

2.模板渲染

3.过滤器

4.标签

5.组件

6.静态文件配置

dispatch

回顾:CBV对应的URL传参

urls.py

url(r'^book/(\d+)/(\d+)/', views.Book.as_view()),

views.py

from django.shortcuts import render, HttpResponse
from django.views import View class Book(View):
def get(self,request, year, month):
return HttpResponse(year+ month + '书籍') def post(self,request,year, month):
pass

CBV的实质中提到了dispatch方法

  Django的url是将一个请求分配给可调用的function的,而不是一个class。

  针对这个问题,class-based view提供了一个as_view()静态方法(也就是类方法)

  调用这个方法,会创建一个类的实例,然后通过实例调用dispatch()方法

  dispatch()方法会根据request的method的不同调用相应的方法来处理request(如get() ,post() 等)

dispatch在底层是如何实现的 ?

'''重点: 反射,将请求方法分发到同名的类方法去处理'''
def dispatch(self, request, *args, **kwargs):
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)

可以拓展dispatch方法

在请求方法分发给对应的类方法执行前后,做一些事情

from django.shortcuts import render, HttpResponse
from django.views import View class Book(View):
def dispatch(self, request, *args, **kwargs):
print('dispatch front')
ret = super().dispatch( request, *args, **kwargs) # 继承父类dispatch的所有内容
print('dispatch behind')
return ret def get(self,request, year, month):
print('get method')
return HttpResponse(year+ month + '书籍') def post(self,request,year, month):
pass '''执行结果'''
dispatch前
get方法
dispatch后

模板渲染

views.py

from django.shortcuts import render

def home(request):
username = 'SByaya' # 可以传字符串
num = 10 # 可以传数字
lst1 = [11,22,33] # 可以传列表
dict1 = {'k1':'v1','k2':'v2'} # 可以传字典
class A:
def __init__(self):
self.name = 'yayasillydog'
def get_name(self):
return self.name + '太蠢了'
a = A() # 可以传类对象 dic = {
'username':username,
'num':num,
'lst1':lst1,
'dict1':dict1,
'a':a, } return render(request,'home.html',dic)

home.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
</head>
<body> <h1>Welcome to dog's home!!</h1>
<h1>{{ username }}</h1>
<h1>{{ num }}</h1>
<h1>{{ lst1 }}</h1>
<h1>{{ lst1.1 }}</h1> <!-- 用点索引来取值 -->
<h1>{{ dict1 }}</h1>
<h1>{{ dict1.k1 }}</h1> <!-- 字典.键来取值 -->
<h1>{{ a.name }}</h1> <!-- 可以获取对象里的属性 -->
<h1>{{ a.get_name }}</h1> <!-- 只能获取对象里的无参方法,不能够获取有参方法 --> </body>
</html>

过滤器

过滤器语法

语法:{{ value|filter_name:参数 }}

注意点:管道符两边不能有空格,有参数的冒号加参数,无参数的不需要冒号

常见的过滤器

1.default默认值

如果一个变量没有传值或者值为空,使用给定的默认值。 否则,使用变量的值。

没有传值

'''没有传值'''
def home(request):
username = 'yayapig' # 可以传字符串
dic = {
# 'username':username, # 没有传username
} return render(request,'home.html',dic)

值为空

'''值为空'''
username = ''

default默认值语法

<p>
{{ username|default:'Libolun' }}
</p

2.length 判断长度

<p>
{{ username|length }}
</p>

3.filesizeformat 展示为可读的大小,自动计算单位

<p>
{{ file_size|filesizeformat }}
</p>

4.slice 切片

<p>
{{ msg|slice:'0:4' }}
</p>

5.date 日期格式化

<p>
{{ current_time|date:"Y-m-d H:i:s" }} <!-- 注意分钟是用i来表示 -->
</p>

6.safe 将标签字符串识别为一个标签效果

使用safe的目的:防止xss攻击(跨站脚本攻击)

views.py

def test(requqest):
a_tag = '<a href="">某宝</a>'
return render(request,'test.html',{'a_tag':a_tag})

test.html

<p>
{{ a_tag|safe }}
</p>

7.truncatechars 字符截断

注意:7包括4个字符加3个省略号

<p>
{{ msg|truncatechars:7 }}
</p>

8.truncatewords 单词截断

<p>
{{ msg|truncatewords:2 }}
</p>

9.cut 移除value中所有的与给出的变量相同的字符串

<p>
{{ msg|cut:' ' }} <!-- 去除value中所有的空格 -->
</p>

10.join 字符串拼接

<p>
{{ list1|join:'+' }} <!-- 等同于python中的"+".join(list1) -->
</p>

标签

标签语法

语法: {% 标签逻辑 %}

for循环标签

1.循环列表

<ul>
{% for i in lst1 %}
<li>{{ i }}</li>
{% empty %}
<span>哥,啥也木有啊</span>
{% endfor %}
</ul>
<!-- 如果lst1为空,或者后台没有给lst1数据,那么就展示empty下面的内容 -->

2.循环字典

<ul>
{% for k,v in dic1.items %}
<li>{{ k }}--->{{ v }}</li>
{% endfor %}
</ul>
<!-- 在循环中,可以接dic1.keys values items -->

3.循环嵌套

<ul>
{% for i in lst1 %}
<li>{{ i }}--->{{ forloop.counter }}</li>
{% if forloop.last %}
{% for ii in i %}
<li>{{ ii }}--->{{ forloop.counter }}--->{{ forloop.parentloop.counter }}</li>
{% endfor %}
{% endif %}
{% endfor %}
</ul>

forloop用法

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

if循环标签

if语句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判断,注意条件两边都有空格。

views.py

from django.shortcuts import render

def home(request):
number = 102 dic = {
'number':number,
} return render(request,'home.html',dic)

home.html

{% if number == 100 %}
<h1>猜对了</h1>
{% elif number == 101 %}
<h1>101不对呀</h1>
{% else %}
<h1>这更不对了</h1> {% endif %}

if语句也可以和过滤配合使用

{% if user_list|length > 5 %}  <!--结合过滤器来使用-->
可以可以
{% else %}
不行不行
{% endif %}

组件

组件:把完整的一套功能封装成模块

在前端中,就是把一套完整的样式封装起来,供其他人使用

在其他的html文件中引入一个html文件

在index.html中如果我们想使用已经封装好的zujian.html,该怎么引入呢?

index.html

{% include 'zujian.html' %} 

zujian.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body> <h1 style="color:red;">这是导航栏</h1> </body>
</html>

静态文件配置

1.在项目根目录下创建一个文件夹,比如名称为xx

2.在setting.py中写入如下内容

STATIC_URL = '/static/' #别名

STATICFILES_DIRS = [
os.path.join(BASE_DIR,'jingtaiwenjian'), # 注意别忘了写逗号,第二个参数就是项目中你存放静态文件的文件夹名称
]

3.在html文件中使用别名

设置STATIC_URL的意义

别名也是一种安全机制,浏览器上通过调试台你能够看到的是别名的名字,这样别人就不能知道你静态文件夹的名字了,不然别人就能通过这个文件夹路径进行攻击。

STATIC_URL的用法

<!-- 两种引入方式 -->
<link rel="stylesheet" href="/static/css/test.css">
<link rel="stylesheet" href="{% static 'css/test.css' %}"> <!-- 导入一张图片 -->
<img src="/static/imgs/test.png" alt=""> <!-- 引入js文件 -->
<script src="/static/js/xx.js"></script>

1.在项目根目录下创建一个文件夹,比如名称为xx

2.在setting.py中写入如下内容

上一篇:x264_param_t结构


下一篇:Django框架之第二篇