django知识点回顾与补充
一、django知识点回顾
1.Cookie操作 - 客户端本地存储的键值对 2.Session操作 - 3.URL路由 - /index -> view.函数 4.MTV 5.View中返回方式 - HttpResponse("内容") - render(request,'模板路径',{}) - redirect('URL') 6.启动 python manage.py runserver 7. 创建project django-admin startproject [project名称] python manage.py startapp [app名称] 8. URL中有别名 [ ('/index/(\d+)', func, name='xxoo') ] 9. settings.py配置 STATICFILES_DIRS=( os.path.join(BASE_DIR,'static'), ) 10. 模板 {{变量}} {% for,if, %} views.py def func(request): return render(request, 'index.html',{'arg': [1,3,4,6]}) index.html: {{arg.2}} 11. 数据库连接修改mysql 默认:MySQLDB 修改:pymysql 12. 模板继承 block extends ?? 一个子模板是否可以继承多个父模板 13. request参数 - request.method - request.GET - request.POST.get - request.POST.getlist('hobby') 14. 外键 15. 操作数据表 python manage.py makemigrations python manage.py migrate 16. 在html中使用别名代指静态文件路径 17. 路由分发(urls.py) 18. 数据操作 models.Tb.objects.all().delete() models.Tb.objects.filter(条件).delete() 19. 外键的添加添加 class A(models.Model):部门表 name = c.CharField(max_length=16,null=True,blank=True) class B() 员工表 title = c fk = FK(A) models.B.objects.create( title='1', fk=models.A.objects.get(id=1) ) models.B.objects.create( title='1', fk_id= 1 ) 20. 外键关联删除 21. URL匹配 [ ('/index/(?P<nid>\d+)'), func ] views.py def func(request,nid): pass 22. ORM - Models中操作 - shell操作 对象 = models.TB.objects.get(id=1) [对象,] = models.TB.objects.filter(id=1) 23.CSRF 安全机制 24.自定义标签 25. XSS攻击 views.py def func(request,nid): return render(request, 'x.html', {'k1':'v1','k2': "<h1>v2</h1>"}) x.html: {{k1}} {{k2}} 页面输出: v1 <h1>v2</h1> {{k1}} {{k2|safe}} 页面输出: v1 v2(加大加粗) 26. obj = models.Tb.objects.get(id=1) obj.name = '新名称' obj.save() models.Tb.objects.filter(id=1).update(nam='新') 27. 多表查询 双下划线跨表 28. URL,namespace
29. 迭代器
二、django补充
Day54 - 内容回顾 - 请求响应Http 1. 发送Http请求 2. 服务器接收,根据请求头中的url在路由关系表中进行匹配(从上到下) 3. 匹配成功后,执行指定的views函数 URL -> 函数 ==> FBV URL -> 类 ==> CBV 4. 业务处理 - 根据个人需求自定 - 操作数据库 - 原生SQL - Django ORM (可能是史上最牛的ORM框架) ==> 返回给用户的结果 <== - 响应内容 - 响应头 - 响应体 请求字符串: 请求头 Request URL:http://www.cnblogs.com/getData/ reqeust.GET Request Method:POST Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Encoding:gzip, deflate, sdch Accept-Language:zh-CN,zh;q=0.8 Cache-Control:max-age=0 Connection:keep-alive Cookie:__utma=226521935.503212689.1478164225.1478164225.1478164225.1; __utmz=226521935.1478164225.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _ga=GA1.2.503212689.1478164225 Host:www.cnblogs.com If-Modified-Since:Tue, 07 Mar 2017 01:49:57 GMT Upgrade-Insecure-Requests:1 User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36 分隔: \r\n\r\n 请求体: nid=sb reqeust.body字符串 => reqeust.POST 字典 响应字符串: 响应头: Cache-Control:no-cache Connection:keep-alive ContentType:text/json;charset=UTF-8 Date:Tue, 07 Mar 2017 03:18:30 GMT Server:Tengine Transfer-Encoding:chunked X-Tingyun-Tx-Data:{"r":"56710730","action":"WebAction\/SpringController%2Fpassport\/login (GET)","id":"rUsXqRdGAHI#hxFVdq76WLA","time":{"duration":8,"rds":0,"ex":0,"code":8,"qu":0,"mc":0,"mon":0,"db":0},"trId":"e9725e96a5a2fca4"} X-Via:1.1 zw13:0 (Cdn Cache Server V2.0), 1.1 ietong143:1 (Cdn Cache Server V2.0) 分隔: \r\n\r\n 响应体: ....
fbv示例:
views.py
from django.shortcuts import render,redirect,HttpResponse # Create your views here. from django.views import View def fbv(request): if request.method == 'GET': return HttpResponse('FBV.GET') elif request.method == 'POST': return HttpResponse('FBV.POST') ---------------------------------------------------------------------------------- urls.py urlpatterns = [ url(r' ^fbv$', views.fbv), ]
三、dispatch用法
urls.py
url(r'^cbv$', views.CBV.as_view()),
views.py
from django.shortcuts import render,redirect,HttpResponse # Create your views here. from django.views import View class CBV(View): def dispatch(self, request, *args, **kwargs): result =super(CBV,self).dispatch(request, *args, **kwargs) return result def get(self,request): return render(request,'cbv.html') def post(self,request): return HttpResponse('CBV.POST')
cbv.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="cbv" method="POST"> <input type="text" /> <input type="submit" /> </form> </body> </html>
四、增,删,改,查
1、手动创建app命令
python manage.py startapp app01
2、配置新app_设置settings.py
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01', ]
3、增,册,改,查
models.py
from django.db import models # Create your models here. # 在数据库创建表,表名userinfo class UserInfo(models.Model): name = models.CharField(max_length=16) # 表中创建一列数据 age = models.IntegerField() class Group(models.Model): caption = models.CharField(max_length=16) # userinfo """ id name(字符串类型) age 1 root 18 2 eric 20 """ """ 1. 创建和修改数据库表 在settings中的配置app的名字app02 python manage.py makemigrations python manage.py migrate 2. 数据库操作 增删改查 """
test.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>test</h1> <ul> {# #[{id:1,name:root,age:18},{id:1,name:root,age:18},]#} {% for foo in uuu %} <li>{{ foo.id }} ----- {{ foo.name }} ----- {{ foo.age }} </li> {% endfor %} </ul> </body> </html>
views.py
from django.shortcuts import render from django.shortcuts import HttpResponse # Create your views here. from app02 import models def test(request): # 增加 # name,age表示列名
#方法一: # models.UserInfo.objects.create(name='alex',age=18)
#方法二:
#Teachers.object.create(name='root')
obj = Teachers(name='root')
obj.save()
# models.Group.objects.create(caption='组2') # 获取 # user_list = models.UserInfo.objects.all() #[{id:1,name:root,age:18},{id:1,name:root,age:18},] # 删除 # models.UserInfo.objects.all().delete() # models.UserInfo.objects.all().delete() # models.UserInfo.objects.filter(id=1).delete() # models.UserInfo.objects.filter(age=18).delete() # models.UserInfo.objects.filter(id=2,age=18).delete() # models.UserInfo.objects.filter(id=2,age=18,name='root').delete() # 更新 # models.UserInfo.objects.all().update(age=10) # models.UserInfo.objects.filter(name='alex').update(age=10) # models.UserInfo.objects.filter(id=1).update(age=10) # models.UserInfo.objects.filter(id=1).update(age=10, name='tony') # for row in user_list: # print(row.id,row.name,row.age) # return HttpResponse('ok') # 1.找test.html文件,并打开获取其内容 # 2.将获取到的内容+{'user_list': user_list}参数进行替换 # 3.将替换后的字符串返回给用户 return render(request,'test.html',{'uuu': user_list}) def add_test(request): n = request.GET.get('name') a = request.GET.get('age') models.UserInfo.objects.create(name=n,age=a) return HttpResponse('创建成功') def del_test(request): nid = request.GET.get('iid') models.UserInfo.objects.filter(id=nid).delete() return HttpResponse('删除成功') def edit_test(request): i = request.GET.get('id') n = request.GET.get('name') a = request.GET.get('age') models.UserInfo.objects.filter(id=i).update(name=n,age=a) return HttpResponse('更新成功')
#获取id>1的值
result = Teachers.object.filter(id__gt=1)
result = Teachers.object.filter(id__gt=1),first()
多表查询
from django.db import models class Classes(models.Model): """ 班级表,男 """ titile = models.CharField(max_length=32) m = models.ManyToManyField('Teachers') class Teachers(models.Model): """ 老师表,女 """ name = models.CharField (max_length=32)
class Student(models.Model): """ 学生表 """ username = models.CharField(max_length=32) age = models.IntegerField() gender = models.BooleanField() cs = models.ForeignKey(Classes) # cs,cs_id 1 3班 ######################## 单表 ######################## # 增加 # Teachers.objects.create(name='root') # obj = Teachers(name='root') # obj.save() # 查 # Teachers.objects.all() # Teachers.objects.filter(id=1) # Teachers.objects.filter(id=1,name='root') # result = Teachers.objects.filter(id__gt=1) # [obj(id,name),] # result = Teachers.objects.filter(id__gt=1).first() # 删除 # Teachers.objects.filter(id=1).delete() # 改 # Teachers.objects.all().update(name='alex') # Teachers.objects.filter(id=1).update(name='alex') ######################## 一对多 ######################## """ 班级: id name 1 3班 2 6班 学生 id username age gender cs_id 1 东北 18 男 1 2 东北1 118 男 2 2 东北1 118 男 1 """ # 增加 # Student.objects.create(username='东北',age=18,gender='男',cs_id=1) # Student.objects.create(username='东北',age=18,gender='男',cs= Classes.objects.filter(id=1).first() ) # 查看 """ ret = Student.objects.all() # [] # [ obj(..),] # [ obj(1 东北 18 男 1),obj(2 东北1 118 男 2),obj(..),] for item in ret: print(item.id) print(item.username) print(item.age) print(item.gender) print(item.cs_id) print(item.cs.id) print(item.cs.name) """ # 删除 # Student.objects.filter(id=1).delete() # Student.objects.filter(cs_id=1).delete() # cid = input('请输入班级ID') # Student.objects.filter(cs_id=cid).delete() # cname = input('请输入班级名称') # Student.objects.filter(cs_id=cid).delete() # Student.objects.filter(cs__name=cname).delete() ######################## 多对多 ######################## # 多对多 """ 班级: id title 1 3班 2 4班 3 5班 老师: id title 1 Alex 2 老妖 3 瞎驴 4 Eric 老师班级关系表(类): id 班级id 老师id 1 1 2 2 1 3 4 2 2 5 2 3 6 2 4 7 1 5 # 增 obj = Classes.objects.filter(id=1).first() #1 3班 obj.m.add(2) obj.m.add([4,3]) # obj = Classes.objects.filter(id=2).first() #1 3班 # obj.m.add(2) # obj.m.add([4,3]) obj = Classes.objects.filter(id=1).first() #1 3班 # 删除 # obj.m.remove([4,3]) # 清空 obj.m.clear() # 重置 obj.m.set([2,3,5]) # 查第三张表 # 把3班的所有老师列举 obj = Classes.objects.filter(id=1).frist() obj.id obj.titile ret = obj.m.all() # 第三张表 # ret是一个 [ 老师1(id,name),obj(id,name) ] """