note
View Code
内容回顾: Model - 数据库操作 on_delete Query_set select_related 跨表数据一次性拿过来,不增加sql查询次数。帮助跨表,后面参数只能加连表字段 foreign key等 id,name不能加 prefetch_related 第一次操作多次查询 - 验证 clean class A(MOdel): user = email = pwd = Form cls 自定制 - class LoginForm(Form): email = fields.EmailField() user = pwd = - is_valid -> 每一个字段进行正则(字段内置正则)+clean_字段 -> clean(__all__) -> _post_clean - cleand_data - error --------> 推荐 <--------- 一、ModelForm #耦合度高,小程序适用,不适合大程序 参考博客: http://www.cnblogs.com/wupeiqi/articles/6229414.html Model + Form => 验证 + 数据库操作 - class LoginModelForm(xxxxx): 利用model.A中的字段 1. 生成HTML标签:class Meta: ... 2. mf = xxxModelForm(instance=ModelObj) 3. 额外的标签, is_rmb = Ffields.CharField(widget=Fwidgets.CheckboxInput()) 4. 各种验证 is_valid() -> 各种钩子... 5. mf.save() # 或 instance = mf.save(False) instance.save() mf.save_m2m() 二、Ajax 参考博客: http://www.cnblogs.com/wupeiqi/articles/5703697.html 原生 jQuery 伪Ajax操作 时机: 如果发送的是【普通数据】 -> jQuery,XMLHttpRequest,iframe 三、文件上传(预览) - Form提交 - Ajax上传文件 时机: 如果发送的是【文件】 -> iframe,jQuery(FormData),XMLHttpRequest(FormData), 四、图片验证码 + Session - session - check_code.py(依赖:Pillow,字体文件) - src属性后面加? 五、CKEditor,UEEditor,TinyEditor,KindEditor(***) 参考博客: http://www.cnblogs.com/wupeiqi/articles/6307554.html - 基本使用 - 文件上传,多文件上传,文件空间管理 - XSS攻击(过滤的函数或类) 下节课说... 作业(): 主站: http://127.0.0.1:8000/ 博客首页 http://127.0.0.1:8000/zhaofan/1.html 某人的某篇博客 个人博客: http://127.0.0.1:8000/zhaofan.html 某人的博客 http://127.0.0.1:8000/zhaofan/tag/python.html 某人的博客筛选 http://127.0.0.1:8000/zhaofan/catetory/mvc.html 某人的博客筛选 http://127.0.0.1:8000/zhaofan/date/2011-11.html 某人的博客筛选 个人后台管理: http://127.0.0.1:8000/backend/base-info.html http://127.0.0.1:8000/backend/tag.html http://127.0.0.1:8000/backend/category.html http://127.0.0.1:8000/backend/article.html http://127.0.0.1:8000/backend/add-article.html
models
View Code
1 from django.db import models 2 # Create your models here. 3 class UserType(models.Model): 4 caption = models.CharField(max_length=32) 5 class UserGroup(models.Model): 6 name = models.CharField(max_length=32) 7 class UserInfo(models.Model): 8 username = models.CharField(max_length=32) 9 email = models.EmailField() 10 user_type = models.ForeignKey(to='UserType',to_field='id',on_delete=models.CASCADE) 11 u2g = models.ManyToManyField(UserGroup)
views
View Code
1 from django.shortcuts import render,HttpResponse 2 from app01 import models 3 from django import forms 4 from django.forms import fields as Ffields 5 from django.forms import widgets as Fwidgets 6 class UserInfoModelForm(forms.ModelForm): 7 is_rmb = Ffields.CharField(widget=Fwidgets.CheckboxInput()) 8 class Meta: 9 model = models.UserInfo 10 fields = '__all__' 11 # fields = ['username','email'] 12 # exclude = ['username'] 13 labels = { 14 'username': '用户名', 15 'email': '邮箱', 16 } 17 help_texts = { 18 'username': '...' 19 } 20 widgets = { 21 'username': Fwidgets.Textarea(attrs={'class': 'c1'}) 22 } 23 error_messages = { 24 '__all__':{ 25 26 }, 27 'email': { 28 'required': '邮箱不能为空', 29 'invalid': '邮箱格式错误..', 30 } 31 } 32 field_classes = { 33 # 'email': Ffields.URLField 34 } 35 # localized_fields=('ctime',) 36 def clean_username(self): 37 old = self.cleaned_data['username'] 38 return old 39 class UserInfoForm(forms.Form): 40 username = Ffields.CharField(max_length=32) 41 email = Ffields.EmailField() 42 user_type = Ffields.ChoiceField( 43 choices=models.UserType.objects.values_list('id','caption') 44 ) 45 46 def __init__(self, *args, **kwargs): 47 super(UserInfoForm,self).__init__(*args, **kwargs) 48 self.fields['user_type'].choices = models.UserType.objects.values_list('id','caption') 49 def index(request): 50 if request.method == "GET": 51 obj = UserInfoModelForm() 52 return render(request,'index.html',{'obj': obj}) 53 elif request.method == "POST": 54 obj = UserInfoModelForm(request.POST) 55 if obj.is_valid(): 56 # obj.save() 57 instance = obj.save(False) 58 instance.save() 59 obj.save_m2m() 60 61 62 # print(obj.is_valid()) 63 # print(obj.cleaned_data) 64 # print(obj.errors.as_json()) 65 return render(request,'index.html',{'obj': obj}) 66 def user_list(request): 67 li = models.UserInfo.objects.all().select_related('user_type') 68 return render(request,'user_list.html',{'li': li}) 69 def user_edit(request, nid): 70 # 获取当前id对象的用户信息 71 # 显示用户已经存在数据 72 if request.method == "GET": 73 user_obj = models.UserInfo.objects.filter(id=nid).first() 74 mf = UserInfoModelForm(instance=user_obj) 75 return render(request,'user_edit.html',{'mf': mf, 'nid': nid}) 76 elif request.method == 'POST': 77 user_obj = models.UserInfo.objects.filter(id=nid).first() 78 mf = UserInfoModelForm(request.POST,instance=user_obj) 79 if mf.is_valid(): 80 mf.save() 81 else: 82 print(mf.errors.as_json()) 83 return render(request,'user_edit.html',{'mf': mf, 'nid': nid}) 84 def ajax(request): 85 return render(request, 'ajax.html') 86 def ajax_json(request): 87 import time 88 time.sleep(3) 89 print(request.POST) 90 ret = {'code': True , 'data': request.POST.get('username')} 91 import json 92 return HttpResponse(json.dumps(ret)) 93 def upload(request): 94 return render(request,'upload.html') 95 def upload_file(request): 96 username = request.POST.get('username') 97 fafafa = request.FILES.get('fafafa') 98 import os 99 img_path = os.path.join('static/imgs/',fafafa.name) 100 with open(img_path,'wb') as f: 101 for item in fafafa.chunks(): 102 f.write(item) 103 ret = {'code': True , 'data': img_path} 104 import json 105 return HttpResponse(json.dumps(ret)) 106 def kind(request): 107 return render(request, 'kind.html') 108 def upload_img(request): 109 request.GET.get('dir') 110 print(request.FILES.get('fafafa')) 111 # 获取文件保存 112 import json 113 dic = { 114 'error': 0, 115 'url': '/static/imgs/20130809170025.png', 116 'message': '错误了...' 117 } 118 return HttpResponse(json.dumps(dic)) 119 import os 120 import time 121 import json 122 def file_manager(request): 123 """ 124 文件管理 125 :param request: 126 :return: 127 { 128 moveup_dir_path: 129 current_dir_path: 130 current_url: 131 file_list: [ 132 { 133 'is_dir': True, 134 'has_file': True, 135 'filesize': 0, 136 'dir_path': '', 137 'is_photo': False, 138 'filetype': '', 139 'filename': xxx.png, 140 'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path))) 141 }, 142 { 143 'is_dir': True, 144 'has_file': True, 145 'filesize': 0, 146 'dir_path': '', 147 'is_photo': False, 148 'filetype': '', 149 'filename': xxx.png, 150 'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path))) 151 } 152 ] 153 154 } 155 156 157 """ 158 dic = {} 159 root_path = 'C:/Users/Administrator/PycharmProjects/day24/static/' 160 static_root_path = '/static/' 161 request_path = request.GET.get('path') 162 if request_path: 163 abs_current_dir_path = os.path.join(root_path, request_path) 164 move_up_dir_path = os.path.dirname(request_path.rstrip('/')) 165 dic['moveup_dir_path'] = move_up_dir_path + '/' if move_up_dir_path else move_up_dir_path 166 else: 167 abs_current_dir_path = root_path 168 dic['moveup_dir_path'] = '' 169 170 dic['current_dir_path'] = request_path 171 dic['current_url'] = os.path.join(static_root_path, request_path) 172 file_list = [] 173 for item in os.listdir(abs_current_dir_path): 174 abs_item_path = os.path.join(abs_current_dir_path, item) 175 a, exts = os.path.splitext(item) 176 is_dir = os.path.isdir(abs_item_path) 177 if is_dir: 178 temp = { 179 'is_dir': True, 180 'has_file': True, 181 'filesize': 0, 182 'dir_path': '', 183 'is_photo': False, 184 'filetype': '', 185 'filename': item, 186 'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path))) 187 } 188 else: 189 temp = { 190 'is_dir': False, 191 'has_file': False, 192 'filesize': os.stat(abs_item_path).st_size, 193 'dir_path': '', 194 'is_photo': True if exts.lower() in ['.jpg', '.png', '.jpeg'] else False, 195 'filetype': exts.lower().strip('.'), 196 'filename': item, 197 'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path))) 198 } 199 file_list.append(temp) 200 dic['file_list'] = file_list 201 return HttpResponse(json.dumps(dic))
views.bak
View Code
1 from django.shortcuts import render 2 from django import forms 3 from django.forms import fields 4 from app01 import models 5 class UserInfoForm(forms.Form): 6 username = fields.CharField(max_length=32) 7 email = fields.EmailField() 8 user_type = fields.ChoiceField( 9 choices=models.UserType.objects.values_list('id','caption') 10 ) 11 def __init__(self, *args, **kwargs): 12 super(UserInfoForm,self).__init__(*args, **kwargs) 13 self.fields['user_type'].choices = models.UserType.objects.values_list('id','caption') 14 def index(request): 15 if request.method == "GET": 16 obj = UserInfoForm() 17 return render(request,'index.html',{'obj': obj}) 18 elif request.method == "POST": 19 obj = UserInfoForm(request.POST) 20 obj.is_valid() 21 obj.errors 22 # models.UserInfo.objects.create(**obj.cleaned_data) 23 # models.UserInfo.objects.filter(id=1).update(**obj.cleaned_data) 24 return render(request,'index.html',{'obj': obj})
urls
View Code
1 from django.conf.urls import url 2 from django.contrib import admin 3 from app01 import views 4 urlpatterns = [ 5 url(r'^admin/', admin.site.urls), 6 url(r'^index/', views.index), 7 url(r'^user_list/', views.user_list), 8 url(r'^edit-(\d+)/', views.user_edit), 9 url(r'^ajax/$', views.ajax), 10 url(r'^ajax_json/$', views.ajax_json), 11 url(r'^upload/$', views.upload), 12 url(r'^upload_file/$', views.upload_file), 13 url(r'^kind/$', views.kind), 14 url(r'^upload_img/$', views.upload_img), 15 url(r'^file_manager/$', views.file_manager), 16 ]
ajax
View Code
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <input type="text"/> 9 <input type="button" value="Ajax1" onclick="Ajax1();" /> 10 <!-- 11 <input type="text" id="url" /> 12 <input type="button" value="发送Iframe请求" οnclick="iframeRequest();" /> 13 <iframe id="ifm" src="http://www.baidu.com"></iframe> 14 --> 15 <form action="/ajax_json/" method="POST" target="ifm1"> 16 <iframe id="ifm1" name="ifm1" ></iframe> 17 <input type="text" name="username" /> 18 <input type="text" name="email" /> 19 <input type="submit" onclick="sumitForm();" value="Form提交"/> 20 </form> 21 <script type="text/javascript" src="/static/jquery-1.12.4.js"></script> 22 <script> 23 function getXHR(){ 24 var xhr = null; 25 if(XMLHttpRequest){ 26 xhr = new XMLHttpRequest(); 27 }else{ 28 xhr = new ActiveXObject("Microsoft.XMLHTTP"); 29 } 30 return xhr; 31 } 32 function Ajax1(){ 33 var xhr = getXHR(); 34 //var xhr = new XMLHttpRequest(); 35 xhr.open('POST', '/ajax_json/',true); 36 xhr.onreadystatechange = function(){ 37 if(xhr.readyState == 4){ 38 // 接收完毕 39 var obj = JSON.parse(xhr.responseText); 40 console.log(obj); 41 } 42 }; 43 xhr.setRequestHeader('k1','v1'); 44 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8'); 45 xhr.send("name=root;pwd=123"); 46 } 47 /* 48 function iframeRequest(){ 49 var url = $('#url').val(); 50 $('#ifm').attr('src',url); 51 } 52 */ 53 function sumitForm(){ 54 $('#ifm1').load(function(){ 55 var text = $('#ifm1').contents().find('body').text(); 56 var obj = JSON.parse(text); 57 }) 58 } 59 </script> 60 </body> 61 </html>
index
View Code
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <form action="/index/" method="POST"> 9 {% csrf_token %} 10 {{ obj.as_p }} 11 <input type="submit" value="提交" /> 12 </form> 13 </body> 14 </html>
kind
View Code
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <form> 9 {% csrf_token %} 10 <div style="width: 500px;margin: 0 auto"> 11 <textarea id="content"></textarea> 12 </div> 13 <input type="submit" value="提交"/> 14 </form> 15 <script src="/static/jquery-1.12.4.js"></script> 16 <script src="/static/kindeditor-4.1.10/kindeditor-all.js"></script> 17 \ 18 <script> 19 $(function () { 20 KindEditor.create('#content', { 21 {# items: ['superscript', 'clearhtml', 'quickformat', 'selectall']#} 22 {# noDisableItems: ["source", "fullscreen"],#} 23 {# designMode: false#} 24 uploadJson: '/upload_img/', 25 fileManagerJson: '/file_manager/', 26 allowImageRemote: true, 27 allowImageUpload: true, 28 allowFileManager: true, 29 extraFileUploadParams: { 30 csrfmiddlewaretoken: "{{ csrf_token }}" 31 }, 32 filePostName: 'fafafa' 33 }); 34 }) 35 </script> 36 </body> 37 </html>
upload
View Code
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 <style> 7 .upload{ 8 display: inline-block;padding: 10px; 9 background-color: brown; 10 position: absolute; 11 top: 0; 12 bottom: 0; 13 right: 0; 14 left: 0; 15 z-index: 90; 16 } 17 .file{ 18 width: 100px;height: 50px;opacity: 0; 19 position: absolute; 20 top: 0; 21 bottom: 0; 22 right: 0; 23 left: 0; 24 z-index: 100; 25 } 26 </style> 27 </head> 28 <body> 29 <div style="position: relative;width: 100px;height: 50px;"> 30 <input class="file" type="file" id="fafafa" name="afafaf" /> 31 <a class="upload">上传</a> 32 </div> 33 <input type="button" value="提交XHR" onclick="xhrSubmit();" /> 34 <input type="button" value="提交jQuery" onclick="jqSubmit();" /> 35 <hr/> 36 <form id="form1" action="/upload_file/" method="POST" enctype="multipart/form-data" target="ifm1"> 37 <iframe id="ifm1" name="ifm1" style="display: none;"></iframe> 38 <input type="file" name="fafafa" onchange="changeUpalod();" /> 39 {# <input type="submit" onclick="iframeSubmit();" value="Form提交"/>#} 40 </form> 41 <div id="preview"></div> 42 <script src="/static/jquery-1.12.4.js"></script> 43 <script> 44 function changeUpalod(){ 45 $('#ifm1').load(function(){ 46 var text = $('#ifm1').contents().find('body').text(); 47 var obj = JSON.parse(text); 48 $('#preview').empty(); 49 var imgTag = document.createElement('img'); 50 imgTag.src = "/" + obj.data; 51 $('#preview').append(imgTag); 52 }); 53 $('#form1').submit(); 54 } 55 function jqSubmit(){ 56 // $('#fafafa')[0] 57 var file_obj = document.getElementById('fafafa').files[0]; 58 var fd = new FormData(); 59 fd.append('username','root'); 60 fd.append('fafafa',file_obj); 61 $.ajax({ 62 url: '/upload_file/', 63 type: 'POST', 64 data: fd, 65 processData: false, // tell jQuery not to process the data 66 contentType: false, // tell jQuery not to set contentType 67 success:function(arg,a1,a2){ 68 console.log(arg); 69 console.log(a1); 70 console.log(a2); 71 } 72 }) 73 } 74 function xhrSubmit(){ 75 // $('#fafafa')[0] 76 var file_obj = document.getElementById('fafafa').files[0]; 77 var fd = new FormData(); 78 fd.append('username','root'); 79 fd.append('fafafa',file_obj); 80 var xhr = new XMLHttpRequest(); 81 xhr.open('POST', '/upload_file/',true); 82 xhr.onreadystatechange = function(){ 83 if(xhr.readyState == 4){ 84 // 接收完毕 85 var obj = JSON.parse(xhr.responseText); 86 console.log(obj); 87 } 88 }; 89 xhr.send(fd); 90 } 91 function iframeSubmit(){ 92 $('#ifm1').load(function(){ 93 var text = $('#ifm1').contents().find('body').text(); 94 var obj = JSON.parse(text); 95 $('#preview').empty(); 96 var imgTag = document.createElement('img'); 97 imgTag.src = "/" + obj.data; 98 $('#preview').append(imgTag); 99 }) 100 } 101 </script> 102 </body> 103 </html>
user_edit
View Code
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <form method="POST" action="/edit-{{ nid }}/"> 9 {% csrf_token %} 10 {{ mf.as_p }} 11 <input type="submit" value="提交" /> 12 </form> 13 </body> 14 </html>
user_list
View Code
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <ul> 9 {% for row in li %} 10 <li>{{ row.username }} - {{ row.user_type.caption }} - <a href="/edit-{{ row.id }}/">编辑</a></li> 11 {% endfor %} 12 </ul> 13 </body> 14 </html>
EdmureBlog