基本配置
python3 manage.py runserver 127.0.0.1:8000 启动服务
python3 manage.py startapp cmdb
python3 manage.py startapp monitor 创建app
路由
from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^cmdb/', include('cmdb.urls')),
url(r'^monitor/', include('monitor.urls')),
url(r'^detail-(d+)/',def detail(request,nid))),
]
static文件配置
STATIC_URL = '/static/' STATICFILES_DIR=(os.path.join(BASE_DIR,'static'),)
views配置
1.至少一个参数:request
2.request 包含请求的所有信息
request.get 去请求头里面拿数据
request.post 去请求体里面拿数据,也就是去request.body里面取值
request.body 请求体里面原生的值,如果post里面没有数据,就去body里面找
request.FILES 取文件
3. 处理完给用户返回
return HttpResponse(..) #返回字典或数据 return HttpResponse(json.dumps(task_result,default=date_handler))
return render 把当前获取到的值,返回到html渲染
return render(request,"new_article.html",{"form":article_form})
return render(request,'multitask_file.html',locals())
return render(request,'index.html')
locals()返回一个包含当前作用域里面的所有变量和它们的值的字典
return redirect() 后面跟具体的请求路径 return redirect("/category/all/")
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 from django.shortcuts import render 2 from django.shortcuts import redirect 3 from django.shortcuts import HttpResponse 4 from cmdb import models 5 6 # Create your views here. 7 def users(request): 8 return HttpResponse('OK')
创建数据库
from django.db import models class UserInfo(models.Model): uid = models.AutoField(primary_key=True) username = models.CharField(max_length=32) pwd = models.CharField(max_length=64) age = models.IntegerField()
根据app的models.py生成数据库表
python manage.py makemigrations
python manage.py migrate
自定义配置数据库
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 DATABASES = { 2 'default': { 3 'ENGINE': 'django.db.backends.mysql', 4 'NAME':'dbname', 5 'USER': 'root', 6 'PASSWORD': 'xxx', 7 'HOST': '', 8 'PORT': '', 9 } 10 }
数据库基本操作
类---》数据库的表
字段----》列
对象---》一行数据
查:
models.tb.objects.all()
models.tb.objects.filter(nid=1)
models.tb.objects.filter(nid=1).first()
删:
models.tb.objects.all().delete()
models.tb.objects.filter(nid=1).delete()
增:
models.UserInfo.objects.create(username=u,pwd=p,age=a)
改:
obj = models.UserInfo.objects.filter(uid=uuid).update(username=u,pwd=p,age=a)
模板引擎
基本语法
取值:return render(request,'xx.html',{v:[1234]})
{{v.2}}
{% for i in d%}
{{i}} -->循环所有key
{%endfor%}
{% for k,v in d.items%}
{{k}} --{{v}}
{%endfor%}
特殊规则:
- 1
{{k1}}
- 2
{% if a == 123 %}
{% else %}
{% endif %}
- 3
{% for item in LIST %}
{{item}}
{% endfor %}
- 4
# 索引:字典.k1 列表.1
- 5.自定义模板方法
- filter: 在if条件中做条件时
- simple_tag: 在页面仅显示内容时
- 6. extends
- 模板的继承
- 7. include
- 导入公共组件
Cookie和Session
obj = redirect(‘、home’)
obj.set_cookie('uuuu',u,max-age=10) 设置cookie超时时间10s
v= request.COOKIES.get(‘uuuuu’) 获取cookie
session 服务器端保存的键值对 key是随机字符串
request.session['user'] =u
前者是用户浏览器上的一个键值对,后者是放在服务器端的键值对
session = {
'asdfasdfasd': {'username':'hailong'},
'asdfasdfasdf': {username:'feinikesi'},
}
注销:
request.session.clear()
return redirect('/login/')
settings里面设置
1 SESSION_ENGINE = 'django.contrib.sessions.backends.db' # 引擎(默认) 2 3 SESSION_COOKIE_NAME = "sessionid" # Session的cookie保存在浏览器上时的key,即:sessionid=随机字符串(默认) 4 SESSION_COOKIE_PATH = "/" # Session的cookie保存的路径(默认) 5 SESSION_COOKIE_DOMAIN = None # Session的cookie保存的域名(默认) 6 SESSION_COOKIE_SECURE = False # 是否Https传输cookie(默认) 7 SESSION_COOKIE_HTTPONLY = True # 是否Session的cookie只支持http传输(默认) 8 SESSION_COOKIE_AGE = 1209600 # Session的cookie失效日期(2周)(默认) 9 SESSION_EXPIRE_AT_BROWSER_CLOSE = False # 是否关闭浏览器使得Session过期(默认) 10 SESSION_SAVE_EVERY_REQUEST = True # 是否每次请求都保存Session,默认修改之后才保存(默认)
ORM操作
models.UserInfo.objects.all() 返回Queryset类型(特殊的列表,每一行就是一个userinfo对象)
models.UserInfo.objects.values('name','pwd') 内部元素是字典
models.UserInfo.objects.values_list('name','pwd') 内部元素是列表
models.UserInfo.objects.filter(name='alex') 条件过滤,取到的是对象
models.UserInfo.objects.filter(name='alex').values(...) 变成字典
models.UserInfo.objects.get(name='alex') 获取一个元素,没有找到和找到多了 都会报错
models.UserInfo.objects.filter(name='alex').first() 获取一个元素,如果有多个取第一个,没有返回None
class DePart(models.Model):
title = models.CharField(max_length=16)
class UserInfo(models.Model):
username = models.CharField(max_length=32)
password = models.CharField(max_length=32)
dp = models.ForeignKey("DePart")
正向查询:
q = models.UserInfo.objects.all()
q = models.UserInfo.objects.all().only('id','name') #只取
q = models.UserInfo.objects.all().defer('id','name') #不取
for row in q:
print(row.username,row.password,row.dp_id,row.dp.id,row.dp.title)
q = models.UserInfo.objects.values('username','password','dp__title')
q = models.UserInfo.objects.values_list('username','password','dp__title')
print(q)
反向查询:
q = models.UserInfo.objects.all()
for row in q:
print(row.username,row.password,row.dp_id,row.dp.id,row.dp.title)
q = models.UserInfo.objects.values('username','password','dp__title')
q = models.UserInfo.objects.values_list('username','password','dp__title')
print(q)
v = models.DePart.objects.all()
for row in v:
print(row.id,row.title,row.userinfo_set.values('username'))
print(row.id,row.title,row.userinfo_set.all())
v1 = models.DePart.objects.values('id','title','userinfo__username')
for row1 in v1:
print(row1)
总结:
all方法(对象):正向跨表查询用字段.字段,比如,row.dp.title;反向查询用小写的表名_set,例如:row.userinfo_set.all()
values和values_list方法(字典,元组):正向跨表查询用字段__字段,比如 dp__title;反向查询用小写表名__字段,例如:userinfo__username
通用分页功能
1 <nav aria-label="..."> 2 <ul class="pagination"> 3 {{ page_info.page_str|safe }} 4 </ul> 5 </nav> 6 </div>
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 """ 4 @Author:Liumj 5 @file: page.py 6 @time: 2018/1/6 0:01 7 """ 8 """ 9 使用方式: 10 all_count = models.UserInfo.objects.all().count() 11 page_info = PageInfo(request.GET.get('p'),10,all_count,request.path_info) 12 user_list = models.UserInfo.objects.all()[page_info.start():page_info.end()] 13 14 return render(request,'users2.html',{'user_list':user_list,'page_info':page_info}) 15 """ 16 17 class PageInfo(object): 18 def __init__(self,current_page,per_page_num,all_count,base_url,page_range=9): 19 """ 20 21 :param current_page: 当前页 22 :param per_page_num: 每页显示数据条数 23 :param all_count: 数据库总个数 24 :param base_url: 页码标签前缀 25 :param page_range: 页面最多显示的页码个数 26 """ 27 try: 28 current_page = int(current_page) 29 except Exception as e: 30 current_page = int(1) 31 self.current_page = current_page 32 self.per_page_num = per_page_num 33 self.all_count = all_count 34 self.base_url = base_url 35 a,b = divmod(self.all_count,self.per_page_num) 36 if b !=0: 37 self.all_page = a+1 38 else: 39 self.all_page = a 40 self.page_range = page_range 41 def start(self): 42 return (self.current_page - 1) * self.per_page_num 43 def end(self): 44 return self.current_page * self.per_page_num 45 def page_str(self): 46 page_list = [] 47 first_page = '<li><a href="%s?p=%s">首页</a></li>' %(self.base_url,1) 48 page_list.append(first_page) 49 if self.current_page <=1: 50 prev_page = '<li><a href="#">上一页</a></li>' 51 else: 52 prev_page = '<li><a href="%s?p=%s">上一页</a></li>' %(self.base_url,self.current_page-1) 53 page_list.append(prev_page) 54 55 if self.all_page <=self.page_range: 56 start = 1 57 end = self.all_page + 1 58 else: 59 if self.current_page >int(self.page_range/2): 60 if self.current_page + int(self.page_range/2) > self.all_page: 61 start = self.all_page - self.page_range + 1 62 end = self.all_page + 1 63 else: 64 start = self.current_page - int(self.page_range/2) 65 end = self.current_page + int(self.page_range/2) + 1 66 else: 67 start = 1 68 end = self.page_range + 1 69 for i in range(start,end): 70 if self.current_page == i: 71 temp = '<li class="active"><a href="%s?p=%s">%s</a></li>' %(self.base_url,i,i) 72 else: 73 temp = '<li><a href="%s?p=%s">%s</a></li>' %(self.base_url,i,i) 74 page_list.append(temp) 75 76 if self.current_page >= self.all_page: 77 next_page = '<li><a href="#">下一页</a></li>' 78 else: 79 next_page = '<li><a href="%s?p=%s">下一页</a></li>' %(self.base_url,self.current_page+1) 80 page_list.append(next_page) 81 82 end_page = '<li><a href="%s?p=%s">尾页</a></li>' % (self.base_url, self.all_page) 83 page_list.append(end_page) 84 85 return "".join(page_list)
form表单
功能:
验证用户请求
自动生成html(保留上次提交内容)
字段:
CharField(字符串) EmailField(邮件格式) IntergerField(整型,数字格式) GenericIPAdderessField(IP格式) FiledField(文件) ChoiceField(多选) RegexField(自定义字符串)
插件:
widgets.TextInput
widgets.PasswordInput
widgets.Textarea
widgets.Select(attrs={'class': 'form-control'},choices=[(1,'普通用户'),(2,"超级用户")])
widgets.SelectMultiple(attrs={'class': 'form-control'},choices=[(1,'普通用户'),(2,"超级用户")])
widget=widgets.RadioSelect(choices=((1,'上海'),(2,'北京'),))
widget=widgets.CheckboxInput()
widget=widgets.CheckboxSelectMultiple()
widget=widgets.FileInput()
FK表:
问题:数据源无法实时更新
重写构造函数
def __init__(self,*args,**kwargs):
super(UserForm,self).__init__(*args,**kwargs)
self.fields['ut_id'].widget.choices = models.UserType.objects.values_list('id','name')
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 from django import forms 2 from django.forms import fields 3 from django.forms import widgets 4 class UserForm(forms.Form): 5 username = fields.CharField(required=True,error_messages={'required':"用户名必填"}, 6 widget = widgets.TextInput(attrs={'class':'form-control'})) 7 password = fields.CharField(required=True,error_messages={'required':"密码必填"}, 8 widget=widgets.TextInput(attrs={'class': 'form-control'})) 9 email = fields.EmailField(required=True,error_messages={'required':"邮箱必填",'invalid':"邮箱格式错误"}, 10 widget=widgets.TextInput(attrs={'class': 'form-control'})) 11 12 def add_user(request): 13 if request.method == 'GET': 14 obj = UserForm() 15 return render(request,'add-user.html',{'obj':obj}) 16 else: 17 #获取用户提交的数据 18 #数据和正则进行验证 19 obj = UserForm(request.POST) 20 if obj.is_valid(): 21 print("验证通过",obj.cleaned_data) 22 23 else: 24 pass 25 # print("错误信息",obj.errors["username"][0]) 26 # print("错误信息",obj.errors["password"][0]) 27 # print("错误信息",obj.errors["email"][0]) 28 return render(request,'add-user.html',{'obj':obj})
缓存
配置(内存缓存方式),全局配置
1 CACHES = { 2 'default': { 3 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 4 'LOCATION': 'unique-snowflake', 5 'TIMEOUT':300, 6 }, 7 'OPTIONS': { 8 'MAX_ENTRIES': 300, # 最大缓存个数(默认300) 9 'CULL_FREQUENCY': 10,#缓存达到最大个数时,剔除缓存个数的比例 10 }}
1.全站缓存
MIDDLEWARE = [
'django.middleware.cache.UpdateCacheMiddleware', #第一行
。。。。。。。。。。。。。。
'django.middleware.cache.FetchFromCacheMiddleware', #最后一行
]
2.单独试图函数缓存
1 from django.views.decorators.cache import cache_page 2 # Create your views here. 3 @cache_page(10) #缓存时间10s 4 def index(request):+ 5 ctime = time.time() 6 return render(request,'index.html',{'ctime':ctime})
3.局部模板缓存
1 {% load cache %} 2 <!DOCTYPE html> 3 <html lang="en"> 4 <head> 5 <meta charset="UTF-8"> 6 <title>Title</title> 7 </head> 8 <body> 9 {% cache 5000 xxx %} 10 <h1>{{ ctime }}</h1> 11 {% endcache %} 12 <h3>{{ ctime }}</h3> 13 14 </body> 15 </html>
综合练习
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 from django.shortcuts import render 2 from django.shortcuts import redirect 3 from django.shortcuts import HttpResponse 4 from cmdb import models 5 6 # Create your views here. 7 def users(request): 8 v = request.session.get('username') 9 if not v: 10 return redirect('/cmdb/login') 11 server_list = models.UserInfo.objects.all() 12 return render( 13 request, 14 'server1.html', 15 {'server_list':server_list,'current_user':v} 16 ) 17 def add_user(request): 18 if request.method == "GET": 19 return render(request,'add_user.html') 20 elif request.method == "POST": 21 u = request.POST.get('user') 22 p = request.POST.get('pwd') 23 a = request.POST.get('age') 24 models.UserInfo.objects.create(username=u,pwd=p,age=a) 25 return redirect('/cmdb/users') 26 def del_user(request): 27 if request.method == "GET": 28 uuid =request.GET.get('uid') 29 models.UserInfo.objects.filter(uid=uuid).delete() 30 return redirect('/cmdb/users') 31 def edit_user(request): 32 if request.method == "GET": 33 uuid = request.GET.get('uid') 34 obj = models.UserInfo.objects.filter(uid =uuid).first() 35 return render(request,'edit_user.html',{"obj":obj}) 36 elif request.method == 'POST': 37 uuid = request.POST.get('uid') 38 u = request.POST.get('user') 39 p = request.POST.get('pwd') 40 a = request.POST.get('age') 41 obj = models.UserInfo.objects.filter(uid=uuid).update(username=u,pwd=p,age=a) 42 return redirect('/cmdb/users') 43 def edit_user_new(request,uuid): 44 if request.method == 'GET': 45 obj=models.UserInfo.objects.filter(uid=uuid).first() 46 return render(request,'edit_user_new.html',{'obj':obj}) 47 elif request.method == 'POST': 48 u = request.POST.get('user') 49 p = request.POST.get('pwd') 50 a = request.POST.get('age') 51 obj = models.UserInfo.objects.filter(uid=uuid).update(username=u, pwd=p, age=a) 52 return redirect('/cmdb/users') 53 def upload(request): 54 if request.method == "GET": 55 return render(request,'upload.html') 56 elif request.method == "POST": 57 obj = request.FILES.get('up') 58 import os 59 #f = open(os.path.join('upload',obj.name),'wb') 60 f = open(os.path.join('upload', obj.name), 'wb') 61 #f = open(obj.name,'wb') 62 for line in obj.chunks(): 63 f.write(line) 64 f.close() 65 return HttpResponse('...') 66 def tpl(request): 67 return render(request,'tpl.html',{'sum':'nihaohelloljdfskadl;dkj;lj'}) 68 def group(request): 69 return render(request,'group.html') 70 def login(request): 71 if request.method == 'GET': 72 return render(request,'login.html') 73 elif request.method == 'POST': 74 u = request.POST.get('user') 75 p = request.POST.get('pwd') 76 obj = models.UserInfo.objects.filter(username=u,pwd=p) 77 if obj: 78 obj = redirect('/cmdb/users') 79 #obj.set_cookie(key='user_name', value=u, max_age=10) 80 request.session['username'] = u 81 return obj 82 else: 83 return render(request,'login.html',{'msg':'用户名或密码错误'})
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # Author:Liumj 4 from django.conf.urls import url,include 5 from django.contrib import admin 6 from cmdb import views 7 8 urlpatterns = [ 9 url(r'^users$',views.users), 10 url(r'^add_user$',views.add_user), 11 url(r'^del_user$',views.del_user), 12 url(r'^edit_user$',views.edit_user), 13 url(r'^edit_user_new-(?P<uuid>\d+).html$',views.edit_user_new,name='nnn'), 14 url(r'^upload$',views.upload), 15 url(r'^tpl.html$',views.tpl), 16 url(r'^group$',views.group), 17 url(r'^login$',views.login), 18 ]