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. 用DLL实现插件的简单演示

    这是DLL的代码 library MyDll; uses SysUtils, Dialogs, Classes; procedure ShowInfo(info:PChar);stdcall; beg ...

  2. 无法连接到 OPC服务器[无此类接口支持(异常来自HRESULT:0x80004002(E_NOINTERFACE))]

    来源:https://stackoverrun.com/cn/q/10400663 无法连接到ABB Freelance OPC服务器[无此类接口支持(异常来自HRESULT:0x80004002(E ...

  3. windows defender和windows firewall

    Windows defender: Windows Defender,曾用名Microsoft Anti Spyware,是一个杀毒程序,可以运行在Windows XP和Windows Server ...

  4. Azure ARM (18) 将Azure RM Manage Disk托管磁盘的Image,跨订阅迁移

    <Windows Azure Platform 系列文章目录> 先挖一个坑,以后再埋. 最近遇到一个客户需求,客户使用了Azure RM Manage Disk托管磁盘,然后捕获镜像做成了 ...

  5. sqlserver触发器执行顺序【未经验证】

    exec sp_settriggerorder @triggername = 'tr_customer_1', @order = 'first', @stmttype = 'insert',@name ...

  6. wxPython 入门开发示例

    1.背景资料 wxPython API:https://www.wxpython.org/Phoenix/docs/html/ 2.入门示例 wxPython最重要的两个概念:App与Frame,其中 ...

  7. QT中webkit去掉默认的右键菜单

    在qt设计师中,选择webview,按下图选择那一行设置contextMenuPolicy属性:

  8. socket.io入门整理教程

    socket.io入门整理  发布于 5 年前  作者 dtrex  124983 次浏览  最后一次编辑是 1 年前 我自己在用socket.io开发,对官方网站上的文档,进行简单的整理,然后自己写 ...

  9. LINUX 内存使用情况

    # free 显示结果如下: Mem:表示物理内存统计 total 内存总数 8057964KBused 已使用的内存 7852484KBfree 空闲的内存数 205480KBshared 当前已经 ...

  10. sqlserver 查询表中的主键、外键列及外键表,外表中的主键列

    1.获取主键信息 EXEC sp_pkeys @table_name='{0}' 2.获取外键 方法二 SELECT Field=(SELECT name FROM syscolumns WHERE ...