s14_04_视图函数
视图函数
# app下views.py
from django.shortcuts import HttpResponse,render,redirect
def func(request):
# request 包含用户提交的所有数据
# request.method GET / POST
# 获取请求发来的而数据
# http://127.0.0.1:8009/home?nid=123&name=alex
# request.GET.get('',None)
# request.POST.get('',None)
# request.POST['users']
# 没有users则报错,不推荐
# return HttpResponse("字符串")
# return render(request, "/path/HTML模板的路径",{'':xxx})
# return redirect('/只能填URL')
# 本地则时/home,网址无需 /
1、获取用户请求数据
request.GET
request.POST
request.FILES
request.getlist # checkbox等多选的内容
request.method
request.path_info
request.COOKIES
request.body
request.GET(request.body)
request.POST(request.body)
request.FILES
request.getlist # checkbox等多选的内容
request.Meta
request.method
request.path_info
request.COOKIES
PS:
GET:获取数据
POST:提交数据
- 请求的其他信息
# def index(request):
# print(type(request))
# from django.core.handlers.wsgi import WSGIRequest
# print(request.environ)
# for k,v in request.environ.items():
# print(k,v)
# return HttpResponse('ok')
from django.core.handlers.wsgi import WSGIRequest
request.environ
request.environ['HTTP_USER_AGENT']
2、返回值
def func(request):
return HttpResponse('字符串')
return render(request, 'index.html', {''})
retrun redirect('URL')
a = '中国‘
return HttpResponse(bytes(a))
# 支持字符串、字节
3、上传文件
# 上传文件,form标签做特殊设置
obj = request.FILES.get('fafafa')
obj.name
f = open(obj.name, mode='wb')
for item in obj.chunks():
f.write(item)
f.close()
# 文件对象.size
4、FBV & CBV
function base view
url.py
index -> 函数名
view.py
def 函数(request):
...
/index/ -> 函数名
/index/ -> 类
建议:两者都用
# CBV
url(r'^home/', views.Home.as_view()),
# ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
from django.views import View
class Home(View):
def dispatch(self, request, *args, **kwargs):
# 调用父类中的dispatch方法
print('before')
result = super(Home,self).dispatch(request, *args, **kwargs)
print('after')
return result
# dispatch实现拓展
def get(self,request):
print(request.method)
return render(request,'home.html')
def post(self,request):
print(request.method)
return render(request,'home.html')
5、装饰器
见cookie
- 登陆实现:
def login(request):
if request.method =='GET':
# GET 必须大写,否则无法进入
return render(request,'login.html')
elif request.method=='POST':
u = request.POST.get('user')
p = request.POST.get('pwd')
if u=='alex'and p=='123':
return redirect('/index/')
else:
return render(request,'login.html')
else:
# put,delete,head,option..
return redirect('/index/')
<form action="/cmdb/login/"method="POST">
<p><input type="text"name="user"placeholder="用户名"></p>
<p><input type="password"name="pwd"placeholder="密码"></p>
<p><input type="submit"value="提交"></p>
</form>
- 注册实现:
def login(request):
if request.method =='GET':
# GET 必须大写,否则无法进入
return render(request,'login.html')
elif request.method=='POST':
# ------ radio/ select 单选
# v=request.POST.get('gender')
# print(v)
# ------ checkbox/ select 多选
# 报错:erros:A server error cocurred. Please contact the administrator
# 解决:makemigrations migrate
# v=request.POST.getlist('favor')
# print(v)
# ------ 文件
# v= request.POST.get('fafafa')
# print(v)
# 只拿到文件名
obj = request.FILES.get('fafafa')
print(obj,type(obj),obj.name)
# obj.name __str__ --> __repr__
from django.core.files.uploadedfile import InMemoryUploadedFile
# 上传功能实现:
import os
file_path = os.path.join('upload',obj.name)
f = open(file_path,mode='wb')
for i in obj.chunks():
f.write(i)
f.close()
return render(request,'login.html')
else:
# put,delete,head,option..
return redirect('/index/')
<form action="/login/"method="POST" enctype="multipart/form-data">
{# # 上传文件必须设置:enctype="multipart/form-data"#}
{# 没加表示上传字符串、文件名#}
<p><input type="text"name="user"placeholder="用户名"></p>
<p><input type="password"name="pwd"placeholder="密码"></p>
<p>男:<input type="radio" name="gender"value="1">
女:<input type="radio" name="gender"value="2">
中:<input type="radio" name="gender"value="3"></p>
<p>男:<input type="checkbox" name="favor"value="11">
女:<input type="checkbox" name="favor"value="22">
中:<input type="checkbox" name="favor"value="33"></p>
<p><select name="city" multiple>
<option value="sh">上海</option>
<option value="bj">北京</option>
<option value="tj">天津</option></select></p>
<p><input type="file"name="fafafa"></p>
<p><input type="submit"value="提交"></p>
</form>