note

内容回顾:
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

 from django.db import models
# Create your models here.
class UserType(models.Model):
caption = models.CharField(max_length=32)
class UserGroup(models.Model):
name = models.CharField(max_length=32)
class UserInfo(models.Model):
username = models.CharField(max_length=32)
email = models.EmailField()
user_type = models.ForeignKey(to='UserType',to_field='id',on_delete=models.CASCADE)
u2g = models.ManyToManyField(UserGroup)
views

 from django.shortcuts import render,HttpResponse
from app01 import models
from django import forms
from django.forms import fields as Ffields
from django.forms import widgets as Fwidgets
class UserInfoModelForm(forms.ModelForm):
is_rmb = Ffields.CharField(widget=Fwidgets.CheckboxInput())
class Meta:
model = models.UserInfo
fields = '__all__'
# fields = ['username','email']
# exclude = ['username']
labels = {
'username': '用户名',
'email': '邮箱',
}
help_texts = {
'username': '...'
}
widgets = {
'username': Fwidgets.Textarea(attrs={'class': 'c1'})
}
error_messages = {
'__all__':{ },
'email': {
'required': '邮箱不能为空',
'invalid': '邮箱格式错误..',
}
}
field_classes = {
# 'email': Ffields.URLField
}
# localized_fields=('ctime',)
def clean_username(self):
old = self.cleaned_data['username']
return old
class UserInfoForm(forms.Form):
username = Ffields.CharField(max_length=32)
email = Ffields.EmailField()
user_type = Ffields.ChoiceField(
choices=models.UserType.objects.values_list('id','caption')
) def __init__(self, *args, **kwargs):
super(UserInfoForm,self).__init__(*args, **kwargs)
self.fields['user_type'].choices = models.UserType.objects.values_list('id','caption')
def index(request):
if request.method == "GET":
obj = UserInfoModelForm()
return render(request,'index.html',{'obj': obj})
elif request.method == "POST":
obj = UserInfoModelForm(request.POST)
if obj.is_valid():
# obj.save()
instance = obj.save(False)
instance.save()
obj.save_m2m() # print(obj.is_valid())
# print(obj.cleaned_data)
# print(obj.errors.as_json())
return render(request,'index.html',{'obj': obj})
def user_list(request):
li = models.UserInfo.objects.all().select_related('user_type')
return render(request,'user_list.html',{'li': li})
def user_edit(request, nid):
# 获取当前id对象的用户信息
# 显示用户已经存在数据
if request.method == "GET":
user_obj = models.UserInfo.objects.filter(id=nid).first()
mf = UserInfoModelForm(instance=user_obj)
return render(request,'user_edit.html',{'mf': mf, 'nid': nid})
elif request.method == 'POST':
user_obj = models.UserInfo.objects.filter(id=nid).first()
mf = UserInfoModelForm(request.POST,instance=user_obj)
if mf.is_valid():
mf.save()
else:
print(mf.errors.as_json())
return render(request,'user_edit.html',{'mf': mf, 'nid': nid})
def ajax(request):
return render(request, 'ajax.html')
def ajax_json(request):
import time
time.sleep(3)
print(request.POST)
ret = {'code': True , 'data': request.POST.get('username')}
import json
return HttpResponse(json.dumps(ret))
def upload(request):
return render(request,'upload.html')
def upload_file(request):
username = request.POST.get('username')
fafafa = request.FILES.get('fafafa')
import os
img_path = os.path.join('static/imgs/',fafafa.name)
with open(img_path,'wb') as f:
for item in fafafa.chunks():
f.write(item)
ret = {'code': True , 'data': img_path}
import json
return HttpResponse(json.dumps(ret))
def kind(request):
return render(request, 'kind.html')
def upload_img(request):
request.GET.get('dir')
print(request.FILES.get('fafafa'))
# 获取文件保存
import json
dic = {
'error': 0,
'url': '/static/imgs/20130809170025.png',
'message': '错误了...'
}
return HttpResponse(json.dumps(dic))
import os
import time
import json
def file_manager(request):
"""
文件管理
:param request:
:return:
{
moveup_dir_path:
current_dir_path:
current_url:
file_list: [
{
'is_dir': True,
'has_file': True,
'filesize': 0,
'dir_path': '',
'is_photo': False,
'filetype': '',
'filename': xxx.png,
'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path)))
},
{
'is_dir': True,
'has_file': True,
'filesize': 0,
'dir_path': '',
'is_photo': False,
'filetype': '',
'filename': xxx.png,
'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path)))
}
] } """
dic = {}
root_path = 'C:/Users/Administrator/PycharmProjects/day24/static/'
static_root_path = '/static/'
request_path = request.GET.get('path')
if request_path:
abs_current_dir_path = os.path.join(root_path, request_path)
move_up_dir_path = os.path.dirname(request_path.rstrip('/'))
dic['moveup_dir_path'] = move_up_dir_path + '/' if move_up_dir_path else move_up_dir_path
else:
abs_current_dir_path = root_path
dic['moveup_dir_path'] = '' dic['current_dir_path'] = request_path
dic['current_url'] = os.path.join(static_root_path, request_path)
file_list = []
for item in os.listdir(abs_current_dir_path):
abs_item_path = os.path.join(abs_current_dir_path, item)
a, exts = os.path.splitext(item)
is_dir = os.path.isdir(abs_item_path)
if is_dir:
temp = {
'is_dir': True,
'has_file': True,
'filesize': 0,
'dir_path': '',
'is_photo': False,
'filetype': '',
'filename': item,
'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path)))
}
else:
temp = {
'is_dir': False,
'has_file': False,
'filesize': os.stat(abs_item_path).st_size,
'dir_path': '',
'is_photo': True if exts.lower() in ['.jpg', '.png', '.jpeg'] else False,
'filetype': exts.lower().strip('.'),
'filename': item,
'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path)))
}
file_list.append(temp)
dic['file_list'] = file_list
return HttpResponse(json.dumps(dic))
views.bak

 from django.shortcuts import render
