第三单元
视图层
第三单元的重要
方法
生成迁移文件:python .\manage.py makemigrations
执行迁移:python .\manage.py migrate
迁移完 在创建python .\manage.py createsuperuser
get和post
定义 post和get 是http协议与服务器的交互
get的请求处理
def index(request):
print(request.GET) # <QueryDict: {'name': ['jack'], 'id': ['1']}>
print(type(request.GET)) # <class 'django.http.request.QueryDict'>
name_ = request.GET.get('name')
id_ = request.GET.get('id')
content = '%s:%s' % (name_,id_)
return HttpResponse(content)
使用时用这个来获取结果
http://127.0.0.1:8000/?name=jack&id=1
get和post的区别
post的请求不会被浏览器缓存
post提交数据长度
post比get更安全
post的请求处理
因为涉及了表单 需要用html页面
<body>
<div>这是一个关于 POST 的测试</div>
<form action="/" method="POST">
{% csrf_token %}
账号:<input type="text" name="account">
<br>
密码:<input type="password" name="passwd">
<input type="submit" value="提交">
</form>
</body>
- 写一个视图函数用来捕获当前表单使用 POST 形式提交的数据:
def index(request):
if request.method="POST":
print(request.POST)
print(type(request.POST))
account = request.POST.get("account")
passwd = request.POST.get("passwd")
content = "%s:%s" % (account,passwd)
return HttpResponse(content)
return render(request,"index.html") #在使用 get 形式请求时,返回表单页面
<form action="/" method="POST">
{% csrf_token %}
<input type="checkbox" name="taste" value="eat">吃
<input type="checkbox" name="taste" value="sleep">睡
<input type="checkbox" name="taste" value="play">耍
<input type="submit" value="提交">
</form>
视图请求
from django.http import HttpResponse
def index(request):
return HttpResponse('Hello world')
错误:
[24/Apr/2022 19:31:47] “GET /admin/auth/ HTTP/1.1” 200 2882
[24/Apr/2022 19:31:47] “GET /admin/auth/ HTTP/1.1” 200 2882
[24/Apr/2022 19:31:47] “GET /admin/auth/ HTTP/1.1” 200 2882
[24/Apr/2022 19:32:46] “GET /myview/ HTTP/1.1” 200 42
[24/Apr/2022 19:32:54] “GET /index/ HTTP/1.1” 200 475
[24/Apr/2022 19:33:00] “POST /myview2/ HTTP/1.1” 200 37
Not Found: /
[24/Apr/2022 19:35:53] “GET / HTTP/1.1” 404 2244
[24/Apr/2022 19:36:00] “GET /admin/ HTTP/1.1” 200 3005
Not Found: /
[24/Apr/2022 19:37:04] “GET / HTTP/1.1” 404 2244
[24/Apr/2022 19:37:12] “GET /myview/ HTTP/1.1” 200 42
Not Found: /mysql
[24/Apr/2022 19:37:21] “GET /mysql HTTP/1.1” 404 2277
解决方法 :
在使用创建超级用户的时候 要注意自己使用的方法是否正确
用的是get 方法还是post方法
因为这个方法用错了 导致了错误
总结
get和post的应用方法
还有视图响应返回