python学习笔记_week24
内容回顾:
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
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)
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))
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})
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),
]
<!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>
<!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>
<!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>
<!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>
<!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>
<!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的更多相关文章
- python学习笔记整理——字典
python学习笔记整理 数据结构--字典 无序的 {键:值} 对集合 用于查询的方法 len(d) Return the number of items in the dictionary d. 返 ...
- VS2013中Python学习笔记[Django Web的第一个网页]
前言 前面我简单介绍了Python的Hello World.看到有人问我搞搞Python的Web,一时兴起,就来试试看. 第一篇 VS2013中Python学习笔记[环境搭建] 简单介绍Python环 ...
- python学习笔记之module && package
个人总结: import module,module就是文件名,导入那个python文件 import package,package就是一个文件夹,导入的文件夹下有一个__init__.py的文件, ...
- python学习笔记(六)文件夹遍历,异常处理
python学习笔记(六) 文件夹遍历 1.递归遍历 import os allfile = [] def dirList(path): filelist = os.listdir(path) for ...
- python学习笔记--Django入门四 管理站点--二
接上一节 python学习笔记--Django入门四 管理站点 设置字段可选 编辑Book模块在email字段上加上blank=True,指定email字段为可选,代码如下: class Autho ...
- python学习笔记--Django入门0 安装dangjo
经过这几天的折腾,经历了Django的各种报错,翻译的内容虽然不错,但是与实际的版本有差别,会出现各种奇葩的错误.现在终于找到了解决方法:查看英文原版内容:http://djangobook.com/ ...
- python学习笔记(一)元组,序列,字典
python学习笔记(一)元组,序列,字典
- Pythoner | 你像从前一样的Python学习笔记
Pythoner | 你像从前一样的Python学习笔记 Pythoner
- OpenCV之Python学习笔记
OpenCV之Python学习笔记 直都在用Python+OpenCV做一些算法的原型.本来想留下发布一些文章的,可是整理一下就有点无奈了,都是写零散不成系统的小片段.现在看 到一本国外的新书< ...
随机推荐
- 【springboot】之Application配置
# =================================================================== # COMMON SPRING BOOT PROPERTIE ...
- 《剑指offer(第二版)》面试题55——判断是否为平衡二叉树
一.题目大意 输入一颗二叉树,判断该二叉树是否为平衡二叉树(AVL树). 二.题解 <剑指offer>上给出了两种解决方式: 1.第一种是从根节点开始,从上往下遍历每个子节点并计算以子节点 ...
- Qt学习——QListWidget控件的使用
转载:GDUTLYP Qt提供QListWidget类列表框控件用来加载并显示多个列表项.QListWidgetItem类就是列表项类. 一般列表框控件中的列表项有两种加载方式: 一种是由用户手动添加 ...
- Spark 在Hadoop HA下配置HistoryServer问题
我的Spark机群是部署在Yarn上的,因为之前Yarn的部署只是简单的完全分布式,但是后来升级到HA模式,一个主NN,一个备NN,那么Spark HistoryServer的配置也需要相应的做修改, ...
- FB工作流相关
1.初始化项目 gitlab上建立一个仓库 在命令行中运行git clone,将仓库克隆到本地 在命令行中找到前端模版文件(模版文件夹(front-template)有个sao.js脚本,用来在本地按 ...
- C#、AE开发入门之打开CAD文件并显示
加载CAD文件稍显复杂一些,总体还是和前面基本类似 private void button3_Click(object sender, EventArgs e) { axMapControl1.Cle ...
- PAT 乙级 1078 字符串压缩与解压 (20)
文本压缩有很多种方法,这里我们只考虑最简单的一种:把由相同字符组成的一个连续的片段用这个字符和片段中含有这个字符的个数来表示.例如 ccccc 就用 5c 来表示.如果字符没有重复,就原样输出.例如 ...
- [C#][Quartz]帮助类
本文来自:http://www.cnblogs.com/pengze0902/p/6128558.html /// <summary> /// 任务处理帮助类 /// </summa ...
- MySQL架构之keepalived+haproxy+mysql 实现MHA中slave集群负载均衡的高可用(原创)
MySQL的高可用方案一般有如下几种:keepalived+双主,MHA,PXC,MMM,Heartbeat+DRBD等,比较常用的是keepalived+双主,MHA和PXC. HAProxy是一款 ...
- (转)TP-LINK WR720N v3 刷OpenWrt
之前买了一台改过硬件的TP-Link WR841N-V7路由器,并且成功刷机OpenWrt也完成了FQ,WR841N-V7的更多详情可以看这里,但是可能卖家焊接的有问题,导致老是听到滋滋滋高频率的赤耳 ...