一、Django 视图概念
Django 中的视图的概念是「一类具有相同功能和模板的网页的集合」。在 Django 中,网页和其他内容都是从视图派生而来。每一个视图表现为一个 Python 函数(或者说方法,如果是在基于类的视图里的话)。Django 将会根据用户请求的 URL 来选择使用哪个视图(更准确的说,是根据 URL 中域名之后的部分)。它接受Web请求并返回Web响应。二、路由配置
2.1 helloworld
在setting.py中通过ROOT_URLCONF指定根级url配置
urlpatterns是一个url()实例表的列表
urls.py
//setting指定路径设置
urlpatterns = [
path('admin/', admin.site.urls),
path('book/', include('book.urls')),
]
//include中urls.py
urlpatterns = [
path('index/', views.index),
]
view.py
def index(request):
return HttpResponse("hello world")
http://127.0.0.1:8000/book/index/
2.2 HttpResponse
2.2.1 get请求: http://127.0.0.1:8000/book/index/?id=1&name=li
2.2.2 post请求:
setting 中配置TEMPLATES ‘DIRS’: [BASE_DIR / ‘templates’]
Django 1.8 及以上的版本 settings.py,修改 TEMPLATES 中的 DIRS
TEMPLATES = [
{
...
'DIRS': [os.path.join(BASE_DIR, 'templates')],
...
},
]
Django 1.7 及以下的版本,修改 TEMPLATE_DIRS:
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
urls.py
//urls.py
from django.contrib import admin
from django.urls import path, include
from book import views
urlpatterns = [
path('admin/', admin.site.urls),
path('book/', include('book.urls')),
]
//book.urls.py
from django.urls import path
from book import views
urlpatterns = [
path('index/', views.index),
path('usrInfo/', views.usrInfo)
]
views.py
# Create your views here.
def index(request):
return render(request, 'index.html')
def usrInfo(request):
print(request.path)
print(request.method)
# print(request.GET.get("id"))
# print(request.GET['name'])
print(request.POST['usrName'])
return HttpResponse("hello world")
templates文件下index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="/book/usrInfo/" method="POST">
{% csrf_token %}
<input name="usrName" />
<input TYPE="submit" value="submit" />
</form>
</body>
</html>
http://127.0.0.1:8000/book/usrInfo/
2.3 类视图
urls.py
path('getUsr/', views.GetTestView.as_view()),
views.py
class GetTestView(View):
def get(self, request):
return HttpResponse(request.method)
def post(self, request):
return HttpResponse(request.method)
三 部分bug
(1)问:
“ CSRF verification failed. Request aborted.
”
答:
html中输入 {% csrf_token %}
(2)问:
Exception Value: “ as_view() takes 1 positional argument but 2 were given
”
答:
path('getUsr/', views.GetTestView.as_view()),//注意是as_view()
小知识点:
(1)vscode 快速生成html
- 输入! ,选择下拉项的第一个回车确认
按tab
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
</html>