django1與2路由的差異
在django1中的url在django2中爲re_path django2中新增了path 1.from django.urls import path 2.不支持正則,精準匹配 3.有5個轉換器(int,str,slug,path,uuid) 4.自定義轉換器: 1 寫一個類: class Test: regex = '[0-9]{4}' def to_python(self, value):
MVC和MTV
M T V
models template views M V C(路由+views) models 模板 控制器 其實MVC與MTV是同樣的,django中爲MTV,數據交互層,視圖層以及控制層
視圖層:request對象
request對象: # form表單,不寫method ,默認是get請求 # 1 什麼狀況下用get:請求數據,請求頁面, # 2 用post請求:向服務器提交數據 # request.GET 字典 # request.POST 字典 # 請求的類型 # print(request.method) # 路徑 # http://127.0.0.1:8000/index/ppp/dddd/?name=lqz # 協議:ip地址和端口/路徑?參數(數據) # print(request.path) -->/index/ppp/dddd/ # print(request.get_full_path()) -->/index/ppp/dddd/?name=lqz
三件套
render HttpResponse redirect
JsonResponse
向前端頁面發json格式字符串
封裝了json from django.http import JsonResponse dic={'name':'lqz','age':18} li=[1,2,3,4] return JsonResponse(li,safe=False)
CBV和FBV
CBV(class base view)和FBV(function base view) cbv: from django.views import View class Test(View): def dispatch(self, request, *args, **kwargs):
簡單文件上傳
html中: <form action="" method="post" enctype="multipart/form-data"> 用戶名:<input type="text" name="name"> 密碼:<input type="text" name="password"> 文件:<input type="file" name="myfile"> <input type="submit"> </form> views中 class Cbv(View): def dispatch(self, request, *args, **kwargs): obj = super().dispatch(request, *args, **kwargs) return obj def get(self,request): return render(request,'index.html') def post(self,request): aaa = request.FILES.get('myfile') with open(aaa.name,'wb') as f: for line in aaa.chunks(): f.write(line) return HttpResponse('ok')