python版本 3.+
Django version 1.0.1
一、Django基础
Django笔记:
1、Django请求生命周期
-> URL对应关系(匹配) -> 视图函数 -> 返回用户字符串
-> URL对应关系(匹配) -> 视图函数 -> 打开一个HTML文件,读取内容
2、创建django projcet
django-admin startproject mysite
..
mysite
mysite
- 配置文件
- url.py
- settings.py
cd mysite
python manage.py startapp cmdb
mysite
mysite
- 配置文件
- url.py
- settings.py
cmdb
- views.py
- admin.py
- models.py # 创建数据库表
3、配置
模板路径
静态文件路径
# CSRF
4、编写程序
a. url.py
/index/ -> func
b. views.py
def func(request):
# 包含所有的请求数据
...
return HttpResponse('字符串')
return render(request, 'index.html', {''})
retrun redirect('URL')
c. 模板语言
return render(request, 'index.html', {'li': [11,22,33]})
{% for item in li %}
<h1>{{item}}</h1>
{% endfor %}
*********** 索引用点 **********
<h2> {{item.0 }} </h2>
一、路由系统,URL
1、url(r'^index/', views.index),
url(r'^home/', views.Home.as_view()),
2、url(r'^detail-(\d+).html', views.detail),
3、url(r'^detail-(?P<nid>\d+)-(?P<uid>\d+).html', views.detail)
PS:
def detail(request, *args,**kwargs):
pass
实战:
a.
url(r'^detail-(\d+)-(\d+).html', views.detail),
def func(request, nid, uid):
pass
def func(request, *args):
args = (2,9)
def func(request, *args, **kwargs):
args = (2,9)
b.
url(r'^detail-(?P<nid>\d+)-(?P<uid>\d+).html', views.detail)
def func(request, nid, uid):
pass
def funct(request, **kwargs):
kwargs = {'nid': 1, 'uid': 3}
def func(request, *args, **kwargs):
args = (2,9)
4、 name
对URL路由关系进行命名, ***** 以后可以根据此名称生成自己想要的URL *****
url(r'^asdfasdfasdf/', views.index, name='i1'),
url(r'^yug/(\d+)/(\d+)/', views.index, name='i2'),
url(r'^buy/(?P<pid>\d+)/(?P<nid>\d+)/', views.index, name='i3'),
def func(request, *args, **kwargs):
from django.urls import reverse
url1 = reverse('i1') # asdfasdfasdf/
url2 = reverse('i2', args=(1,2,)) # yug/1/2/
url3 = reverse('i3', kwargs={'pid': 1, "nid": 9}) # buy/1/9/
xxx.html
{% url "i1" %} # asdfasdfasdf/
{% url "i2" 1 2 %} # yug/1/2/
{% url "i3" pid=1 nid=9 %} # buy/1/9/
注:
# 当前的URL
request.path_info
5、多级路由
project/urls.py
from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
url(r'^cmdb/', include("app01.urls")),
url(r'^monitor/', include("app02.urls")),
]
app01/urls.py
from django.conf.urls import url,include
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^login/', views.login),
]
app02/urls.py
from django.conf.urls import url,include
from django.contrib import admin
from app02 import views
urlpatterns = [
url(r'^login/', views.login),
]
6、默认值(欠)
7、命名空间(欠)
二、视图
1、获取用户请求数据
request.GET
request.POST
request.FILES
PS:
GET:获取数据
POST:提交数据
2、checkbox等多选的内容
request.POST.getlist()
3、上传文件
# 上传文件,form标签做特殊设置
obj = request.FILES.get('fafafa')
obj.name
f = open(obj.name, mode='wb')
for item in obj.chunks():
f.write(item)
f.close()
4、FBV & CBV
function base view
url.py
index -> 函数名
view.py
def 函数(request):
...
====》
/index/ -> 函数名
/index/ -> 类
====》
建议:两者都用
5、装饰器
欠
三、模板
四、ORM操作
select * from tb where id > 1
# 对应关系
models.tb.objects.filter(id__gt=1)
models.tb.objects.filter(id=1)
models.tb.objects.filter(id__lt=1)
创建类
a. 先写类
from django.db import models
# app01_userinfo
class UserInfo(models.Model):
# id列,自增,主键
# 用户名列,字符串类型,指定长度
username = models.CharField(max_length=32)
password = models.CharField(max_length=64)
b. 注册APP
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01',
]
c. 执行命令
python manage.py makemigrations
python manage.py migrate
d. ********** 注意 ***********
Django默认使用MySQLdb模块链接MySQL
主动修改为pymysql,在project同名文件夹下的__init__文件中添加如下代码即可:
import pymysql
pymysql.install_as_MySQLdb()
1. 根据类自动创建数据库表
# app下的models.py
python manage.py makemigrations
python manage.py migrate
字段:
字符串类型
数字
时间
二进制
自增(primary_key=True)
字段的参数:
null -> db是否可以为空
default -> 默认值
primary_key -> 主键
db_column -> 列名
db_index -> 索引
unique -> 唯一索引
unique_for_date ->
unique_for_month
unique_for_year
auto_now -> 创建时,自动生成时间
auto_now_add -> 更新时,自动更新为当前时间
# obj = UserGroup.objects.filter(id=1).update(caption='CEO')
# obj = UserGroup.objects.filter(id=1).first()
# obj.caption = "CEO"
# obj.save()
choices -> django admin中显示下拉框,避免连表查询
blank -> django admin是否可以为空
verbose_name -> django admin显示字段中文
editable -> django admin是否可以被编辑
error_messages -> 错误信息欠
help_text -> django admin提示
validators -> django form ,自定义错误信息(欠)
创建 Django 用户:python manage.py createsuperuser
2. 根据类对数据库表中的数据进行各种操作
一对多:
a. 外检
b.
外键字段_id
c.
models.tb.object.create(name='root', user_group_id=1)
d.
userlist = models.tb.object.all()
for row in userlist:
row.id
row.user_group_id
row.user_group.caption
参考:http://www.cnblogs.com/wupeiqi/articles/5246483.html
二、自定义分页
1.pagination.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Author:Du Fei
"""
分页思路:
如果:总页数 < 11
start_index =0
end_index = 总页数
else:
当前页<=6
start_index=1
end_index=11
else:
start_index = 当前页 -5
end_index=当前页 +5+1
如果 当前页 + 5 > 总页数:
end_index = 总页数 +1
当前页current_page
数据总量:data_count
显示页数:pager_num
每页显示10条数据:per_page_count
显示页数开始索引函数:start()
显示页数结束索引函数:end()
总页数:total_count
"""
from django.utils.safestring import mark_safe
class Page:
def __init__(self,current_page,data_count,per_page_count=10,pager_num=11):
self.current_page=current_page
self.data_count = data_count
self.per_page_count =per_page_count
self.pager_num = pager_num
@property
def start(self):
return (self.current_page-1) *self.per_page_count
@property
def end(self):
return self.current_page * self.per_page_count
@property
def total_count(self):
# v =len(LIST)
v, y = divmod(self.data_count, self.per_page_count)
if y:
v += 1
return v
def page_str(self,base_url):
page_list = []
# total_count总页数
if self.total_count < self.pager_num:
start_index = 1
end_index = self.total_count + 1
else:
if self.current_page <= (self.pager_num + 1) / 2:
start_index = 1
end_index = self.pager_num + 1
else:
start_index = self.current_page - (self.pager_num - 1) / 2
end_index = self.current_page + (self.pager_num + 1) / 2
if (self.current_page + (self.pager_num - 1) / 2) > self.total_count:
end_index = self.total_count + 1
start_index = self.total_count - self.pager_num + 1
if self.current_page == 1:
prev = '<a class="page" href="javascript:void(0)">上一页</a>'
else:
prev = '<a class="page" href="%s?p=%s">上一页</a>' % (base_url,self.current_page - 1,)
page_list.append(prev)
for i in range(int(start_index), int(end_index)):
if i == self.current_page:
temp = '<a class="page active" href="%s?p=%s">%s</a>' % (base_url,i, i)
else:
temp = '<a class="page" href="%s?p=%s">%s</a>' % (base_url,i, i)
page_list.append(temp)
if self.current_page == self.total_count:
nex = '<a class="page" href="javascript:void(0)">下一页</a>'
else:
nex = '<a class="page" href="%s?p=%s">下一页</a>' % (base_url,self.current_page + 1,)
page_list.append(nex)
# 跳转
jump = """
<input type='text' /><a onclick='jumpTo(this, "%s?p=");'>GO</a>
<script>
function jumpTo(ths,base){
var val = ths.previousSibling.value;
location.href = base + val;
}
</script>
""" % (base_url,)
page_list.append(jump)
# page_str ="".join(page_list)
page_str = mark_safe("".join(page_list))
return page_str
2.views.py
from django.shortcuts import render
from utils import pagination
LIST =[]
for i in range(500):
LIST.append(i)
def user_list(request):
#current_page当前页
current_page = request.GET.get('p',1)
current_page = int(current_page)
page_obj = pagination.Page(current_page,len(LIST))
data = LIST[page_obj.start:page_obj.end]
page_str = page_obj.page_str("/user_list/")
return render(request,'user_list.html',{'li':data,'page_str':page_str})
3.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.pagination .page{
display: inline-block;
padding: 5px;
background-color: cyan;
margin: 5px;
}
.pagination .page.active{
background-color: brown;
color: white;
}
</style>
</head>
<body>
<ul>
{% for item in li %}
{% include 'li.html' %}
{% endfor %}
</ul>
<div class="pagination">
{{ page_str }}
</div>
</body>
</html>
三.原生ajax
1.get请求方式
views.py
from django.shortcuts import render,HttpResponse
def ajax_json(request):
ret ={'code':True,'data':None}
print(ret)
print(request.method)
import json
return HttpResponse(json.dumps(ret))
ajax.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" />
<input type="button" value="Ajax1" onclick="Ajax1();"/>
<script>
get请求
function Ajax1() {
var xhr = new XMLHttpRequest();
xhr.open('GET','/ajax_json/',true);
xhr.onreadystatechange = function(){
if( xhr.readyState == 4){
//接收完毕
console.log(xhr.responseText);
var obj=JSON.parse(xhr.responseText);
console.log(obj);
console.log(obj.code)
}
};
xhr.setRequestHeader('k1','v1');
xhr.send("name=root;pwd=123")
}
</script>
</body>
</html>
2.post请求方式
views.py
from django.shortcuts import render,HttpResponse
def ajax_json(request):
print(request.POST)
ret ={'code':True,'data':None}
print(ret)
print(request.method)
import json
return HttpResponse(json.dumps(ret))
ajax.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" />
<input type="button" value="Ajax1" onclick="Ajax1();"/>
<script>
//opst请求
function Ajax1() {
//浏览器兼容
function getXHR(){
var xhr = null;
if(XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
}
{#var xhr = new XMLHttpRequest();#}
var xhr = getXHR();
xhr.open('POST','/ajax_json/',true);
xhr.onreadystatechange = function(){
if( xhr.readyState == 4){
//接收完毕
{#console.log(xhr.responseText);#}
var obj=JSON.parse(xhr.responseText);
console.log(obj);
{#console.log(obj.code)#}
}
};
{#xhr.setRequestHeader('k1','v1');#}
//设置请求头
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');
xhr.send("name=root;pwd=123")
}
</script>
</body>
</html>
四、文件上传
views.py
from django.shortcuts import render,HttpResponse
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))
upload.html
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Title</title>
6 <style>
7 .upload{
8 display: inline-block;
9 padding: 10px;
10 background-color: brown;
11 position: absolute;
12 top: 0;
13 bottom: 0;
14 right: 0;
15 left: 0;
16 z-index: 90;
17 }
18 .file{
19 width: 100px;height: 100px;opacity: 0;
20 position: absolute;
21 top: 0;
22 bottom: 0;
23 right: 0;
24 left: 0;
25 z-index: 100;
26 }
27 </style>
28 </head>
29 <body>
30 <div style="position: relative;width: 100px;height: 50px;">
31 <input class="file" type="file" id="fafafa" name="afafaf">
32 <a class="upload">上传</a>
33 </div>
34 <p>aaaaaa</p>
35 <input type="submit" value="提交XHR" onclick="xhrSubmit();"/>
36 <input type="submit" value="提交jQuery" onclick="jqSubmit();"/>
37
38 <hr/>
39 <form id="form1" action="/upload_file/" method="POST" enctype="multipart/form-data" target="ifm1">
40 <iframe id="ifm1" name="ifm1" style="display: none;"></iframe>
41 <input type="file" name="fafafa" onchange="changeUpalod();" />
42 {# <input type="submit" onclick="iframeSubmit();" value="Form提交"/>#}
43 </form>
44 <div id="preview"></div>
45
46
47 <script src="/static/jquery-1.12.4.js"></script>
48 <script>
49 function changeUpalod() {
50 $('#ifm1').load(function(){
51 var text = $('#ifm1').contents().find('body').text();
52 var obj = JSON.parse(text);
53
54 $('#preview').empty();
55 var imgTag = document.createElement('img');
56 imgTag.src = "/" + obj.data;
57 $('#preview').append(imgTag);
58 });
59 $('#form1').submit();
60 }
61
62 function jqSubmit() {
63 var file_obj = document.getElementById('fafafa').files[0];
64
65 var fd = new FormData();
66 fd.append('username', 'root');
67 fd.append('fafafa', file_obj);
68 $.ajax({
69 url:'/upload_file/',
70 type:'POST',
71 data:fd,
72 processData:false,
73 contentType:false,
74 success:function (arg,a1,a2) {
75 console.log(arg);
76 console.log(a1);
77 console.log(a2);
78
79 }
80
81 })
82
83 }
84
85 function xhrSubmit() {
86 //$('#fafafa')[0]
87 var file_obj=document.getElementById('fafafa').files[0];
88 console.log(file_obj);
89
90 var fd = new FormData();
91 fd.append('username','root');
92 fd.append('fafafa',file_obj);
93
94 var xhr = new XMLHttpRequest();
95 xhr.open('POST','/upload_file/',true);
96
97 xhr.onreadystatechange = function(){
98 if( xhr.readyState == 4){
99 //接收完毕
100 {#console.log(xhr.responseText);#}
101 var obj=JSON.parse(xhr.responseText);
102 console.log(obj);
103 {#console.log(obj.code)#}
104 }
105 };
106 xhr.send(fd);
107 }
108
109 function iframeSubmit(){
110 $('#ifm1').load(function(){
111 var text = $('#ifm1').contents().find('body').text();
112 var obj = JSON.parse(text);
113
114 $('#preview').empty();
115 var imgTag = document.createElement('img');
116 imgTag.src = "/" + obj.data;
117 $('#preview').append(imgTag);
118 })
119 }
120 </script>
121
122 </body>
123 </html>
来源:oschina
链接:https://my.oschina.net/u/4410561/blog/4082771