setting中注释:
#'django.middleware.csrf.CsrfViewMiddleware',
FBV模式:
function base views
url.py:
re_path(r'fbv', views.fbv)
views.py:
def fbv(request):
return render(request, 'fbv.html', {'method': request.method})
templates文件夹下:
创建fbv.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>fbv</title>
</head>
<body>
<h3>{{method}}</h3>
<form action="fbv" method="post">
<input type="submit">
</form>
</form>
</body>
</html>
运行环境:python manage.py runsrver 0.0.0.0:8080
浏览器进入默认get方式如下图:
点击提交按钮,通过form表单实现post请求,如下图:
CBV模式:
class base views
url.py:
re_path(r'cbv$', views.CBV.as_view()),
views.py:
class CBV(View):
def get(self,request):
return render(request, 'cbv.html', {'method': 'CBV.GET'})
def post(self,request):
return HttpResponse('<h3>CBV.POST</h3>')
cbv.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>cbv</title>
</head>
<body>
<h3>{{method}}</h3>
<form action="cbv" method="post">
<input type="submit">
</form>
</form>
</body>
</html>
自动加载django。
浏览器打开:
点击提交按钮,通过form表单实现post的工作:
CBV的动作是:
http请求 - url - views.CBV.as_views() - 进入View类 - dispatch方法读取method - 执行CBV类中的对应的方法。
会通过自己继承的View类中,自动找到method,执行对应的类函数,不需要人工判断是GET还是POST。