django-session,CBV,ORM实例
1 from django.shortcuts import render,HttpResponse,redirect 2 from django.core.paginator import Paginator 3 from app01 import models 4 5 # Create your views here. 6 # def edit(request,a1): 7 # 8 # return HttpResponse('=========') 9 10 11 12 # def index(request): 13 # list=['json','tony','python'] 14 # from app01 import models 15 # #add 16 # # models.usergroup.objects.create(title='销售部') 17 # models.UserInfo.objects.create(username='李柔',password='123',ug_id='1') 18 # 19 # #查询 20 # models.usergroup.objects.filter(id__gt=2).update(title='销售') 21 # """ 22 # 大于 __gt 23 # 小于 __lt 24 # 25 # """ 26 # 27 # user_list=models.UserInfo.objects.all() 28 # 29 # 30 # #user_list 类型 queryset类型 31 # for row in user_list: 32 # print(row.username) 33 # 34 # 35 # 36 # 37 # 38 # return render(request,'index.html',{'user_list':user_list}) 39 40 #以下是cbv架构 41 """ 42 get 查 43 post 创建 44 put 更新 45 delete 删除 46 47 在models里面创建表 48 from django.db import models 49 class userinfo(models.Model): 50 name=models.CharField(max_length=32) 51 password=models.CharField(max_length=32) 52 53 database的增删改查操作:在views中 54 增加: 55 models.userinfo.objects.create(title='salary') 56 57 删除 58 models.userinfo.objects.filter(id__gt=1).delete() 59 60 更改 61 models.userinfo.objects.filter(id__gt=1).update(name='qst') 62 id__lt=1 ---> lower than 1 63 id__gt=1 :greater than 1 64 65 66 查询: 67 models.userinfo.objects.all() 68 .filter(id=1) 69 .filter(id__gt=1) 70 .filter(id__lt=1) 71 72 73 74 75 76 77 78 79 80 81 82 83 """ 84 85 from django.views import View 86 87 class login(View):#继承view作为父类 88 #写一个装饰器,在不更改原函数内部的条件下,增加函数执行前后的动作 89 def dispatch(self, request, *args, **kwargs):#重写函数 90 print('begin......') 91 obj=super(login,self).dispatch(request,*args,**kwargs) 92 print('over......') 93 return obj 94 95 96 def get(self,request): 97 return render(request,'login.html') 98 99 def post(self,request): 100 print(request.POST.get('name')) 101 return HttpResponse('ok post') 102 103 104 def test(request): 105 # models.usertype.objects.create(title='普通玩家') 106 # models.usertype.objects.create(title='二玩家') 107 # models.usertype.objects.create(title='人民币玩家') 108 # models.UserInfo.objects.create(username='马家军',password='123',ut_id=1) 109 # models.UserInfo.objects.create(username='钱jb',password='123',ut_id=2) 110 # models.UserInfo.objects.create(username='洛凯',password='123',ut_id=3) 111 user_info=models.UserInfo.objects.all()#queryset格式 112 obj=models.usertype.objects.all().first()#对象,能点出来相关联的东西 113 result=models.UserInfo.objects.values('username','password','ut__title') #神奇的下划线 114 for i in result: 115 print(i) 116 117 """ 118 [obj,obj,obj] 119 .filter(id__gt=1) 120 .all() 对象,批量拿一般是queryset类型 121 122 123 [{},{},{}] 124 .values('id','name') 字典 125 126 127 128 [(),(),(),] 129 .values_list('id','name') 元组 130 """ 131 for item in user_info: 132 print(item.username,' ',item.password,' ',item.ut.title) 133 #ut是外键,代指一行数据,直接拿来用 134 135 for row in obj.userinfo_set.all(): 136 print('对应的是:',row.username) 137 return HttpResponse('...') 138 """ 139 分页器Paginator,返回一个paginator对象 140 paginator 对象 141 142 paginator.page(xxx) 143 has_next 有下一页 144 next_page_number 下一页的页码 145 has_previous 有前一页 146 previous_page_number 前一页页码 147 148 """ 149 def index(request): 150 user_list=models.UserInfo.objects.all() 151 # for i in range(0,200): 152 # name='root'+str(i) 153 # models.UserInfo.objects.create(username=name,password=123,ut_id=1) 154 paginator=Paginator(user_list,10) 155 current_page=request.GET.get('page') 156 print(current_page) 157 try: 158 posts=paginator.page(current_page) 159 except Exception as e: 160 print(e) 161 posts=paginator.page(1) 162 return render(request,'index1.html',{'posts':posts}) 163 164 165 """ 166 167 反向操作:关联的表名(想取的)小写加_(下划线) 168 userinfo_set.all() 169 """ 170 171 def custom(request): 172 all_count=models.UserInfo.objects.all().count()#总个数 173 # print(all_count) 174 current_page=request.GET.get('page') 175 print(current_page) 176 page_info=pageinfo(current_page,all_count,10,11)#对象 177 user_list=models.UserInfo.objects.all()[page_info.start():page_info.end()]#注意是冒号,表示取的范围 178 return render(request,'custom.html',{'user_list':user_list,'page_info':page_info}) 179 180 class pageinfo(object): 181 def __init__(self,current_page,all_count,per_page,show_page): 182 """ 183 :param current_page: 184 :param all_count: 数据库中的记录总条数 185 :param per_page: 每页显示的行数 186 187 """ 188 try: 189 self.current_page=int(current_page) 190 191 except Exception as e: 192 print(e) 193 self.current_page=1 194 self.per_page=per_page 195 196 self.show_page=show_page 197 198 a,b=divmod(all_count,per_page) 199 200 if b: 201 a=a+1 202 203 self.all_page=a#总页码 204 half=int((show_page-1)/2) 205 206 self.begin=self.current_page-half 207 if self.current_page<=5: 208 self.begin=1 209 self.stop=self.current_page+half+1 210 if self.current_page>=self.all_page-half: 211 self.stop=self.all_page+1 212 213 def start(self): 214 return (self.current_page-1)*self.per_page 215 216 def end(self): 217 return self.current_page*self.per_page 218 219 def pager(self): 220 # v="<a href='/custom.html?page=1'>1</a>" 221 # print('=====================ok======================') 222 # return v 223 page_list=[] 224 if self.current_page==1: 225 prev="<li><a href='#'>上一页</a></li>" 226 else:prev= "<li><a href='/custom.html?page=%s'>上一页</a></li>"%(self.current_page-1) 227 228 page_list.append(prev) 229 230 231 if self.current_page==self.all_page: 232 next="<li><a href='#'>下一页</a></li>" 233 else:next="<li><a href='/custom.html?page=%s'>下一页</a></li>"%(self.current_page+1) 234 page_list.append(next) 235 236 237 for i in range(self.begin,self.stop): 238 if i==self.current_page: 239 temp="<li class='active'><a href='/custom.html?page=%s'>%s</a></li>"%(i,i) 240 else: 241 temp = "<li><a href='/custom.html?page=%s'>%s</a></li>" % (i, i) 242 243 # temp="<a style='display:inline-block;padding:5px' href='/custom.html?page=%s'>%s</a>"%(i,i) 244 # elif self.current_page-5==i: 245 # temp="<a style='display:inline-block;padding:5px' href='/custom.html?page=%s'>上一页</a>"%(self.current_page-1,) 246 # else: 247 # temp="<a style='display:inline-block;padding:5px' href='/custom.html?page=%s'>%s</a>"%(i,i) 248 249 page_list.append(temp) 250 print(''.join(page_list)) 251 return ''.join(page_list)#把列表用字符串传 252 253 254 def test01(request): 255 # user_list=models.UserInfo.objects.all().order_by('-ut_id',)#-ut_id 从大到小 256 from django.db.models import Count,Sum,Max,Min,F,Q 257 user_list=models.UserInfo.objects.values('ut_id').annotate(number=Count('nid')).filter(number__gt=3) 258 """ 259 F 在update时,取数据库里面原来的数 260 261 ================================================================================= 262 Q 263 # Q 参考资产管理 :加入设备,有很多台设备,属性为已使用,公司为不同公司。每个类中用|即or连接,不同类用and &连接 264 # 265 *********************************************************************************** 266 # 方式一: 267 # Q(nid__gt=10) 268 # Q(nid=8) | Q(nid__gt=10)-------->>>>>>filter('nid'=8,'nid_gt'=10) 方式一是不必要的,一般应用都是方式二 269 # Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption='root') 270 ********************************************************************************** 271 # 方式二:采用对象的方式 272 # con = Q() 273 274 # q1 = Q() 275 # q1.connector = 'OR' 276 # q1.children.append(('id', 1)) 277 # q1.children.append(('id', 10)) 278 # q1.children.append(('id', 9)) 279 # q2 = Q() 280 281 # q2.connector = 'OR' 282 # q2.children.append(('c1', 1)) 283 # q2.children.append(('c1', 10)) 284 # q2.children.append(('c1', 9)) 285 # con.add(q1, 'AND') 286 # con.add(q2, 'AND') 287 # 288 # models.Tb1.objects.filter(con) 289 ================================================================================================ 290 extra 291 292 # extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None) 293 294 # Entry.objects.extra(select={'new_id': "select col from sometable where othercol > %s"}, select_params=(1,)) 295 296 ----------->>> 映射 select:里面写sql语句 select_param: sql中的参数 297 298 # Entry.objects.extra(where=['headline=%s'], params=['Lennon']) 299 300 ----------->>> 条件 where :联想到filter, params:where中参数 301 302 # Entry.objects.extra(select={'new_id': "select id from tb where id > %s"}, select_params=(1,), order_by=['-nid'],table=['usertype']) 303 304 ----------->>> order: 排序 ,-nid就是倒序排; 305 306 ----------->>>表名 table :加一个表, select * from 本表,usertype(其他表) 307 308 ================================================================================================ 309 # 执行原生SQL 310 # 311 # from django.db import connection, connections 312 # cursor = connection.cursor() # cursor = connections['default'].cursor()#DATABASE里面的default默认连接sqlite 313 # cursor.execute('SELECT * from auth_user where id = %s', [1]); 314 # row = cursor.fetchone() 315 316 317 ============================================================================ 318 def aggregate(self, *args, **kwargs): 319 # 聚合函数,获取字典类型聚合结果 320 from django.db.models import Count, Avg, Max, Min, Sum 321 result = models.UserInfo.objects.aggregate(k=Count('u_id', distinct=True), n=Count('nid')) 322 ===> {'k': 3, 'n': 4} 323 324 =============================================================================== 325 def create(self, **kwargs): 326 # 创建对象 327 res=models.usertype.create(**{'title':'超级用户'}) 328 res.id:last_row_id 329 330 331 ================================================================================== 332 select_related('xxx'):第一次连接的时候就主动做连表操作,提升性能 333 334 335 336 337 338 339 340 """ 341 models.UserInfo.objects.all().update(ut_id=F('ut_id')-1)#某一列减一 342 # user_list = models.UserInfo.objects.values('ut_id').annotate(number=Sum('nid')) 343 print(user_list) 344 #<QuerySet [{'ut_id': 1, 'xxx': 1}, {'ut_id': 2, 'xxx': 4}, {'ut_id': 3, 'xxx': 2}]> 345 #SELECT `app01_userinfo`.`ut_id`, COUNT(`app01_userinfo`.`nid`) AS `xxx` FROM `app01_userinfo` GROUP BY `app01_userinfo`.`ut_id` ORDER BY NULL 346 return HttpResponse('==========okk========') 347 348 def test02(request): 349 # boy_info=[ 350 # models.boy(name='邱舒庭'), 351 # models.boy(name='马家军'), 352 # models.boy(name='钱jb'), 353 # models.boy(name='罗海波'), 354 # models.boy(name='陆家新') 355 # 356 # ] 357 # 358 # models.boy.objects.bulk_create(boy_info,5) 359 # 360 # girl_info = [ 361 # models.girl(nick='小鱼'), 362 # models.girl(nick='小虾'), 363 # models.girl(nick='小猫'), 364 # models.girl(nick='小狗'), 365 # models.girl(nick='小雨') 366 # 367 # ] 368 # 369 # models.girl.objects.bulk_create(girl_info,5) 370 # models.lov.objects.create(b_id=2,g_id=1) 371 # models.lov.objects.create(b_id=2,g_id=2) 372 # models.lov.objects.create(b_id=3,g_id=3) 373 # models.lov.objects.create(b_id=2,g_id=3) 374 # obj=models.boy.objects.filter(name='马家军').first() 375 # love_list=obj.lov_set.all() 376 # print(love_list) 377 # for row in love_list: 378 # print(row.g.nick) 379 # love_list=models.lov.objects.filter(b__id='2').select_related('g') 380 # for item in love_list: 381 # print(item.g.nick) 382 # 383 # return HttpResponse('============okk==================') 384 385 386 387 obj=models.boy.objects.filter(id=2).first()#不加first ,就是一个queryset格式,里面封装了对象,用first取出对象 388 print(obj.name) 389 list=obj.m.all() 390 for row in list: 391 print(row.nick) 392 393 394 return HttpResponse('*************okk**************') 395 396 397 398 # love_list=obj.m.all() 399 # print(love_list) 400 401 """ 402 csrf: 跨站请求伪造 403 1.form 表单中添加 404 {%csrf_token%} 405 406 2.全站禁用 在settings里面注释掉CSRF 407 408 3.局部禁用 409 410 添加装饰器 411 from django.views.decorators.csrf import csrf_exempt 412 @csrf_exempt 413 414 4.局部使用 415 from django.views.decorators.csrf import csrf_protect 416 @csrf_protect 417 418 5.CBV:在类上加 419 420 @method_decorator(csrf_protect,name='dispatch') 421 422 """ 423 424 def test03(request): 425 return render(request,'test03.html',{'userinfo':{'k1':'qst','k2':'v2'}}) 426 427 428 429 """ 430 3.session 431 432 433 cookie:保存在客户浏览器上的键值对 434 435 session: 436 保存在服务端的数据(本质是键值对) 437 应用:依赖cookie 438 作用:保持回话(web网站) 439 好处:敏感信息不会保存在用户电脑上 440 441 request.session 442 -增删改 443 -获取随机字符串 444 -主动设置超时时间 445 446 447 448 449 450 451 452 453 454 455 456 457 4.中间件 458 459 """ 460 461 def test04(request): 462 if request.method=='GET': 463 return render(request,'test04.html') 464 else: 465 username=request.POST.get('info') 466 password=request.POST.get('pwd') 467 print(username,password) 468 if username=='alex' and password=='123': 469 #1.生成随机字符串 470 #2.cookie发给客户端 471 #3.服务端保存 {随机字符串1:{'usename':'alex'......}} 472 request.session['username']='alex' 473 request.session['password']='123' 474 475 return redirect('/verify.html') 476 else: 477 return render(request,'test04.html',{'msg':'用户名或密码错误'}) 478 def verify(request): 479 """ 480 获取客户端cookie中的随机字符串 481 去session中查找有没有随机字符串 482 去session对应key的value中查看是否有username 483 484 """ 485 v=request.session.get('username') 486 487 488 if v: 489 return HttpResponse('登录成功 %s 先生/女士'%v) 490 491 492 else:return redirect('/test04.html')