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中:
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')