1.基于函数的视图和基于类的视图
1.用基于类的视图,可以自动识别是get 还是post 类型。
只需要重写 get post 方法就行了
子urls中
from django.urls import path,re_path
from stu import views
urlpatterns = [
path('',views.IndexView.as_view()),
re_path('hello/(.*)$',views.StaticView.as_view()),
]
2.对类中定义 get post方法
class IndexView(View):
def get(self,request,*args,**kwargs):
return render(request,'index.html')
def post(self,request,*args,**kwargs):
return HttpResponse('Post')
3 html中,写一个post
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/student/" method="post">
{% csrf_token %}
<input type="submit" value="login"/>
</form>
</body>
</html>
2.静态页面的读取
对于http://127.0.0.1:8000/student/hello/bd_logo1.png
返回静态页面中的图片
1.原始实现
1.静态页面中包括 css images js
2.定义子路由
re_path('hello/(.*)$',views.StaticView.as_view()),
3.views中 获取路径,返回页面
import re,os
class StaticView(View):
def get(self, request, *args, **kwargs):
#获取路径
filepath = request.path
print(filepath)
m = re.match('/student/hello/(.*)',filepath)
filename = m.group(1)
print(filename)
filedir = os.path.join(os.getcwd(),'static\\images',filename)
print(filedir)
if not os.path.exists(filedir):
raise Http404()
#mimetypes
return FileResponse(open(filedir,'rb'),content_type='image/png'
,content_type=’/’ 匹配任意内容。
2.django实现
1.setting 中加入STATICFILES_DIRS
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static\images'),
os.path.join(BASE_DIR,'static\css'),
os.path.join(BASE_DIR,'static\js')
]
2.运行 http://127.0.0.1:8000/static/bd_logo1.png
3.设置css js images 都在页面显示
html
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="{% static 'my.css' %}" type="text/css"/>
<script type="text/javascript" src="{% static 'my.js' %}"></script>
</head>
<body>
<img src="/static/1.png">
<img src="{% static '1.png' %}">
<form action="/student/" method="post">
{% csrf_token %}
<input type="submit" value="login"/>
</form>
</body>
</html>
css 加边框
img{
border:3px solid red;
}
js 加弹框
window.onload = function(){
alert('hello')
document.getElementById('btn').onclick = function(){
alert('hhahah')
}
}
3.模板标签渲染 传值
(1)通过关键字,设置Conten内容,传到Temple中
>>> from django.template import Context, Template
>>> t = Template('My name is {{ name }}.')
>>> c = Context({'name': 'nowamagic'})
>>> t.render(c)
u'My name is nowamagic.'
(2)with open 读取html文件
def query_view1(request):
with open('temples/index.html','rb') as fr:
content = fr.read()
t = Template(content)
c = Context({'name': 'nowamagic'})
renderStr = t.render(c)
return HttpResponse(renderStr)
(3)loader模块获取模板对象
def query_view1(request):
t = loader.get_template('index.html')
renderStr = t.render({'name': 'nowamagic'})
return HttpResponse(renderStr)
呈现先找主templates中的html,再找应用下templates中的html
4 模板标签语法 获取值
(1)列表,字典的取值
所有方法,对象在html中都是没有括号的。
(2)for 循环的取值 快标签
1.建立html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>获取views传值</h3>
<ol>
<li>{{ user.uname }}</li>
<li>{{ numlist.2}}</li>
<li>{{ current.year }}</li>
<li>{{ str.upper }}</li>
</ol>
{% for n in numlist reversed%}
{{ forloop.revcounter }}-{{ n }}<br/>
{% endfor %}
<br/>
<hr/>
{% for k,v in user.items %}
{{ k }}-{{ v }}<br/>
{% endfor %}
<br/>
<hr/>
{% for foo in hello %}
{{ foo }}
{% empty %}
无记录
{% endfor %}
<hr/>
{% if score > 90 %}
优秀
{% elif score > 80 %}
良好
{% else %}
再接再厉~
{% endif %}
{#{% csrf_token %}#}
{% autoescape off %}
{{ loc }}
{% endautoescape %}
</body>
</html>
2. 传值进去
class GetDataView(View):
def get(self,request):
import datetime
loc = '<script>location.href="/student2/r3/"</script>'
return render(request,'getdata1.html',{'user':{'uname':'zhangsan','pwd':'123'},'numlist':[1,2,3,4,5],'current':datetime.datetime.today(),'str':'hello','score':88,'loc':loc})
3.页面展示
5 过滤器
相当于管道似的,先取值,再通过|后面function进行操作
(1)传值
class IndexView(View):
def get(self,request):
import datetime
d = datetime.datetime.today()
urlstr = '<h3>北京</h3>'
return render(request,'index.html',{'num':8,'str':'明天天气咋样','d':d,'urlstr':urlstr})
(2)页面接受
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ num|add:'2' }}<br/>
{{ str|capfirst }}<br/>
{{ d|date:'Y-m-d H:i:s' }}<br/>
{{ num|divisibleby:'2' }}<br/>
{{ urlstr|safe }}<br/>
{{ str|truncatewords:'2' }}<br/>
{{ str|truncatechars:'5' }}
</body>
</html>
(3)显示
5.自定义过滤器
(1)应用stu下创建包 包名和函数名不能错
(2)创建库 编写 filter_mark
from django.template import Library
register = Library()
@register.filter
def splitstr(value,args):
start,end = args.split(',')
value = value.encode('utf-8').decode('utf-8')
return value[int(start):int(end)]
(3)传值 views
class IndexView(View):
def get(self,request):
content = '###'
str = 'aadsd'
return render(request,'index.html',{'c':content,'str':str})
(4)html写
{% load filter_mark %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ c }}
<br/>
{{ str|splitstr:'1,3' }}
</body>
</html>
6. 全局上下文 把公共内容放在某个特定的地方
比如:百度页面的导航栏 每个页面都有。
1.应用下创建my_context_processors.py 文件 保存全局参数
def getData(request):
return {'uname':'zhangsan'}
2.setting中设置TEMPLATES
OPTIONS中添加 ‘stu1.my_context_processors.getData’
3.view中返回页面
from django.views import View
class Index(View):
def get(self,request):
return render(request,'index1.html')
4.html中直接用默认参数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ 'uname' }}
</body>
</html>
5.结果为:
7.模板继承
1.在总的tmplate中创建base.html模板,
写head.html (也是总的模板当中)
{% include 'head.html '%}
主题内容需要在子template中,写一个block
{%block main%}
{%endblock main%}
2.在应用下创立tmplate文件
query.html
继承base.htm
{% extend 'base.html '%}