django
django的 CBV
定制dispatch,定制响应头,定制cookie
1 from django.shortcuts import render,HttpResponse 2 from django.views import View 3 # Create your views here. 4 class Myindex(View): 5 #定制dispatch 6 def dispatch(self, request, *args, **kwargs): 7 result=super(Myindex,self).dispatch(request,*args,**kwargs) 8 return result 9 def get(self,request): 10 return render(request,'index.html') 11 def post(self,request): 12 #定制响应头 13 ret=HttpResponse('saoka') 14 ret['h1']='v1' 15 ret['h2']='v3' 16 #设置cookie 17 ret.set_cookie('c1','v2') 18 ret.set_cookie('c2','v3') 19 return ret
django的 静态文件路径的设置STATICFILES_DIRS=[
os.path.join(BASE_DIR,'static')
]
Django 2.0的
创建app
1 python manage.py startapp app01
2 在settings.py中的设置
1 INSTALLED_APPS = [ 2 'app02.apps.App02Config', 3 'app01.apps.App01Config', 4 'django.contrib.admin', 5 'django.contrib.auth', 6 'django.contrib.contenttypes', 7 'django.contrib.sessions', 8 'django.contrib.messages', 9 'django.contrib.staticfiles', 10 #'app01.apps.AppConfig', 11 ]
3 创建model相关的数据库表结构
4 python manage.py migrate
5 python manage.py makemigrations app01
6 url.py 的路由的写法
1 from django.contrib import admin 2 from django.urls import path 3 from app01.views import classes,students,teachers 4 urlpatterns = [ 5 path('admin/', admin.site.urls), 6 path(r'index/',classes.Myclasses.as_view()), 7 path('add_classes/',classes.AddClasses.as_view()), 8 path('del_classes-<int:class_id>/',classes.DelClasses.as_view()), 9 path('edit_classes-<int:class_id>/',classes.EditClasses.as_view()), 10 path('student/',students.Students.as_view()), 11 path('stu_add/',students.StuAdd.as_view()), 12 path('stu_edit-<int:stu_id>/',students.StuEdit.as_view()), 13 ]
ajax 原生的js 实现ajax的方法
1 <script> 2 var the_a=document.getElementById('a1'); 3 the_a.onclick=function (ev) { 4 var myx= new XMLHttpRequest(); 5 myx.onreadystatechange=function () { 6 if (myx.readyState==4){ 7 console.log(myx.responseText); 8 } 9 } 10 myx.open('get','/myaa/myajax/?name=sakula'); 11 myx.send(null); 12 13 } 14 </script>
ajax 原生的js 实现ajax的post方法
1 <script> 2 var the_a=document.getElementById('a1'); 3 the_a.onclick=function (ev) { 4 var myx= new XMLHttpRequest(); 5 myx.onreadystatechange=function () { 6 if (myx.readyState==4){ 7 console.log(myx.responseText); 8 } 9 } 10 //myx.open('get','/myaa/myajax/?name=sakula'); 11 myx.open('post','/myaa/myajax/?name=sakula'); 12 //设置请求头,这样django才能解析 13 myx.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8') 14 myx.send('p=sakula'); 15 16 } 17 </script>
伪ajax form表单 提交 和iframe的不刷新页面的功能 实现 ajax的提交数据不刷新页面的效果
1 <div> 2 <iframe name="myi"></iframe> 3 </div> 4 <div> 5 <h4>iframe的方式 伪ajax的方式提交数据不刷新页面</h4> 6 <form action="/myaa/myajax/" method="post" target="myi"> 7 <input type="text" value="1111" name="usernname"> 8 <input type="submit" value="提交"> 9 </form> 10 </div>
伪ajax form 表单提交 和回调函数的实现提取数据 这种方式对平台的兼容性很好
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style> 7 .b_a{ 8 display: inline-block; 9 background-color: antiquewhite; 10 padding: 5px 10px; 11 color: white; 12 } 13 </style> 14 </head> 15 <body> 16 <div> 17 <h4>莆田提交</h4> 18 <div> 19 <a id='a1' class="b_a">伪ajax提交</a> 20 </div> 21 <iframe id='if'name="iii"></iframe> 22 <form id='fm' action="/myaa/mytest/" method="post" target="iii"> 23 <input type="text" value="1111"> 24 </form> 25 </div> 26 <script> 27 document.getElementById('a1').onclick=wajax_click; 28 function wajax_click() { 29 //注册onload事件 30 document.getElementById('if').onload=ifrealod; 31 //form的表单提交 32 document.getElementById('fm').submit(); 33 } 34 function ifrealod() { 35 //获取回调的显示在iframe中内容 36 var content=this.contentWindow.document.body.innerText; 37 var myresponse=JSON.parse(content); 38 //类似于回调函数 39 if(myresponse.status){ 40 alert('......'); 41 } 42 } 43 </script> 44 </body> 45 </html>
ajax js 与ajax jquey 上传文件
1 ajax js form data 对象的打包数据的方式上传文件
1 function ajax_js() { 2 var mydata=new FormData(); 3 var myx=new XMLHttpRequest(); 4 var myfile=document.getElementById('img').files[0] 5 mydata.append('k1','v1'); 6 mydata.append('k2','v2'); 7 mydata.append('aa',myfile); 8 var myx= new XMLHttpRequest(); 9 myx.onreadystatechange=function () { 10 if (myx.readyState==4){ 11 console.log(myx.responseText); 12 } 13 } 14 //myx.open('get','/myaa/myajax/?name=sakula'); 15 myx.open('post','/myaa/mytest/'); 16 //设置请求头,这样django才能解析 17 // myx.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8') 18 myx.send(mydata); 19 }
2 ajax jquery form data 对象的打包数据的方式上传文件
1 function ajax_jquery() { 2 var mydata=new FormData(); 3 var myfile=document.getElementById('img').files[0] 4 mydata.append('k1','v1'); 5 mydata.append('k3','v3'); 6 mydata.append('aa',myfile); 7 $.ajax({ 8 url:'/myaa/mytest/', 9 type:'post', 10 data:mydata, 11 success:function (arg) { 12 console.log(arg); 13 }, 14 processData: false, // tell jQuery not to process the data 15 contentType: false // tell jQuery not to set contentType 16 }); 17 }
iframe + form表单的方式 上传文件
1 <div> 2 <h4>iframe + form 上传文件</h4> 3 <iframe id="if2" name="iiff"></iframe> 4 <div><a id="a4">提交</a></div> 5 <form id='ff' action="/myaa/mytest/" method="post" target="iiff" enctype="multipart/form-data"> 6 <input type="text" name="username" placeholder="username"> 7 <input type="text" name="password" placeholder="password"> 8 <input type="file" name="uimg"> 9 </form> 10 </div> 11 12 13 <script> 14 document.getElementById('a4').onclick=fii; 15 function fii() { 16 document.getElementById('if2').onload=if2on; 17 document.getElementById('ff').submit(); 18 } 19 function if2on() { 20 var content=this.contentWindow.document.body.innerText; 21 console.log(content); 22 } 23 </script>
iframe + form表达方式 实现 上传图片+图片预览的功能
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>图像上传预览</title> 6 </head> 7 <body> 8 <div> 9 <iframe style="display: none" id="if" name="iiff"></iframe> 10 <form id="fm" action="/myaa/upload/" method="post" target="iiff" enctype="multipart/form-data"> 11 <input id="ii" name="im" type="file"> 12 </form> 13 </div> 14 <div><h4>图像预览</h4></div> 15 <div id="yl"> 16 17 </div> 18 <script> 19 document.getElementById('ii').onchange=asubmit; 20 function asubmit() { 21 document.getElementById('if').onload=fsubmit; 22 document.getElementById('fm').submit(); 23 } 24 function fsubmit() { 25 var content=this.contentWindow.document.body.innerText; 26 var content_dict=JSON.parse(content); 27 if(content_dict.status){ 28 //console.log(content_dict.data); 29 var up_img=document.createElement('img') 30 //up_img.attr('src',content_dict.data) 31 up_img.src="/"+content_dict.data 32 document.getElementById('yl').appendChild(up_img) 33 } 34 } 35 </script> 36 </body> 37 </html>
1 class Upp(View): 2 def get(self,request): 3 return render(request,'user/upload.html') 4 def post(self,request): 5 myf=request.FILES.get('im') 6 import os 7 file_name=str(uuid.uuid4())+myf.name 8 file_path=os.path.join('static/upload',file_name) 9 with open(file_path,'wb') as ff: 10 for line in myf.chunks(): 11 ff.write(line) 12 response_dict={'status':True,'error':None,'data':file_path} 13 return HttpResponse(json.dumps(response_dict))
Jsonp 跨域 ajax
1浏览器的同源策略
2XMLHttpRequest对象遵循这同源策略
3 利用 img,script, 等标签的src属性 可以访问外部的地址,不遵循这同源策略 实现
4 jsonp返回的数据 包裹在函数中
5在本地实现这函数,通过参数 来获取 jsonp返回的数据
6 请求的方式为get
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>MyJspon 练习</title> 6 </head> 7 <body> 8 <div> 9 <a id="a1" style="display: inline-block;padding: 5px 10px; background-color: bisque;color: white">点我测试</a> 10 </div> 11 <script> 12 //触发jsonp 13 document.getElementById('a1').onclick=a1_click; 14 function a1_click() { 15 var tag=document.createElement('script'); 16 tag.src="http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403"; 17 document.head.appendChild(tag); 18 document.head.removeChild(tag); 19 } 20 function list(arg) { 21 console.log(arg); 22 } 23 </script> 24 </body> 25 </html>
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>jsonp 的jquery ajax的方式实现</title> 6 </head> 7 <body> 8 <div> 9 <a id="a1">点我试试</a> 10 </div> 11 <script src="/static/js/jquery-3.1.1.js"></script> 12 <script> 13 $('#a1').click(mybb); 14 function mybb() { 15 $.ajax({ 16 url:'http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403', 17 type:'get', 18 dataType:'jsonp', 19 }); 20 } 21 function list(arg) { 22 console.log(arg); 23 } 24 </script> 25 </body> 26 </html>
1 function submitJsonp4() { 2 $.ajax({ 3 url: 'http://127.0.0.1:9000/xiaokai.html', 4 type: 'POST', 5 dataType: 'jsonp', 6 jsonp: 'callback', 7 jsonpCallback: 'func' 8 }) 9 } 10 function func(arg) { 11 console.log(arg); 12 }
1 #用请求端自己的callback函数包裹响应数据 2 func_name=request.Get.get('callback') 3 return HttpResponse("%s('the_return_data')"%(func_name))
CORS
现在的浏览器可以支持主动设置从而允许跨域请求,即:跨域资源共享(CORS,Cross-Origin Resource Sharing),其本质是设置响应头,使得浏览器允许跨域请求。
1 可以不仅仅为get的方式请求数据
2返回数据时候,主动设置响应头
Access
-
Control
-
Request
-
Headers="*"
form表单
1 from django.forms import Form 2 from django.forms import fields,ValidationError 3 from django.forms import widgets 4 class UserInfoAdmin(Form): 5 name=fields.CharField( 6 required=True,#是否可以为空 7 max_length=32,#最大长度 8 min_length=2,#最小长度 9 error_messages={ 10 'required':'aa', 11 },#错误提示 12 widget=widgets.TextInput(attrs={'class':'form-control','placeholder':'name'}) 13 ) 14 15 password=fields.CharField( 16 widget=widgets.TextInput(attrs={'class': 'form-control', 'placeholder': 'password'}) 17 ) 18 email=fields.EmailField( 19 widget=widgets.TextInput(attrs={'class':'form-control','placeholder':'Email'}) 20 ) 21 nic_img=fields.ImageField( 22 23 ) 24 def __init__(self,*args,**kwargs): 25 super(UserInfoAdmin,self).__init__(*args,**kwargs) 26 self.fields['nic_img'].widget.attrs['class']='upi'
form表单的choices可以从数据库中获取值,但由于是静态字段,不能够实时更新,我们可以自定义构造函数 实现 choices字段的实时更新
1 from django.forms import Form 2 from django.forms import widgets 3 from django.forms import fields 4 5 class MyForm(Form): 6 7 user = fields.ChoiceField( 8 # choices=((1, '上海'), (2, '北京'),), 9 initial=2, 10 widget=widgets.Select 11 ) 12 13 def __init__(self, *args, **kwargs): 14 super(MyForm,self).__init__(*args, **kwargs) 15 # self.fields['user'].widget.choices = ((1, '上海'), (2, '北京'),) 16 # 或 17 self.fields['user'].widget.choices = models.Classes.objects.all().value_list('id','caption')