from django import forms
from django.forms import fields
from app01 import models
class UserInfoForm(forms.Form):
username = fields.CharField(max_length=32)
email = fields.EmailField()
user_type = fields.ChoiceField(
choices=models.UserType.objects.values_list('id','caption')
)
def __init__(self, *args, **kwargs):
super(UserInfoForm,self).__init__(*args, **kwargs)
self.fields['user_type'].choices = models.UserType.objects.values_list('id','caption')
def index(request):
if request.method == "GET":
obj = UserInfoForm()
return render(request,'index.html',{'obj': obj})
elif request.method == "POST":
obj = UserInfoForm(request.POST)
obj.is_valid()
obj.errors
# models.UserInfo.objects.create(**obj.cleaned_data)
# models.UserInfo.objects.filter(id=1).update(**obj.cleaned_data)
return render(request,'index.html',{'obj': obj})
urls

 from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', views.index),
url(r'^user_list/', views.user_list),
url(r'^edit-(\d+)/', views.user_edit),
url(r'^ajax/$', views.ajax),
url(r'^ajax_json/$', views.ajax_json),
url(r'^upload/$', views.upload),
url(r'^upload_file/$', views.upload_file),
url(r'^kind/$', views.kind),
url(r'^upload_img/$', views.upload_img),
url(r'^file_manager/$', views.file_manager),
]
ajax

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input type="text"/>
<input type="button" value="Ajax1" onclick="Ajax1();" />
<!--
<input type="text" id="url" />
<input type="button" value="发送Iframe请求" onclick="iframeRequest();" />
<iframe id="ifm" src="http://www.baidu.com"></iframe>
-->
<form action="/ajax_json/" method="POST" target="ifm1">
<iframe id="ifm1" name="ifm1" ></iframe>
<input type="text" name="username" />
<input type="text" name="email" />
<input type="submit" onclick="sumitForm();" value="Form提交"/>
</form>
<script type="text/javascript" src="/static/jquery-1.12.4.js"></script>
<script>
function getXHR(){
var xhr = null;
if(XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
}
function Ajax1(){
var xhr = getXHR();
//var xhr = new XMLHttpRequest();
xhr.open('POST', '/ajax_json/',true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
// 接收完毕
var obj = JSON.parse(xhr.responseText);
console.log(obj);
}
};
xhr.setRequestHeader('k1','v1');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');
xhr.send("name=root;pwd=123");
}
/*
function iframeRequest(){
var url = $('#url').val();
$('#ifm').attr('src',url);
}
*/
function sumitForm(){
$('#ifm1').load(function(){
var text = $('#ifm1').contents().find('body').text();
var obj = JSON.parse(text);
})
}
</script>
</body>
</html>
index

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="/index/" method="POST">
{% csrf_token %}
{{ obj.as_p }}
<input type="submit" value="提交" />
</form>
</body>
</html>
kind

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form>
{% csrf_token %}
<div style="width: 500px;margin: 0 auto">
<textarea id="content"></textarea>
</div>
<input type="submit" value="提交"/>
</form>
<script src="/static/jquery-1.12.4.js"></script>
<script src="/static/kindeditor-4.1.10/kindeditor-all.js"></script>
\
<script>
$(function () {
KindEditor.create('#content', {
{# items: ['superscript', 'clearhtml', 'quickformat', 'selectall']#}
{# noDisableItems: ["source", "fullscreen"],#}
{# designMode: false#}
uploadJson: '/upload_img/',
fileManagerJson: '/file_manager/',
allowImageRemote: true,
allowImageUpload: true,
allowFileManager: true,
extraFileUploadParams: {
csrfmiddlewaretoken: "{{ csrf_token }}"
},
filePostName: 'fafafa'
});
})
</script>
</body>
</html>
upload

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
.upload{
display: inline-block;padding: 10px;
background-color: brown;
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
z-index: 90;
}
.file{
width: 100px;height: 50px;opacity: 0;
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
z-index: 100;
}
</style>
</head>
<body>
<div style="position: relative;width: 100px;height: 50px;">
<input class="file" type="file" id="fafafa" name="afafaf" />
<a class="upload">上传</a>
</div>
<input type="button" value="提交XHR" onclick="xhrSubmit();" />
<input type="button" value="提交jQuery" onclick="jqSubmit();" />
<hr/>
<form id="form1" action="/upload_file/" method="POST" enctype="multipart/form-data" target="ifm1">
<iframe id="ifm1" name="ifm1" style="display: none;"></iframe>
<input type="file" name="fafafa" onchange="changeUpalod();" />
{# <input type="submit" onclick="iframeSubmit();" value="Form提交"/>#}
</form>
<div id="preview"></div>
<script src="/static/jquery-1.12.4.js"></script>
<script>
function changeUpalod(){
$('#ifm1').load(function(){
var text = $('#ifm1').contents().find('body').text();
var obj = JSON.parse(text);
$('#preview').empty();
var imgTag = document.createElement('img');
imgTag.src = "/" + obj.data;
$('#preview').append(imgTag);
});
$('#form1').submit();
}
function jqSubmit(){
// $('#fafafa')[0]
var file_obj = document.getElementById('fafafa').files[0];
var fd = new FormData();
fd.append('username','root');
fd.append('fafafa',file_obj);
$.ajax({
url: '/upload_file/',
type: 'POST',
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success:function(arg,a1,a2){
console.log(arg);
console.log(a1);
console.log(a2);
}
})
}
function xhrSubmit(){
// $('#fafafa')[0]
var file_obj = document.getElementById('fafafa').files[0];
var fd = new FormData();
fd.append('username','root');
fd.append('fafafa',file_obj);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload_file/',true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
// 接收完毕
var obj = JSON.parse(xhr.responseText);
console.log(obj);
}
};
xhr.send(fd);
}
function iframeSubmit(){
$('#ifm1').load(function(){
var text = $('#ifm1').contents().find('body').text();
var obj = JSON.parse(text);
$('#preview').empty();
var imgTag = document.createElement('img');
imgTag.src = "/" + obj.data;
$('#preview').append(imgTag);
})
}
</script>
</body>
</html>
user_edit

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form method="POST" action="/edit-{{ nid }}/">
{% csrf_token %}
{{ mf.as_p }}
<input type="submit" value="提交" />
</form>
</body>
</html>
user_list

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<ul>
{% for row in li %}
<li>{{ row.username }} - {{ row.user_type.caption }} - <a href="/edit-{{ row.id }}/">编辑</a></li>
{% endfor %}
</ul>
</body>
</html>

EdmureBlog

python学习笔记_week24的更多相关文章

  1. python学习笔记整理——字典

    python学习笔记整理 数据结构--字典 无序的 {键:值} 对集合 用于查询的方法 len(d) Return the number of items in the dictionary d. 返 ...

  2. VS2013中Python学习笔记[Django Web的第一个网页]

    前言 前面我简单介绍了Python的Hello World.看到有人问我搞搞Python的Web,一时兴起,就来试试看. 第一篇 VS2013中Python学习笔记[环境搭建] 简单介绍Python环 ...

  3. python学习笔记之module && package

    个人总结: import module,module就是文件名,导入那个python文件 import package,package就是一个文件夹,导入的文件夹下有一个__init__.py的文件, ...

  4. python学习笔记(六)文件夹遍历,异常处理

    python学习笔记(六) 文件夹遍历 1.递归遍历 import os allfile = [] def dirList(path): filelist = os.listdir(path) for ...

  5. python学习笔记--Django入门四 管理站点--二

    接上一节  python学习笔记--Django入门四 管理站点 设置字段可选 编辑Book模块在email字段上加上blank=True,指定email字段为可选,代码如下: class Autho ...

  6. python学习笔记--Django入门0 安装dangjo

    经过这几天的折腾,经历了Django的各种报错,翻译的内容虽然不错,但是与实际的版本有差别,会出现各种奇葩的错误.现在终于找到了解决方法:查看英文原版内容:http://djangobook.com/ ...

  7. python学习笔记(一)元组,序列,字典

    python学习笔记(一)元组,序列,字典

  8. Pythoner | 你像从前一样的Python学习笔记

    Pythoner | 你像从前一样的Python学习笔记 Pythoner

  9. OpenCV之Python学习笔记

    OpenCV之Python学习笔记 直都在用Python+OpenCV做一些算法的原型.本来想留下发布一些文章的,可是整理一下就有点无奈了,都是写零散不成系统的小片段.现在看 到一本国外的新书< ...

随机推荐

  1. 17行代码解决微信小程序图片延迟加载

    js 页面 Page({ data: { realScrollTop: 0,//页面滚动距离 driveHeight //屏幕高度可初始化设置 }, scroll(e){ if(e.detail.sc ...

  2. apache配置https协议

    安装openssl有两种方式,第一种直接下载安装包,装上就可运行:第二种可以自己下载源码,自己编译.下面对两种方式均进行详细描述. 一.下载和安装openss 方法一:直接使用openssl安装包 W ...

  3. NP完全性理论与近似算法

    转自:http://www.cnblogs.com/chinazhangjie/archive/2010/12/06/1898070.html 一.图灵机 根据有限状态控制器的当前状态及每个读写头读到 ...

  4. R语言数据挖掘相关包总结-转帖

    与数据挖掘有关或者有帮助的R包和函数的集合. 1.聚类 常用的包: fpc,cluster,pvclust,mclust 基于划分的方法: kmeans, pam, pamk, clara 基于层次的 ...

  5. 阿里云服务器 ECS Linux操作系统加固

    1. 账号和口令 1.1 禁用或删除无用账号 减少系统无用账号,降低安全风险. 操作步骤 使用命令 userdel <用户名> 删除不必要的账号. 使用命令 passwd -l <用 ...

  6. vue-router配合vue-cli的实例

    前面在说到vue-router的时候,都是用最简单的方式说明用法的,但是在实际项目中可能会有所出入,所以,今天就结合vue脚手架来展示项目中的vue-router的用法. 创建项目 首先需要使用脚手架 ...

  7. 服务容错保护断路器Hystrix之二:Hystrix工作流程解析

    一.总运行流程 当你发出请求后,hystrix是这么运行的 红圈 :Hystrix 命令执行失败,执行回退逻辑.也就是大家经常在文章中看到的“服务降级”. 绿圈 :四种情况会触发失败回退逻辑( fal ...

  8. R语言——实验5-聚类分析

    针对课件中的例子自己实现k-means算法 调用R语言自带kmeans()对给定数据集表示的文档进行聚类. 给定数据集: a)         数据代表的是文本信息. b)        第一行代表词 ...

  9. [转][C#]Web.config 相关配置

    设置默认首页 <?xml version="1.0" encoding="UTF-8"?> <configuration> <sy ...

  10. Linux性能优化 第三章 性能工具:系统内存

    3.1内存性能统计信息 3.1.1 内存子系统和性能 和CPU相比,内存的读写速度都大大落后于CPU.为了弥补这个差距,通常CPU会采用高速缓存的机制(高cache). 3.1.2 内存子系统(虚拟存 ...