python学习:Django的Url,View,Template (2)
Django加载静态资源
静态文件引入:
setting.py文件增加:
STATIC_URL = '/static/'
#静态文件绝对路径
STATICFILES_DIRS = (
os.path.join(BASE_DIR,"statics"),
)
方式1:直接/static路径,hello.html修改:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello page</title>
</head>
<body>
<h1>hello</h1>
<h2>当前时间:{{time}}</h2>
<img src="/static/pic1.jpg">
</body>
</html>
方式2:load静态文件方式
修改hello.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello page</title>
<!--加载静态文件-->
{% load staticfiles %}
</head>
<body>
<h1>hello</h1>
<h2>当前时间:{{time}}</h2>
<!--<img src="/static/pic1.jpg">-->
<img src="{% static 'pic1.jpg' %}">
</body>
</html>
Django的URL系统
正则表达式URL
可以使用正则表达式匹配url路径。
re_path类可以匹配正则表达式路径,
url类也可以实现正则,需要导入相应类模块
from django.conf.urls import url
修改urls.py,将正则表达式可以加括号,表示分组,也可以不加。
from django.conf.urls import re_path
#url_control/(\d{4})/(\d{2})
#url路径匹配:url_control/4位数字/2位数字
urlpatterns = [
path('admin/', admin.site.urls),
path('show_time/',views.show_time),
re_path(r'url_control/(\d{4})/(\d{2})',views.url_control)
]
在views.py创建视图函数:param1和param2就是 urls中括号分组的对应内容,urls中必须使用括号分组,不然视图函数这获取不到对应内容。
#url控制,传递参数
def url_control(request,param1,param2):
print(param1,param2);
strs = "参数1:" + param1 + "参数2:" + param2;
return HttpResponse(strs);
也可以使用命名分组?P<分组名>,修改urls.py:
re_path(r'url_control1/(?P<year>\d{4})',views.url_control1)
views.py
#url控制,传递参数,命名分组,参数名必须对应分组名,位置可以不对应
def url_control1(request,year):
print(year);
strs = "参数1:" + year
return HttpResponse(strs);
URL别名使用
别名使用的优点,当修改了url的path路径时,对应html的使用别名方式引用的话,就不需要修改。
修改urls.py:name=”别名”
path("url_alias",views.url_alias,name="alias")
修改views.py:建立对应视图函数url_alias
def url_alias(request):
#请求使用的方法
#request.GET 和request.POST,根据提交方式获取提交的数据
print("request:",request.method);
if(request.method == "POST"):
print(request.POST);
return HttpResponse("登陆成功")
return render(request,"login.html");
新建login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登陆页面</title>
{% load staticfiles %}
</head>
<body>
<!--使用别名作为action-->
<!--<form action="{% url 'alias' %}" method="POST">-->
<!--<input type="text" name="name">-->
<!--<input type="password" name="pwd">-->
<!--<input type="submit">-->
<!--</form>-->
<!--直接url作为action-->
<form action="/url_alias/" method="POST">
<input type="text" name="name">
<input type="password" name="pwd">
<input type="submit">
</form>
</body>
</html>
Django跨过csrf检查
注意:使用POST提交会会出现禁止403信息,这是Django的CSRF的安全中间件限制。
将setting中CSRF中间件注释掉:
我们也可以不注释掉中间件,选择form表表单中加{% csrf_token %}
<!--直接url作为action-->
<form action="/url_alias/" method="POST">
<input type="text" name="name">
<input type="password" name="pwd">
<input type="submit">
{% csrf_token %}
</form>
视图函数使用装饰器csrf_exempt,让其csrf检查失效。
示例:
from django.views.decorators.csrf import csrf_exempt,csrf_protect
#使用csrf_exempt可以跨过csrf的检查
@csrf_exempt
def break_csrf(request):
return HttpResponse("ok")
URL分发
每个应用可以有自己的URL,项目urls.py文件负责分发到子URL就行了。
为helloApp应用创建一个urls.py文件
''''
子应用helloApp的urls处理
'''
from django.contrib import admin
from django.urls import path
from helloApp import views
#url分发路径
urlpatterns = [
path("dispatch_page/",views.dispatch_page)
]
修改项目的urls.py:使用include(‘应用的urls文件’),
from django.urls import include
path("url_dispatch/",include('helloApp.urls'))
修改views.py文件,其实views.py文件是helloApp应用的视图函数文件,项目urls应该通过分发方式访问到helloApp的对应视图函数。
创建对应dispatch_page的视图函数
#url分发
def dispatch_page(request):
#分发helloApp页面
return HttpResponse("分发页面");
访问时通过url_dispatch/dispatch_page/才能访问到页面
Django的View视图函数
Django项目中每个应用都有一个views.py文件,这里面就是应用的视图函数。
Http请求中核心对象:HttpRequest对象和HttpResponse对象。
HttpRequest对象:
Request.method:http请求提交方式;
Request.POST:http请求POST方式传递数据;
Request.GET:http请求GET方式传递数据;
Request.path:http请求路径;
Request.get_full_path():http请求路径;
HttpResponse对象:
返回一个页面或者信息。
使用return HttpResponse(“信息”);
或者使用return render(request,”html页面模板”,{参数字典});
修改helloApp的urls.py文件,添加path("show_view/",views.show_view)
'''
子应用helloApp的urls处理
'''
from django.urls import path
from helloApp import views
#url分发路径
urlpatterns = [
path("dispatch_page/",views.dispatch_page),
path("show_view/",views.show_view)
]
修改views.py文件,添加show_view视图函数:
#view语法
#HttpRequest和HttpResponse对象
def show_view(request):
#httprequest对象属性
print('POST传递信息:',request.POST);
print('GET传递信息:',request.GET);
print('HTTP提交方式:',request.method);
print('http路径:',request.path);
#参数
header = "标题"
body = "这是一条信息"
#httpresponse返回信息
# return HttpResponse("hello");
#使用render返回模板页面
return render(request,"template.html",{"header":header,"body":body});
创建模板html:template.html,页面可以直接通过{{字典键}}获取到render传递的参数字典
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>模板页面</title>
</head>
<body>
<h1>{{header}}</h1>
<p>{{body}}</p>
</body>
</html>
也可以使用locals(),可以指代所有视图函数局部变量。
两个语句效果相同:
#使用render返回模板页面
return render(request,"template.html",{"header":header,"body":body});
#使用locals(),将参数字典替代,locals代表所有局部变量,和模板html中{{}}对应参数名对应
return render(request,"template.html",locals());
template.html可以通过{{}}符号拿到对应视图函数的所有局部变量,当然request也算是局部变量
<p>{{request.path}}</p>
使用redirect()重定向页面
from django.shortcuts import redirect
#使用redirect,重定向到其他页面
return redirect("https://www.baidu.com");
Django的Template模板
使用Template模板可以使python代码和html代码解耦。不用使用HttpResponse(html代码字符串)。
模板组成就是Html代码结构+逻辑控制语句,Template对象+Context对象。Template就是templates中新建的html文件,Context就是{{}}的变量。
Django模板渲染过程:
命令:进入Django项目环境
python manage.py shell
#引入Template和Context类
from django.template import Context,Template
#得到template,context对象
template = Template(“<h1>{{header}}</h1>”);
context = Context({“header”:”标题”});
#渲染模板,得到真实html显示文件
html = template.render(context);
#使用Response返回
return HttpResponse(html);
Django模板语法
变量:{{}}双大括号括起来的,对应视图函数中的变量。
取值:{{.}},使用大括号.访问视图函数的变量。
对应views视图函数,添加变量
list1 = ["hello","worlld"];
dict1 = {"name":"tom","age":11}
#类对象
animal = Animal("猴子");
#返回一个html页面
return render(request,"hello.html",{"time":t,"list":list1,"dict":dict1,"animal":animal});
模板html中添加
<!--模板取值
使用.符号
获取list,dict,class的值
-->
<div>{{list.0}}</div>
<div>{{list.1}}</div>
<div>{{dict.name}}</div>
<div>{{dict.age}}</div>
<div>{{animal.name}}</div>
Django的过滤器
变量内置函数:
add:给变量加上相应值
capfirst:首字母大写
cut:从字符串移除指定字符
addslashes:给变量引号前加斜杠
default:如果值为false,替换成默认值;
default_if_none:如果值为空,替换成默认值;
date:显示日期
safe:关闭安全机制,例如后端传来a标签html字符串,如果不关闭安全机制,直接显示为字符串,不会变成可点击链接。
示例:
视图函数views.py中变量:
def show_time(request):
## response返回信息
# response = HttpResponse("hello");
# return response;
t = time.ctime();
list1 = ["hello","worlld"];
dict1 = {"name":"tom","age":11}
#类对象
animal = Animal("猴子");
#链接字符串
links="<a href='http://www.baidu.com'>click</a>"
#返回一个html页面
return render(request,"hello.html",{"time":t,"list":list1,"dict":dict1,"animal":animal,"links":links});
#返回一个html页面,相同效果,locals代表所有局部变量
#return render(request,"hello.html",locals())
html模板页面:
<!--过滤器函数-->
age+10:<div>{{dict.age|add:10}}</div>
首字母大写:<div>{{dict.name|capfirst}}</div>
移除指定字符:<div>{{dict.name|cut:"m"}}</div>
显示日期:<div>{{time|date:"Y-m-d"}}</div>
显示默认:<div>{{dict.name|default:"为空,默认"}}</div>
链接字符串:<div>{{links}}</div>
链接字符串(safe):<div>{{links|safe}}</div>
{% autoescape off %}
链接(关闭安全机制):<div>{{links}}</div>
{% endautoescape %}
Django的标签
标签标识{% 标签 %}
if和for标签
if语法:{% if 条件 %}
语句块
{% elif 条件%}
语句块
{% else %}
语句块
{% endif %}
for语法:
{% for obj in objlist %}
{{obj}}
{% endfor %}
可以使用{{forloop.counter}},可以获取循环索引,默认1开始计数。设置{{forloop:counter0}}从零开始计数;
{{forloop.revcounter}}倒序。123变成321;
{{forloop.first}},第一次循环时为True;
{% empty %}:for循环列表为空
示例:
<!--if 和for语句-->
{% if dict.age > 10 %}
age大于10显示:<span>{{dict.name}}</span></br>
{% elif dict.age > 5 %}
age大于5显示:<span>{{dict.name}}</span></br>
{% else %}
age大于0显示:<span>{{dict.name}}</span></br>
{% endif %}
{% for l in list%}
for遍历{{ forloop.counter }}:<span>{{ l }}</span></br>
{% endfor %}
{% for l in list%}
for遍历{{ forloop.counter }}:<span>{{ l }}</span></br>
{% empty %}
<h1>for循环为空</h1>
{% endfor %}
其他标签
{% url %}:配置路由地址。
{% with %} 语句 {% endwith %}:使用简单变量名,替代复杂变量名。
{% verbatim %} {{hello}} {% endvervatim %}:禁止render,原样输出verbatin包裹的语句。
{% load %}:加载标签库
自定义filter
自定义filter不能传多个参数。
1.在app中创建templatetags模块(必须)
2.创建.py文件,例如:my_tag.py
示例:mytag.py文件:
from django import template
from django.utils.safestring import mark_safe
#注册对象
register = template.library()
#使用装饰器,将函数标识为一个filter
@register.filter
def mul(x,y):
return x*y;
3.导入到html,{% load mytag %}
4.html使用自定义tag
示例:
<!--自定义filter-->
年龄乘上2:<span>{{ dict.age|filter_mul:2 }}</span></br>
自定义标签
自定义标签不能使用在控制语句中。
示例:mytag.py文件增加
#自定义标签
@register.simple_tag
def tag_mul(x,y,z):
return x*y*z;
html中使用:
<!--自定义标签-->
年龄乘上多个值:<span>{% tag_mul dict.age 2 3 %}</span>
Django的模板继承
{% block%}标签,在child_template.html中定义html块
{% block bl1 %}
<h1>模板块</h1>
{% endblock %}
{%extends%}标签新建的child_template.html可以继承一个已有template.html,结构和template.html一样。
{% extends “template.html” %}
{% block bl1 %}
<h1>新的模板块内容</h1>
{% endblock %}
本文来自博客园,作者:渔歌晚唱,转载请注明原文链接:https://www.cnblogs.com/tangToms/articles/14151290.html

浙公网安备 33010602011771号