1:简历
在这里我们使用路由匹配视图类(而不是视图函数)
2:路由(urls.py)
from django.urls import path,re_path,include
from app01 import views
urlpatterns = [
path("index1/", views.index1.as_view()), #在使用路由匹配视图类的时候:寻找视图类的时候必须加后缀.as_view()
注意:在路由匹配视图类的时候:必须在视图类名加上后缀.as_view()
3:视图(views.py)
(1)导包:
from django.views import View
注意:在视图类中写的类,必须继承View否则会报错
from django.views import View
class index1(View):
"""路由匹配类的时候类必须继承:View"""
"""不必我们直接做判断他是什么方法,django会给我们自动判断他是什么方法
并自动执行相对应的方法
"""
def get(self,request):
"""get请求必须给一个参数request来接受信息"""
return render(request,"index1.html")
def post(self,requset):
return HttpResponse("成功进入post请求")
(2):顺序
用户输入对应的url----进入django的路由------django路由匹配视图类-----进入视图类后,先执行我们继承View类的dispatch方法,判断他是什么方法,然后进入我们写的类方法中.
在这里我们可以自己写dispatch方法,以便更加完善我们的程序
class index1(View):
"""路由匹配类的时候类必须继承:View"""
"""不必我们直接做判断他是什么方法,django会给我们自动判断他是什么方法
并自动执行相对应的方法
"""
def dispatch(self, request, *args, **kwargs):
"""在进入视图类的index1中先执行dispatch函数"""
print("先开始走这里面")
# 调用我们继承View类方法中的dispatch函数,super(index1,self)第一个参数必须是视图类的名字
obj=super(index1,self).dispatch(request, *args, **kwargs)
print("出来的要结束了")
return obj
def get(self,request):
"""get请求必须给一个参数request来接受信息"""
return render(request,"index1.html")
def post(self,requset):
a=requset.POST.get("name")
return HttpResponse(a)
html(index1.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" action="/index1/">
{% csrf_token %}
<input type="text" name="name"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>