Best Python code snippet using slash
views.py
Source:views.py
1from django.shortcuts import render,redirect2from django.views.generic import View3from Academics.models import Academics,Feedback,Innovation,UG,PG,ExtraCurricular,AllClear,ThreeClear,Article,Competitive,Startups,Awards,Prizes,Internship,OnlineCertification4from skct.models import Proof,Staff,Hod,It,Cse,Mech,Eee,Ece,Ice,Civil,Mba,Sh5from django.contrib import messages6from django.contrib.auth import logout7from django.contrib.auth import get_user8from django.http import request,HttpResponse9from django.contrib.auth.models import User,Group1011# Create your views here.121314def delete(request,pk):15 if (request.method) == 'POST':16 name =Proof.objects.get(pk=pk)17 name.delete()18 return redirect('profile')1920def delete2(request,pk):21 if (request.method) == 'POST':22 name =Academics.objects.get(pk=pk)23 name.delete()24 print(pk)25 return redirect('responses_view')2627def delete3(request,pk):28 if (request.method) == 'POST':29 name =Feedback.objects.get(pk=pk)30 name.delete()31 print(pk)32 return redirect('responses_view')3334def delete4(request,pk):35 if (request.method) == 'POST':36 name =Innovation.objects.get(pk=pk)37 name.delete()38 print(pk)39 return redirect('responses_view')4041def delete5(request,pk):42 if (request.method) == 'POST':43 name =UG.objects.get(pk=pk)44 name.delete()45 print(pk)46 return redirect('responses_view')4748def delete6(request,pk):49 if (request.method) == 'POST':50 name =PG.objects.get(pk=pk)51 name.delete()52 print(pk)53 return redirect('responses_view')5455def delete7(request,pk):56 if (request.method) == 'POST':57 name =ExtraCurricular.objects.get(pk=pk)58 name.delete()59 print(pk)60 return redirect('responses_view')6162def delete8(request,pk):63 if (request.method) == 'POST':64 name =AllClear.objects.get(pk=pk)65 name.delete()66 print(pk)67 return redirect('responses_view')6869def delete9(request,pk):70 if (request.method) == 'POST':71 name =ThreeClear.objects.get(pk=pk)72 name.delete()73 print(pk)74 return redirect('responses_view')7576def delete10(request,pk):77 if (request.method) == 'POST':78 name =Article.objects.get(pk=pk)79 name.delete()80 print(pk)81 return redirect('responses_view')8283def delete11(request,pk):84 if (request.method) == 'POST':85 name =Competitive.objects.get(pk=pk)86 name.delete()87 print(pk)88 return redirect('responses_view')8990def delete12(request,pk):91 if (request.method) == 'POST':92 name =Startups.objects.get(pk=pk)93 name.delete()94 print(pk)95 return redirect('responses_view')9697def delete13(request,pk):98 if (request.method) == 'POST':99 name =Awards.objects.get(pk=pk)100 name.delete()101 print(pk)102 return redirect('responses_view')103104def delete14(request,pk):105 if (request.method) == 'POST':106 name =Prizes.objects.get(pk=pk)107 name.delete()108 print(pk)109 return redirect('responses_view')110111def delete15(request,pk):112 if (request.method) == 'POST':113 name =Internship.objects.get(pk=pk)114 name.delete()115 print(pk)116 return redirect('responses_view')117118def delete16(request,pk):119 if (request.method) == 'POST':120 name =OnlineCertification.objects.get(pk=pk)121 name.delete()122 print(pk)123 return redirect('responses_view')124125126#------------------------------Delete---------------------------------------------127128129class AcademicView(View):130 template_name =["index2.html"]131 def get(self,request):132 userhere=get_user(request)133 flag=0134 flag2=0135 li = [i for i in range(1,11)]136 li.reverse()137138 if(Hod.objects.all().filter(name=userhere)):139 flag2=1140 return render(request,self.template_name[0],{'flag2':flag2,'li':li})141 else:142 return render(request,self.template_name[0],{'li':li})143144 def post(self,request):145 if(request.POST.get('des')):146 name =Academics()147 name.des=request.POST.get('des')148 name.pdf=request.FILES.get('upload')149 name.user=get_user(request)150 name.points=request.POST.get('dropdown')151 if(It.objects.all().filter(name=get_user(request))):152 name.dept = "IT"153 elif(Cse.objects.all().filter(name=get_user(request))):154 name.dept = "CSE"155 elif(Mech.objects.all().filter(name=get_user(request))):156 name.dept = "MECH"157 elif(Eee.objects.all().filter(name=get_user(request))):158 name.dept = "EEE"159 elif(Ece.objects.all().filter(name=get_user(request))):160 name.dept = "ECE"161 elif(Ice.objects.all().filter(name=get_user(request))):162 name.dept = "ICE"163 elif(Civil.objects.all().filter(name=get_user(request))):164 name.dept = "CIVIL"165 elif(Mba.objects.all().filter(name=get_user(request))):166 name.dept = "MBA"167 elif(Sh.objects.all().filter(name=get_user(request))):168 name.dept = "SH"169 name.save()170 171 userhere=get_user(request)172 ob=Academics.objects.all().filter(user=userhere)173 li = [i for i in range(1,11)]174 li.reverse()175176 if(Hod.objects.all().filter(name=userhere)):177 flag2=1178 return render(request,self.template_name[0],{'flag2':flag2,'li':li})179 return render(request,self.template_name[0],{'li':li,})180181 elif(request.POST.get('des1')):182 name1 = Feedback()183 name1.des = request.POST.get('des1')184 name1.pdf = request.FILES.get('upload1')185 name1.user = get_user(request)186 name1.points = request.POST.get('dropdown1')187 if(It.objects.all().filter(name=get_user(request))):188 name1.dept = "IT"189 elif(Cse.objects.all().filter(name=get_user(request))):190 name1.dept = "CSE"191 elif(Mech.objects.all().filter(name=get_user(request))):192 name1.dept = "MECH"193 elif(Eee.objects.all().filter(name=get_user(request))):194 name1.dept = "EEE"195 elif(Ece.objects.all().filter(name=get_user(request))):196 name1.dept = "ECE"197 elif(Ice.objects.all().filter(name=get_user(request))):198 name1.dept = "ICE"199 elif(Civil.objects.all().filter(name=get_user(request))):200 name1.dept = "CIVIL"201 elif(Mba.objects.all().filter(name=get_user(request))):202 name1.dept = "MBA"203 elif(Sh.objects.all().filter(name=get_user(request))):204 name1.dept = "SH"205 name1.save()206207 userhere=get_user(request)208 ob=Innovation.objects.all().filter(user=userhere)209 li = [i for i in range(1,11)]210 li.reverse()211212 if(Hod.objects.all().filter(name=userhere)):213 flag2=1214 return render(request,self.template_name[0],{'flag2':flag2,'li':li})215 return render(request,self.template_name[0],{'li':li,})216217 elif(request.POST.get('des2')):218 name2 = Innovation()219 name2.des = request.POST.get('des2')220 name2.pdf = request.FILES.get('upload2')221 name2.user = get_user(request)222 name2.points = request.POST.get('dropdown2')223 if(It.objects.all().filter(name=get_user(request))):224 name2.dept = "IT"225 elif(Cse.objects.all().filter(name=get_user(request))):226 name2.dept = "CSE"227 elif(Mech.objects.all().filter(name=get_user(request))):228 name2.dept = "MECH"229 elif(Eee.objects.all().filter(name=get_user(request))):230 name2.dept = "EEE"231 elif(Ece.objects.all().filter(name=get_user(request))):232 name2.dept = "ECE"233 elif(Ice.objects.all().filter(name=get_user(request))):234 name2.dept = "ICE"235 elif(Civil.objects.all().filter(name=get_user(request))):236 name2.dept = "CIVIL"237 elif(Mba.objects.all().filter(name=get_user(request))):238 name2.dept = "MBA"239 elif(Sh.objects.all().filter(name=get_user(request))):240 name2.dept = "SH"241 name2.save()242243 userhere=get_user(request)244 ob=Innovation.objects.all().filter(user=userhere)245 li = [i for i in range(1,11)]246 li.reverse()247248 if(Hod.objects.all().filter(name=userhere)):249 flag2=1250 return render(request,self.template_name[0],{'flag2':flag2,'li':li})251 return render(request,self.template_name[0],{'li':li,})252253 elif(request.POST.get('des3')):254 name3 = UG()255 name3.des = request.POST.get('des3')256 name3.pdf = request.FILES.get('upload3')257 name3.user = get_user(request)258 name3.points = request.POST.get('dropdown3')259 if(It.objects.all().filter(name=get_user(request))):260 name3.dept = "IT"261 elif(Cse.objects.all().filter(name=get_user(request))):262 name3.dept = "CSE"263 elif(Mech.objects.all().filter(name=get_user(request))):264 name3.dept = "MECH"265 elif(Eee.objects.all().filter(name=get_user(request))):266 name3.dept = "EEE"267 elif(Ece.objects.all().filter(name=get_user(request))):268 name3.dept = "ECE"269 elif(Ice.objects.all().filter(name=get_user(request))):270 name3.dept = "ICE"271 elif(Civil.objects.all().filter(name=get_user(request))):272 name3.dept = "CIVIL"273 elif(Mba.objects.all().filter(name=get_user(request))):274 name3.dept = "MBA"275 elif(Sh.objects.all().filter(name=get_user(request))):276 name3.dept = "SH"277 name3.save()278279 userhere=get_user(request)280 ob=UG.objects.all().filter(user=userhere)281 li = [i for i in range(1,11)]282 li.reverse()283284 if(Hod.objects.all().filter(name=userhere)):285 flag2=1286 return render(request,self.template_name[0],{'flag2':flag2,'li':li})287 return render(request,self.template_name[0],{'li':li,})288 289 elif(request.POST.get('des4')):290 name4 = PG()291 name4.des = request.POST.get('des4')292 name4.pdf = request.FILES.get('upload4')293 name4.user = get_user(request)294 name4.points = request.POST.get('dropdown4')295 if(It.objects.all().filter(name=get_user(request))):296 name4.dept = "IT"297 elif(Cse.objects.all().filter(name=get_user(request))):298 name4.dept = "CSE"299 elif(Mech.objects.all().filter(name=get_user(request))):300 name4.dept = "MECH"301 elif(Eee.objects.all().filter(name=get_user(request))):302 name4.dept = "EEE"303 elif(Ece.objects.all().filter(name=get_user(request))):304 name4.dept = "ECE"305 elif(Ice.objects.all().filter(name=get_user(request))):306 name4.dept = "ICE"307 elif(Civil.objects.all().filter(name=get_user(request))):308 name4.dept = "CIVIL"309 elif(Mba.objects.all().filter(name=get_user(request))):310 name4.dept = "MBA"311 elif(Sh.objects.all().filter(name=get_user(request))):312 name4.dept = "SH"313 name4.save()314315 userhere=get_user(request)316 ob=PG.objects.all().filter(user=userhere)317 li = [i for i in range(1,11)]318 li.reverse()319320 if(Hod.objects.all().filter(name=userhere)):321 flag2=1322 return render(request,self.template_name[0],{'flag2':flag2,'li':li})323 return render(request,self.template_name[0],{'li':li,})324325 elif(request.POST.get('des5')):326 name5 = ExtraCurricular()327 name5.des = request.POST.get('des5')328 name5.pdf = request.FILES.get('upload5')329 name5.user = get_user(request)330 name5.points = request.POST.get('dropdown5')331 if(It.objects.all().filter(name=get_user(request))):332 name5.dept = "IT"333 elif(Cse.objects.all().filter(name=get_user(request))):334 name5.dept = "CSE"335 elif(Mech.objects.all().filter(name=get_user(request))):336 name5.dept = "MECH"337 elif(Eee.objects.all().filter(name=get_user(request))):338 name5.dept = "EEE"339 elif(Ece.objects.all().filter(name=get_user(request))):340 name5.dept = "ECE"341 elif(Ice.objects.all().filter(name=get_user(request))):342 name5.dept = "ICE"343 elif(Civil.objects.all().filter(name=get_user(request))):344 name5.dept = "CIVIL"345 elif(Mba.objects.all().filter(name=get_user(request))):346 name5.dept = "MBA"347 elif(Sh.objects.all().filter(name=get_user(request))):348 name5.dept = "SH"349 name5.save()350351 userhere=get_user(request)352 ob=ExtraCurricular.objects.all().filter(user=userhere)353 li = [i for i in range(1,11)]354 li.reverse()355356 if(Hod.objects.all().filter(name=userhere)):357 flag2=1358 return render(request,self.template_name[0],{'flag2':flag2,'li':li})359 return render(request,self.template_name[0],{'li':li,})360361 elif(request.POST.get('des6')):362 name6 = AllClear()363 name6.des = request.POST.get('des6')364 name6.pdf = request.FILES.get('upload6')365 name6.user = get_user(request)366 name6.points = request.POST.get('dropdown6')367 if(It.objects.all().filter(name=get_user(request))):368 name6.dept = "IT"369 elif(Cse.objects.all().filter(name=get_user(request))):370 name6.dept = "CSE"371 elif(Mech.objects.all().filter(name=get_user(request))):372 name6.dept = "MECH"373 elif(Eee.objects.all().filter(name=get_user(request))):374 name6.dept = "EEE"375 elif(Ece.objects.all().filter(name=get_user(request))):376 name6.dept = "ECE"377 elif(Ice.objects.all().filter(name=get_user(request))):378 name6.dept = "ICE"379 elif(Civil.objects.all().filter(name=get_user(request))):380 name6.dept = "CIVIL"381 elif(Mba.objects.all().filter(name=get_user(request))):382 name6.dept = "MBA"383 elif(Sh.objects.all().filter(name=get_user(request))):384 name6.dept = "SH"385 name6.save()386387 userhere=get_user(request)388 ob=AllClear.objects.all().filter(user=userhere)389 li = [i for i in range(1,11)]390 li.reverse()391392 if(Hod.objects.all().filter(name=userhere)):393 flag2=1394 return render(request,self.template_name[0],{'flag2':flag2,'li':li})395 return render(request,self.template_name[0],{'li':li,})396397 elif(request.POST.get('des7')):398 name7 = ThreeClear()399 name7.des = request.POST.get('des7')400 name7.pdf = request.FILES.get('upload7')401 name7.user = get_user(request)402 name7.points = request.POST.get('dropdown7')403 if(It.objects.all().filter(name=get_user(request))):404 name7.dept = "IT"405 elif(Cse.objects.all().filter(name=get_user(request))):406 name7.dept = "CSE"407 elif(Mech.objects.all().filter(name=get_user(request))):408 name7.dept = "MECH"409 elif(Eee.objects.all().filter(name=get_user(request))):410 name7.dept = "EEE"411 elif(Ece.objects.all().filter(name=get_user(request))):412 name7.dept = "ECE"413 elif(Ice.objects.all().filter(name=get_user(request))):414 name7.dept = "ICE"415 elif(Civil.objects.all().filter(name=get_user(request))):416 name7.dept = "CIVIL"417 elif(Mba.objects.all().filter(name=get_user(request))):418 name7.dept = "MBA"419 elif(Sh.objects.all().filter(name=get_user(request))):420 name7.dept = "SH"421 name7.save()422423 userhere=get_user(request)424 ob=ThreeClear.objects.all().filter(user=userhere)425 li = [i for i in range(1,11)]426 li.reverse()427428 if(Hod.objects.all().filter(name=userhere)):429 flag2=1430 return render(request,self.template_name[0],{'flag2':flag2,'li':li})431 return render(request,self.template_name[0],{'li':li,})432433 elif(request.POST.get('des8')):434 name8 = Article()435 name8.des = request.POST.get('des8')436 name8.pdf = request.FILES.get('upload8')437 name8.user = get_user(request)438 name8.points = request.POST.get('dropdown8')439 if(It.objects.all().filter(name=get_user(request))):440 name8.dept = "IT"441 elif(Cse.objects.all().filter(name=get_user(request))):442 name8.dept = "CSE"443 elif(Mech.objects.all().filter(name=get_user(request))):444 name8.dept = "MECH"445 elif(Eee.objects.all().filter(name=get_user(request))):446 name8.dept = "EEE"447 elif(Ece.objects.all().filter(name=get_user(request))):448 name8.dept = "ECE"449 elif(Ice.objects.all().filter(name=get_user(request))):450 name8.dept = "ICE"451 elif(Civil.objects.all().filter(name=get_user(request))):452 name8.dept = "CIVIL"453 elif(Mba.objects.all().filter(name=get_user(request))):454 name8.dept = "MBA"455 elif(Sh.objects.all().filter(name=get_user(request))):456 name8.dept = "SH"457 name8.save()458459 userhere=get_user(request)460 ob=Article.objects.all().filter(user=userhere)461 li = [i for i in range(1,11)]462 li.reverse()463464 if(Hod.objects.all().filter(name=userhere)):465 flag2=1466 return render(request,self.template_name[0],{'flag2':flag2,'li':li})467 return render(request,self.template_name[0],{'li':li,})468469 elif(request.POST.get('des9')):470 name9 = Competitive()471 name9.des = request.POST.get('des9')472 name9.pdf = request.FILES.get('upload9')473 name9.user = get_user(request)474 name9.points = request.POST.get('dropdown9')475 if(It.objects.all().filter(name=get_user(request))):476 name9.dept = "IT"477 elif(Cse.objects.all().filter(name=get_user(request))):478 name9.dept = "CSE"479 elif(Mech.objects.all().filter(name=get_user(request))):480 name9.dept = "MECH"481 elif(Eee.objects.all().filter(name=get_user(request))):482 name9.dept = "EEE"483 elif(Ece.objects.all().filter(name=get_user(request))):484 name9.dept = "ECE"485 elif(Ice.objects.all().filter(name=get_user(request))):486 name9.dept = "ICE"487 elif(Civil.objects.all().filter(name=get_user(request))):488 name9.dept = "CIVIL"489 elif(Mba.objects.all().filter(name=get_user(request))):490 name9.dept = "MBA"491 elif(Sh.objects.all().filter(name=get_user(request))):492 name9.dept = "SH"493 name9.save()494495 userhere=get_user(request)496 ob=Competitive.objects.all().filter(user=userhere)497 li = [i for i in range(1,11)]498 li.reverse()499500 if(Hod.objects.all().filter(name=userhere)):501 flag2=1502 return render(request,self.template_name[0],{'flag2':flag2,'li':li})503 return render(request,self.template_name[0],{'li':li,})504505 elif(request.POST.get('des10')):506 name10 = Startups()507 name10.des = request.POST.get('des10')508 name10.pdf = request.FILES.get('upload10')509 name10.user = get_user(request)510 name10.points = request.POST.get('dropdown10')511 if(It.objects.all().filter(name=get_user(request))):512 name10.dept = "IT"513 elif(Cse.objects.all().filter(name=get_user(request))):514 name10.dept = "CSE"515 elif(Mech.objects.all().filter(name=get_user(request))):516 name10.dept = "MECH"517 elif(Eee.objects.all().filter(name=get_user(request))):518 name10.dept = "EEE"519 elif(Ece.objects.all().filter(name=get_user(request))):520 name10.dept = "ECE"521 elif(Ice.objects.all().filter(name=get_user(request))):522 name10.dept = "ICE"523 elif(Civil.objects.all().filter(name=get_user(request))):524 name10.dept = "CIVIL"525 elif(Mba.objects.all().filter(name=get_user(request))):526 name10.dept = "MBA"527 elif(Sh.objects.all().filter(name=get_user(request))):528 name10.dept = "SH"529 name10.save()530531 userhere=get_user(request)532 ob=Startups.objects.all().filter(user=userhere)533 li = [i for i in range(1,11)]534 li.reverse()535536 if(Hod.objects.all().filter(name=userhere)):537 flag2=1538 return render(request,self.template_name[0],{'flag2':flag2,'li':li})539 return render(request,self.template_name[0],{'li':li,})540541 elif(request.POST.get('des11')):542 name11 = Awards()543 name11.des = request.POST.get('des11')544 name11.pdf = request.FILES.get('upload11')545 name11.user = get_user(request)546 name11.points = request.POST.get('dropdown11')547 if(It.objects.all().filter(name=get_user(request))):548 name11.dept = "IT"549 elif(Cse.objects.all().filter(name=get_user(request))):550 name11.dept = "CSE"551 elif(Mech.objects.all().filter(name=get_user(request))):552 name11.dept = "MECH"553 elif(Eee.objects.all().filter(name=get_user(request))):554 name11.dept = "EEE"555 elif(Ece.objects.all().filter(name=get_user(request))):556 name11.dept = "ECE"557 elif(Ice.objects.all().filter(name=get_user(request))):558 name11.dept = "ICE"559 elif(Civil.objects.all().filter(name=get_user(request))):560 name11.dept = "CIVIL"561 elif(Mba.objects.all().filter(name=get_user(request))):562 name11.dept = "MBA"563 elif(Sh.objects.all().filter(name=get_user(request))):564 name11.dept = "SH"565 name11.save()566567 userhere=get_user(request)568 ob=Awards.objects.all().filter(user=userhere)569 li = [i for i in range(1,11)]570 li.reverse()571572 if(Hod.objects.all().filter(name=userhere)):573 flag2=1574 return render(request,self.template_name[0],{'flag2':flag2,'li':li})575 return render(request,self.template_name[0],{'li':li,})576577 elif(request.POST.get('des12')):578 name12 = Prizes()579 name12.des = request.POST.get('des12')580 name12.pdf = request.FILES.get('upload12')581 name12.user = get_user(request)582 name12.points = request.POST.get('dropdown12')583 if(It.objects.all().filter(name=get_user(request))):584 name12.dept = "IT"585 elif(Cse.objects.all().filter(name=get_user(request))):586 name12.dept = "CSE"587 elif(Mech.objects.all().filter(name=get_user(request))):588 name12.dept = "MECH"589 elif(Eee.objects.all().filter(name=get_user(request))):590 name12.dept = "EEE"591 elif(Ece.objects.all().filter(name=get_user(request))):592 name12.dept = "ECE"593 elif(Ice.objects.all().filter(name=get_user(request))):594 name12.dept = "ICE"595 elif(Civil.objects.all().filter(name=get_user(request))):596 name12.dept = "CIVIL"597 elif(Mba.objects.all().filter(name=get_user(request))):598 name12.dept = "MBA"599 elif(Sh.objects.all().filter(name=get_user(request))):600 name12.dept = "SH"601 name12.save()602603 userhere=get_user(request)604 ob=Prizes.objects.all().filter(user=userhere)605 li = [i for i in range(1,11)]606 li.reverse()607608 if(Hod.objects.all().filter(name=userhere)):609 flag2=1610 return render(request,self.template_name[0],{'flag2':flag2,'li':li})611 return render(request,self.template_name[0],{'li':li,})612613 elif(request.POST.get('des13')):614 name13 = Internship()615 name13.des = request.POST.get('des13')616 name13.pdf = request.FILES.get('upload13')617 name13.user = get_user(request)618 name13.points = request.POST.get('dropdown13')619 if(It.objects.all().filter(name=get_user(request))):620 name13.dept = "IT"621 elif(Cse.objects.all().filter(name=get_user(request))):622 name13.dept = "CSE"623 elif(Mech.objects.all().filter(name=get_user(request))):624 name13.dept = "MECH"625 elif(Eee.objects.all().filter(name=get_user(request))):626 name13.dept = "EEE"627 elif(Ece.objects.all().filter(name=get_user(request))):628 name13.dept = "ECE"629 elif(Ice.objects.all().filter(name=get_user(request))):630 name13.dept = "ICE"631 elif(Civil.objects.all().filter(name=get_user(request))):632 name13.dept = "CIVIL"633 elif(Mba.objects.all().filter(name=get_user(request))):634 name13.dept = "MBA"635 elif(Sh.objects.all().filter(name=get_user(request))):636 name13.dept = "SH"637 name13.save()638639 userhere=get_user(request)640 ob=Internship.objects.all().filter(user=userhere)641 li = [i for i in range(1,11)]642 li.reverse()643644 if(Hod.objects.all().filter(name=userhere)):645 flag2=1646 return render(request,self.template_name[0],{'flag2':flag2,'li':li})647 return render(request,self.template_name[0],{'li':li,})648649 elif(request.POST.get('des14')):650 name14 = OnlineCertification()651 name14.des = request.POST.get('des14')652 name14.pdf = request.FILES.get('upload14')653 name14.user = get_user(request)654 name14.points = request.POST.get('dropdown14')655 if(It.objects.all().filter(name=get_user(request))):656 name14.dept = "IT"657 elif(Cse.objects.all().filter(name=get_user(request))):658 name14.dept = "CSE"659 elif(Mech.objects.all().filter(name=get_user(request))):660 name14.dept = "MECH"661 elif(Eee.objects.all().filter(name=get_user(request))):662 name14.dept = "EEE"663 elif(Ece.objects.all().filter(name=get_user(request))):664 name14.dept = "ECE"665 elif(Ice.objects.all().filter(name=get_user(request))):666 name14.dept = "ICE"667 elif(Civil.objects.all().filter(name=get_user(request))):668 name14.dept = "CIVIL"669 elif(Mba.objects.all().filter(name=get_user(request))):670 name14.dept = "MBA"671 elif(Sh.objects.all().filter(name=get_user(request))):672 name14.dept = "SH"673 name14.save()674 userhere=get_user(request)675 ob=OnlineCertification.objects.all().filter(user=userhere)676 li = [i for i in range(1,11)]677 li.reverse()678679 if(Hod.objects.all().filter(name=userhere)):680 flag2=1681 return render(request,self.template_name[0],{'flag2':flag2,'li':li})682 return render(request,self.template_name[0],{'li':li,})683684685686class AcadListView(View):687 template_name = "academics_list.html"688 def get(self,request):689 flag=0690 if(Hod.objects.all().filter(name=get_user(request)) and It.objects.all().filter(name=get_user(request))):691 li = It.objects.all()692 flag=1693 return render(request,self.template_name,{'i':li,'flag2':flag})694695 def post(self,request):696 flag=0697 if(Hod.objects.all().filter(name=get_user(request)) and It.objects.all().filter(name=get_user(request))):698 li = It.objects.all()699 flag=1700 return render(request,self.template_name,{'i':li,'flag2':flag})701702class FacAcadListView(View):703 template_name = "fac_academics_list.html"704 flag2=0705 def get(self,request,user,pk):706 user1=user707 if(Hod.objects.all().filter(name=get_user(request))):708 i = Academics.objects.all().filter(user=user)709 i2 = Feedback.objects.all().filter(user=user)710 i3 = Innovation.objects.all().filter(user=user)711 i4 = UG.objects.all().filter(user=user)712 i5 = PG.objects.all().filter(user=user)713 i6 = ExtraCurricular.objects.all().filter(user=user)714 i7 = AllClear.objects.all().filter(user=user)715 i8 = ThreeClear.objects.all().filter(user= user)716 i9 = Article.objects.all().filter(user=user)717 i10 = Competitive.objects.all().filter(user=user)718 i11 = Startups.objects.all().filter(user=user)719 i12 = Awards.objects.all().filter(user=user)720 i13 = Prizes.objects.all().filter(user=user)721 i14 = Internship.objects.all().filter(user=user)722 i15 = OnlineCertification.objects.all().filter(user=user)723 flag2=1724 return render(request,self.template_name,{'i15':i15,'i14':i14,'i13':i13,'i12':i12,'i11':i11,'i10':i10,'i9':i9,'i8':i8,'i6':i6,'i7':i7,'i':i,'i2':i2,'i3':i3,'i4':i4,'i5':i5,'flag2':flag2,'user1':user1})725726 def post(self,request,user,pk):727 user1=user728 if(Hod.objects.all().filter(name=get_user(request))):729 i = Academics.objects.all().filter(user = user)730 i2 = Feedback.objects.all().filter(user=user)731 i3 = Innovation.objects.all().filter(user=user)732 i4 = UG.objects.all().filter(user=user)733 i5 = PG.objects.all().filter(user=user)734 i6 = ExtraCurricular.objects.all().filter(user=user)735 i7 = AllClear.objects.all().filter(user=user)736 i8 = ThreeClear.objects.all().filter(user=user)737 i9 = Article.objects.all().filter(user=user)738 i10 = Competitive.objects.all().filter(user=user)739 i11 = Startups.objects.all().filter(user=user)740 i12 = Awards.objects.all().filter(user=user)741 i13 = Prizes.objects.all().filter(user=user)742 i14 = Internship.objects.all().filter(user=user)743 i15 = OnlineCertification.objects.all().filter(user=user)744 value=request.POST.get('points')745 value1=request.POST.get('points1')746 value2=request.POST.get('points2')747 value3=request.POST.get('points3')748 value4=request.POST.get('points4')749 value5=request.POST.get('points5')750 value6=request.POST.get('points6')751 value7=request.POST.get('points7')752 value8=request.POST.get('points8')753 value9=request.POST.get('points9')754 value10=request.POST.get('points10')755 value11=request.POST.get('points11')756 value12=request.POST.get('points12')757 value13=request.POST.get('points13')758 value14=request.POST.get('points14')759 if(request.POST.get('points')):760 a=Academics.objects.filter(pk=pk).update(pointsaward=value)761 elif(request.POST.get('points1')):762 b=Feedback.objects.filter(pk=pk).update(pointsaward=value1)763 elif(request.POST.get('points2')):764 c=Innovation.objects.filter(pk=pk).update(pointsaward=value2)765 elif(request.POST.get('points3')):766 d=UG.objects.all().filter(pk=pk).update(pointsaward=value3)767 elif(request.POST.get('points4')):768 e=PG.objects.all().filter(pk=pk).update(pointsaward=value4)769 elif(request.POST.get('points5')):770 f=ExtraCurricular.objects.all().filter(pk=pk).update(pointsaward=value5)771 elif(request.POST.get('points6')):772 f=AllClear.objects.all().filter(pk=pk).update(pointsaward=value6)773 elif(request.POST.get('points7')):774 f=ThreeClear.objects.all().filter(pk=pk).update(pointsaward=value7)775 elif(request.POST.get('points8')):776 f=Article.objects.all().filter(pk=pk).update(pointsaward=value8)777 elif(request.POST.get('points9')):778 f=Competitive.objects.all().filter(pk=pk).update(pointsaward=value9)779 elif(request.POST.get('points10')):780 f=Startups.objects.all().filter(pk=pk).update(pointsaward=value10)781 elif(request.POST.get('points11')):782 f=Awards.objects.all().filter(pk=pk).update(pointsaward=value11)783 elif(request.POST.get('points12')):784 f=Prizes.objects.all().filter(pk=pk).update(pointsaward=value12)785 elif(request.POST.get('points13')):786 f=Internship.objects.all().filter(pk=pk).update(pointsaward=value13)787 elif(request.POST.get('points14')):788 f=OnlineCertification.objects.all().filter(pk=pk).update(pointsaward=value14)789 return render(request,self.template_name,{'i15':i15,'i14':i14,'i13':i13,'i12':i12,'i11':i11,'i10':i10,'i9':i9,'i8':i8,'i7':i7,'i6':i6,'i':i,'i2':i2,'i3':i3,'i4':i4,'i5':i5,'user1':user1})790791class ResponsesView(View):792 template_name = "responses_view.html"793 flag2=0794 def get(self,request):795 user = get_user(request)796 i = Academics.objects.all().filter(user=user)797 i2 = Feedback.objects.all().filter(user=user)798 i3 = Innovation.objects.all().filter(user=user)799 i4 = UG.objects.all().filter(user=user)800 i5 = PG.objects.all().filter(user=user)801 i6 = ExtraCurricular.objects.all().filter(user=user)802 i7 = AllClear.objects.all().filter(user=user)803 i8 = ThreeClear.objects.all().filter(user= user)804 i9 = Article.objects.all().filter(user=user)805 i10 = Competitive.objects.all().filter(user=user)806 i11 = Startups.objects.all().filter(user=user)807 i12 = Awards.objects.all().filter(user=user)808 i13 = Prizes.objects.all().filter(user=user)809 i14 = Internship.objects.all().filter(user=user)810 i15 = OnlineCertification.objects.all().filter(user=user)811 flag2=1812 return render(request,self.template_name,{'i15':i15,'i14':i14,'i13':i13,'i12':i12,'i11':i11,'i10':i10,'i9':i9,'i8':i8,'i6':i6,'i7':i7,'i':i,'i2':i2,'i3':i3,'i4':i4,'i5':i5,'flag2':flag2})813814 def post(self,request):815 user = get_user(request)816 i = Academics.objects.all().filter(user = user)817 i2 = Feedback.objects.all().filter(user=user)818 i3 = Innovation.objects.all().filter(user=user)819 i4 = UG.objects.all().filter(user=user)820 i5 = PG.objects.all().filter(user=user)821 i6 = ExtraCurricular.objects.all().filter(user=user)822 i7 = AllClear.objects.all().filter(user=user)823 i8 = ThreeClear.objects.all().filter(user=user)824 i9 = Article.objects.all().filter(user=user)825 i10 = Competitive.objects.all().filter(user=user)826 i11 = Startups.objects.all().filter(user=user)827 i12 = Awards.objects.all().filter(user=user)828 i13 = Prizes.objects.all().filter(user=user)829 i14 = Internship.objects.all().filter(user=user)830 i15 = OnlineCertification.objects.all().filter(user=user)831 832 return render(request,self.template_name,{'i15':i15,'i14':i14,'i13':i13,'i12':i12,'i11':i11,'i10':i10,'i9':i9,'i8':i8,'i7':i7,'i6':i6,'i':i,'i2':i2,'i3':i3,'i4':i4,'i5':i5})
...
tests.py
Source:tests.py
1from __future__ import unicode_literals2from math import ceil3from django.db import IntegrityError, connection, models4from django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE5from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature6from django.utils.six.moves import range7from .models import (8 MR, A, Avatar, Base, Child, HiddenUser, HiddenUserProfile, M, M2MFrom,9 M2MTo, MRNull, Parent, R, RChild, S, T, User, create_a, get_default_r,10)11class OnDeleteTests(TestCase):12 def setUp(self):13 self.DEFAULT = get_default_r()14 def test_auto(self):15 a = create_a('auto')16 a.auto.delete()17 self.assertFalse(A.objects.filter(name='auto').exists())18 def test_auto_nullable(self):19 a = create_a('auto_nullable')20 a.auto_nullable.delete()21 self.assertFalse(A.objects.filter(name='auto_nullable').exists())22 def test_setvalue(self):23 a = create_a('setvalue')24 a.setvalue.delete()25 a = A.objects.get(pk=a.pk)26 self.assertEqual(self.DEFAULT, a.setvalue.pk)27 def test_setnull(self):28 a = create_a('setnull')29 a.setnull.delete()30 a = A.objects.get(pk=a.pk)31 self.assertIsNone(a.setnull)32 def test_setdefault(self):33 a = create_a('setdefault')34 a.setdefault.delete()35 a = A.objects.get(pk=a.pk)36 self.assertEqual(self.DEFAULT, a.setdefault.pk)37 def test_setdefault_none(self):38 a = create_a('setdefault_none')39 a.setdefault_none.delete()40 a = A.objects.get(pk=a.pk)41 self.assertIsNone(a.setdefault_none)42 def test_cascade(self):43 a = create_a('cascade')44 a.cascade.delete()45 self.assertFalse(A.objects.filter(name='cascade').exists())46 def test_cascade_nullable(self):47 a = create_a('cascade_nullable')48 a.cascade_nullable.delete()49 self.assertFalse(A.objects.filter(name='cascade_nullable').exists())50 def test_protect(self):51 a = create_a('protect')52 with self.assertRaises(IntegrityError):53 a.protect.delete()54 def test_do_nothing(self):55 # Testing DO_NOTHING is a bit harder: It would raise IntegrityError for a normal model,56 # so we connect to pre_delete and set the fk to a known value.57 replacement_r = R.objects.create()58 def check_do_nothing(sender, **kwargs):59 obj = kwargs['instance']60 obj.donothing_set.update(donothing=replacement_r)61 models.signals.pre_delete.connect(check_do_nothing)62 a = create_a('do_nothing')63 a.donothing.delete()64 a = A.objects.get(pk=a.pk)65 self.assertEqual(replacement_r, a.donothing)66 models.signals.pre_delete.disconnect(check_do_nothing)67 def test_do_nothing_qscount(self):68 """69 A models.DO_NOTHING relation doesn't trigger a query.70 """71 b = Base.objects.create()72 with self.assertNumQueries(1):73 # RelToBase should not be queried.74 b.delete()75 self.assertEqual(Base.objects.count(), 0)76 def test_inheritance_cascade_up(self):77 child = RChild.objects.create()78 child.delete()79 self.assertFalse(R.objects.filter(pk=child.pk).exists())80 def test_inheritance_cascade_down(self):81 child = RChild.objects.create()82 parent = child.r_ptr83 parent.delete()84 self.assertFalse(RChild.objects.filter(pk=child.pk).exists())85 def test_cascade_from_child(self):86 a = create_a('child')87 a.child.delete()88 self.assertFalse(A.objects.filter(name='child').exists())89 self.assertFalse(R.objects.filter(pk=a.child_id).exists())90 def test_cascade_from_parent(self):91 a = create_a('child')92 R.objects.get(pk=a.child_id).delete()93 self.assertFalse(A.objects.filter(name='child').exists())94 self.assertFalse(RChild.objects.filter(pk=a.child_id).exists())95 def test_setnull_from_child(self):96 a = create_a('child_setnull')97 a.child_setnull.delete()98 self.assertFalse(R.objects.filter(pk=a.child_setnull_id).exists())99 a = A.objects.get(pk=a.pk)100 self.assertIsNone(a.child_setnull)101 def test_setnull_from_parent(self):102 a = create_a('child_setnull')103 R.objects.get(pk=a.child_setnull_id).delete()104 self.assertFalse(RChild.objects.filter(pk=a.child_setnull_id).exists())105 a = A.objects.get(pk=a.pk)106 self.assertIsNone(a.child_setnull)107 def test_o2o_setnull(self):108 a = create_a('o2o_setnull')109 a.o2o_setnull.delete()110 a = A.objects.get(pk=a.pk)111 self.assertIsNone(a.o2o_setnull)112class DeletionTests(TestCase):113 def test_m2m(self):114 m = M.objects.create()115 r = R.objects.create()116 MR.objects.create(m=m, r=r)117 r.delete()118 self.assertFalse(MR.objects.exists())119 r = R.objects.create()120 MR.objects.create(m=m, r=r)121 m.delete()122 self.assertFalse(MR.objects.exists())123 m = M.objects.create()124 r = R.objects.create()125 m.m2m.add(r)126 r.delete()127 through = M._meta.get_field('m2m').remote_field.through128 self.assertFalse(through.objects.exists())129 r = R.objects.create()130 m.m2m.add(r)131 m.delete()132 self.assertFalse(through.objects.exists())133 m = M.objects.create()134 r = R.objects.create()135 MRNull.objects.create(m=m, r=r)136 r.delete()137 self.assertFalse(not MRNull.objects.exists())138 self.assertFalse(m.m2m_through_null.exists())139 def test_bulk(self):140 s = S.objects.create(r=R.objects.create())141 for i in range(2 * GET_ITERATOR_CHUNK_SIZE):142 T.objects.create(s=s)143 # 1 (select related `T` instances)144 # + 1 (select related `U` instances)145 # + 2 (delete `T` instances in batches)146 # + 1 (delete `s`)147 self.assertNumQueries(5, s.delete)148 self.assertFalse(S.objects.exists())149 def test_instance_update(self):150 deleted = []151 related_setnull_sets = []152 def pre_delete(sender, **kwargs):153 obj = kwargs['instance']154 deleted.append(obj)155 if isinstance(obj, R):156 related_setnull_sets.append(list(a.pk for a in obj.setnull_set.all()))157 models.signals.pre_delete.connect(pre_delete)158 a = create_a('update_setnull')159 a.setnull.delete()160 a = create_a('update_cascade')161 a.cascade.delete()162 for obj in deleted:163 self.assertIsNone(obj.pk)164 for pk_list in related_setnull_sets:165 for a in A.objects.filter(id__in=pk_list):166 self.assertIsNone(a.setnull)167 models.signals.pre_delete.disconnect(pre_delete)168 def test_deletion_order(self):169 pre_delete_order = []170 post_delete_order = []171 def log_post_delete(sender, **kwargs):172 pre_delete_order.append((sender, kwargs['instance'].pk))173 def log_pre_delete(sender, **kwargs):174 post_delete_order.append((sender, kwargs['instance'].pk))175 models.signals.post_delete.connect(log_post_delete)176 models.signals.pre_delete.connect(log_pre_delete)177 r = R.objects.create(pk=1)178 s1 = S.objects.create(pk=1, r=r)179 s2 = S.objects.create(pk=2, r=r)180 T.objects.create(pk=1, s=s1)181 T.objects.create(pk=2, s=s2)182 RChild.objects.create(r_ptr=r)183 r.delete()184 self.assertEqual(185 pre_delete_order, [(T, 2), (T, 1), (RChild, 1), (S, 2), (S, 1), (R, 1)]186 )187 self.assertEqual(188 post_delete_order, [(T, 1), (T, 2), (RChild, 1), (S, 1), (S, 2), (R, 1)]189 )190 models.signals.post_delete.disconnect(log_post_delete)191 models.signals.pre_delete.disconnect(log_pre_delete)192 def test_relational_post_delete_signals_happen_before_parent_object(self):193 deletions = []194 def log_post_delete(instance, **kwargs):195 self.assertTrue(R.objects.filter(pk=instance.r_id))196 self.assertIs(type(instance), S)197 deletions.append(instance.id)198 r = R.objects.create(pk=1)199 S.objects.create(pk=1, r=r)200 models.signals.post_delete.connect(log_post_delete, sender=S)201 try:202 r.delete()203 finally:204 models.signals.post_delete.disconnect(log_post_delete)205 self.assertEqual(len(deletions), 1)206 self.assertEqual(deletions[0], 1)207 @skipUnlessDBFeature("can_defer_constraint_checks")208 def test_can_defer_constraint_checks(self):209 u = User.objects.create(210 avatar=Avatar.objects.create()211 )212 a = Avatar.objects.get(pk=u.avatar_id)213 # 1 query to find the users for the avatar.214 # 1 query to delete the user215 # 1 query to delete the avatar216 # The important thing is that when we can defer constraint checks there217 # is no need to do an UPDATE on User.avatar to null it out.218 # Attach a signal to make sure we will not do fast_deletes.219 calls = []220 def noop(*args, **kwargs):221 calls.append('')222 models.signals.post_delete.connect(noop, sender=User)223 self.assertNumQueries(3, a.delete)224 self.assertFalse(User.objects.exists())225 self.assertFalse(Avatar.objects.exists())226 self.assertEqual(len(calls), 1)227 models.signals.post_delete.disconnect(noop, sender=User)228 @skipIfDBFeature("can_defer_constraint_checks")229 def test_cannot_defer_constraint_checks(self):230 u = User.objects.create(231 avatar=Avatar.objects.create()232 )233 # Attach a signal to make sure we will not do fast_deletes.234 calls = []235 def noop(*args, **kwargs):236 calls.append('')237 models.signals.post_delete.connect(noop, sender=User)238 a = Avatar.objects.get(pk=u.avatar_id)239 # The below doesn't make sense... Why do we need to null out240 # user.avatar if we are going to delete the user immediately after it,241 # and there are no more cascades.242 # 1 query to find the users for the avatar.243 # 1 query to delete the user244 # 1 query to null out user.avatar, because we can't defer the constraint245 # 1 query to delete the avatar246 self.assertNumQueries(4, a.delete)247 self.assertFalse(User.objects.exists())248 self.assertFalse(Avatar.objects.exists())249 self.assertEqual(len(calls), 1)250 models.signals.post_delete.disconnect(noop, sender=User)251 def test_hidden_related(self):252 r = R.objects.create()253 h = HiddenUser.objects.create(r=r)254 HiddenUserProfile.objects.create(user=h)255 r.delete()256 self.assertEqual(HiddenUserProfile.objects.count(), 0)257 def test_large_delete(self):258 TEST_SIZE = 2000259 objs = [Avatar() for i in range(0, TEST_SIZE)]260 Avatar.objects.bulk_create(objs)261 # Calculate the number of queries needed.262 batch_size = connection.ops.bulk_batch_size(['pk'], objs)263 # The related fetches are done in batches.264 batches = int(ceil(float(len(objs)) / batch_size))265 # One query for Avatar.objects.all() and then one related fast delete for266 # each batch.267 fetches_to_mem = 1 + batches268 # The Avatar objects are going to be deleted in batches of GET_ITERATOR_CHUNK_SIZE269 queries = fetches_to_mem + TEST_SIZE // GET_ITERATOR_CHUNK_SIZE270 self.assertNumQueries(queries, Avatar.objects.all().delete)271 self.assertFalse(Avatar.objects.exists())272 def test_large_delete_related(self):273 TEST_SIZE = 2000274 s = S.objects.create(r=R.objects.create())275 for i in range(TEST_SIZE):276 T.objects.create(s=s)277 batch_size = max(connection.ops.bulk_batch_size(['pk'], range(TEST_SIZE)), 1)278 # TEST_SIZE // batch_size (select related `T` instances)279 # + 1 (select related `U` instances)280 # + TEST_SIZE // GET_ITERATOR_CHUNK_SIZE (delete `T` instances in batches)281 # + 1 (delete `s`)282 expected_num_queries = (ceil(TEST_SIZE // batch_size) +283 ceil(TEST_SIZE // GET_ITERATOR_CHUNK_SIZE) + 2)284 self.assertNumQueries(expected_num_queries, s.delete)285 self.assertFalse(S.objects.exists())286 self.assertFalse(T.objects.exists())287 def test_delete_with_keeping_parents(self):288 child = RChild.objects.create()289 parent_id = child.r_ptr_id290 child.delete(keep_parents=True)291 self.assertFalse(RChild.objects.filter(id=child.id).exists())292 self.assertTrue(R.objects.filter(id=parent_id).exists())293 def test_delete_with_keeping_parents_relationships(self):294 child = RChild.objects.create()295 parent_id = child.r_ptr_id296 parent_referent_id = S.objects.create(r=child.r_ptr).pk297 child.delete(keep_parents=True)298 self.assertFalse(RChild.objects.filter(id=child.id).exists())299 self.assertTrue(R.objects.filter(id=parent_id).exists())300 self.assertTrue(S.objects.filter(pk=parent_referent_id).exists())301 def test_queryset_delete_returns_num_rows(self):302 """303 QuerySet.delete() should return the number of deleted rows and a304 dictionary with the number of deletions for each object type.305 """306 Avatar.objects.bulk_create([Avatar(desc='a'), Avatar(desc='b'), Avatar(desc='c')])307 avatars_count = Avatar.objects.count()308 deleted, rows_count = Avatar.objects.all().delete()309 self.assertEqual(deleted, avatars_count)310 # more complex example with multiple object types311 r = R.objects.create()312 h1 = HiddenUser.objects.create(r=r)313 HiddenUser.objects.create(r=r)314 HiddenUserProfile.objects.create(user=h1)315 existed_objs = {316 R._meta.label: R.objects.count(),317 HiddenUser._meta.label: HiddenUser.objects.count(),318 A._meta.label: A.objects.count(),319 MR._meta.label: MR.objects.count(),320 HiddenUserProfile._meta.label: HiddenUserProfile.objects.count(),321 }322 deleted, deleted_objs = R.objects.all().delete()323 for k, v in existed_objs.items():324 self.assertEqual(deleted_objs[k], v)325 def test_model_delete_returns_num_rows(self):326 """327 Model.delete() should return the number of deleted rows and a328 dictionary with the number of deletions for each object type.329 """330 r = R.objects.create()331 h1 = HiddenUser.objects.create(r=r)332 h2 = HiddenUser.objects.create(r=r)333 HiddenUser.objects.create(r=r)334 HiddenUserProfile.objects.create(user=h1)335 HiddenUserProfile.objects.create(user=h2)336 m1 = M.objects.create()337 m2 = M.objects.create()338 MR.objects.create(r=r, m=m1)339 r.m_set.add(m1)340 r.m_set.add(m2)341 r.save()342 existed_objs = {343 R._meta.label: R.objects.count(),344 HiddenUser._meta.label: HiddenUser.objects.count(),345 A._meta.label: A.objects.count(),346 MR._meta.label: MR.objects.count(),347 HiddenUserProfile._meta.label: HiddenUserProfile.objects.count(),348 M.m2m.through._meta.label: M.m2m.through.objects.count(),349 }350 deleted, deleted_objs = r.delete()351 self.assertEqual(deleted, sum(existed_objs.values()))352 for k, v in existed_objs.items():353 self.assertEqual(deleted_objs[k], v)354 def test_proxied_model_duplicate_queries(self):355 """356 #25685 - Deleting instances of a model with existing proxy357 classes should not issue multiple queries during cascade358 deletion of referring models.359 """360 avatar = Avatar.objects.create()361 # One query for the Avatar table and a second for the User one.362 with self.assertNumQueries(2):363 avatar.delete()364class FastDeleteTests(TestCase):365 def test_fast_delete_fk(self):366 u = User.objects.create(367 avatar=Avatar.objects.create()368 )369 a = Avatar.objects.get(pk=u.avatar_id)370 # 1 query to fast-delete the user371 # 1 query to delete the avatar372 self.assertNumQueries(2, a.delete)373 self.assertFalse(User.objects.exists())374 self.assertFalse(Avatar.objects.exists())375 def test_fast_delete_m2m(self):376 t = M2MTo.objects.create()377 f = M2MFrom.objects.create()378 f.m2m.add(t)379 # 1 to delete f, 1 to fast-delete m2m for f380 self.assertNumQueries(2, f.delete)381 def test_fast_delete_revm2m(self):382 t = M2MTo.objects.create()383 f = M2MFrom.objects.create()384 f.m2m.add(t)385 # 1 to delete t, 1 to fast-delete t's m_set386 self.assertNumQueries(2, f.delete)387 def test_fast_delete_qs(self):388 u1 = User.objects.create()389 u2 = User.objects.create()390 self.assertNumQueries(1, User.objects.filter(pk=u1.pk).delete)391 self.assertEqual(User.objects.count(), 1)392 self.assertTrue(User.objects.filter(pk=u2.pk).exists())393 def test_fast_delete_joined_qs(self):394 a = Avatar.objects.create(desc='a')395 User.objects.create(avatar=a)396 u2 = User.objects.create()397 expected_queries = 1 if connection.features.update_can_self_select else 2398 self.assertNumQueries(expected_queries,399 User.objects.filter(avatar__desc='a').delete)400 self.assertEqual(User.objects.count(), 1)401 self.assertTrue(User.objects.filter(pk=u2.pk).exists())402 def test_fast_delete_inheritance(self):403 c = Child.objects.create()404 p = Parent.objects.create()405 # 1 for self, 1 for parent406 self.assertNumQueries(2, c.delete)407 self.assertFalse(Child.objects.exists())408 self.assertEqual(Parent.objects.count(), 1)409 self.assertEqual(Parent.objects.filter(pk=p.pk).count(), 1)410 # 1 for self delete, 1 for fast delete of empty "child" qs.411 self.assertNumQueries(2, p.delete)412 self.assertFalse(Parent.objects.exists())413 # 1 for self delete, 1 for fast delete of empty "child" qs.414 c = Child.objects.create()415 p = c.parent_ptr416 self.assertNumQueries(2, p.delete)417 self.assertFalse(Parent.objects.exists())418 self.assertFalse(Child.objects.exists())419 def test_fast_delete_large_batch(self):420 User.objects.bulk_create(User() for i in range(0, 2000))421 # No problems here - we aren't going to cascade, so we will fast422 # delete the objects in a single query.423 self.assertNumQueries(1, User.objects.all().delete)424 a = Avatar.objects.create(desc='a')425 User.objects.bulk_create(User(avatar=a) for i in range(0, 2000))426 # We don't hit parameter amount limits for a, so just one query for427 # that + fast delete of the related objs.428 self.assertNumQueries(2, a.delete)429 self.assertEqual(User.objects.count(), 0)430 def test_fast_delete_empty_no_update_can_self_select(self):431 """432 #25932 - Fast deleting on backends that don't have the433 `no_update_can_self_select` feature should work even if the specified434 filter doesn't match any row.435 """436 with self.assertNumQueries(1):437 self.assertEqual(438 User.objects.filter(avatar__desc='missing').delete(),439 (0, {'delete.User': 0})...
0002_insert_permissions.py
Source:0002_insert_permissions.py
1# -*- coding: utf-8 -*-2# Generated by Django 1.11.1 on 2017-06-11 16:403from __future__ import unicode_literals4from django.db import migrations5def forwards_func(apps, schema_editor):6 Permission = apps.get_model("permissions", "Permission")7 PermissionTranslation = apps.get_model("permissions", "PermissionTranslation")8 # Folders9 perm = Permission.objects.create(code="folders_can_edit")10 PermissionTranslation.objects.create(permission=perm, language_code="en", name="Can edit folder")11 PermissionTranslation.objects.create(permission=perm, language_code="ru", name="ÐÐ¾Ð¶ÐµÑ ÑедакÑиÑоваÑÑ Ð´Ð¸ÑÑекÑоÑиÑ")12 perm = Permission.objects.create(code="folders_can_edit_permissions")13 PermissionTranslation.objects.create(permission=perm, language_code="en", name="Can edit folder permissions")14 PermissionTranslation.objects.create(permission=perm, language_code="ru", name="ÐÐ¾Ð¶ÐµÑ ÑедакÑиÑоваÑÑ Ð¿Ñава на диÑÑекÑоÑи")15 perm = Permission.objects.create(code="folders_can_delete")16 PermissionTranslation.objects.create(permission=perm, language_code="en", name="Can delete folder")17 PermissionTranslation.objects.create(permission=perm, language_code="ru", name="ÐÐ¾Ð¶ÐµÑ ÑдалиÑÑ Ð´Ð¸ÑÑекÑоÑиÑ")18 # Permissions inside folder19 perm = Permission.objects.create(code="folders_can_read")20 PermissionTranslation.objects.create(permission=perm, language_code="en", name="Can read folder")21 PermissionTranslation.objects.create(permission=perm, language_code="ru", name="ÐÐ¾Ð¶ÐµÑ Ð¿ÑоÑмаÑÑиваÑÑ ÑодеÑжимое диÑÑекÑоÑии")22 perm = Permission.objects.create(code="folders_can_edit_folders_inside_this_folder")23 PermissionTranslation.objects.create(permission=perm, language_code="en", name="Can edit folders inside this folder")24 PermissionTranslation.objects.create(permission=perm, language_code="ru", name="ÐÐ¾Ð¶ÐµÑ ÑедакÑиÑоваÑÑ Ð´Ð¸ÑÑекÑоÑии, наÑ
одÑÑиеÑÑ Ð²Ð½ÑÑÑи ÑÑой диÑÑекÑоÑии")25 perm = Permission.objects.create(code="folders_can_delete_folders_inside_this_folder")26 PermissionTranslation.objects.create(permission=perm, language_code="en", name="Can delete folders inside this folder")27 PermissionTranslation.objects.create(permission=perm, language_code="ru", name="ÐÐ¾Ð¶ÐµÑ ÑдалÑÑÑ Ð´Ð¸ÑÑекÑоÑии, наÑ
одÑÑиеÑÑ Ð²Ð½ÑÑÑи ÑÑой диÑÑекÑоÑии")28 perm = Permission.objects.create(code="folders_can_create_folders_inside_this_folder")29 PermissionTranslation.objects.create(permission=perm, language_code="en", name="Can create folders")30 PermissionTranslation.objects.create(permission=perm, language_code="ru", name="ÐÐ¾Ð¶ÐµÑ ÑоздаваÑÑ Ð½Ð¾Ð²Ñе диÑÑекÑоÑии")31 perm = Permission.objects.create(code="folders_can_edit_permissions_to_exist")32 PermissionTranslation.objects.create(permission=perm, language_code="en", name="Can edit permissions to exist folders")33 PermissionTranslation.objects.create(permission=perm, language_code="ru", name="ÐÐ¾Ð¶ÐµÑ ÑедакÑиÑоваÑÑ Ð¿Ñава на диÑÑекÑоÑии внÑÑÑи ÑÑой диÑÑекÑоÑии")34 perm = Permission.objects.create(code="folders_can_edit_permissions_to_own")35 PermissionTranslation.objects.create(permission=perm, language_code="en", name="Can edit permissions to own folders")36 PermissionTranslation.objects.create(permission=perm, language_code="ru", name="ÐÐ¾Ð¶ÐµÑ ÑедакÑиÑоваÑÑ Ð¿Ñава на Ñвои диÑÑекÑоÑии (ÑозданнÑе ÑÑим полÑзоваÑелем)")37 # Permissions on documents inside folders38 perm = Permission.objects.create(code="folders_can_edit_documents_inside_this_folder")39 PermissionTranslation.objects.create(permission=perm, language_code="en", name="Can edit documents inside this folder")40 PermissionTranslation.objects.create(permission=perm, language_code="ru", name="ÐÐ¾Ð¶ÐµÑ ÑедакÑиÑоваÑÑ Ð´Ð¾ÐºÑменÑÑ, наÑ
одÑÑиеÑÑ Ð²Ð½ÑÑÑи ÑÑой диÑÑекÑоÑии")41 perm = Permission.objects.create(code="folders_can_delete_documents_inside_this_folder")42 PermissionTranslation.objects.create(permission=perm, language_code="en", name="Can delete documents inside this folder")43 PermissionTranslation.objects.create(permission=perm, language_code="ru", name="ÐÐ¾Ð¶ÐµÑ ÑдалÑÑÑ Ð´Ð¸ÑÑекÑоÑии, наÑ
одÑÑиеÑÑ Ð²Ð½ÑÑÑи ÑÑой диÑÑекÑоÑии")44 perm = Permission.objects.create(code="folders_can_create_documents_inside_this_folder")45 PermissionTranslation.objects.create(permission=perm, language_code="en", name="Can create documents")46 PermissionTranslation.objects.create(permission=perm, language_code="ru", name="ÐÐ¾Ð¶ÐµÑ ÑоздаваÑÑ Ð½Ð¾Ð²Ñе докÑменÑÑ")47 perm = Permission.objects.create(code="folders_can_set_custom_permissions_to_exist_documents")48 PermissionTranslation.objects.create(permission=perm, language_code="en", name="Can set custom permissions to exist documents")49 PermissionTranslation.objects.create(permission=perm, language_code="ru", name="ÐÐ¾Ð¶ÐµÑ Ð½Ð°Ð·Ð½Ð°ÑаÑÑ Ð¿Ñава на ÑÑÑеÑÑвÑÑÑие докÑменÑÑ")50 perm = Permission.objects.create(code="folders_can_set_custom_permissions_to_own_documents")51 PermissionTranslation.objects.create(permission=perm, language_code="en", name="Can set custom permissions to own documents")52 PermissionTranslation.objects.create(permission=perm, language_code="ru", name="ÐÐ¾Ð¶ÐµÑ Ð½Ð°Ð·Ð½Ð°ÑаÑÑ Ð¿Ñава на Ñвои докÑменÑÑ (ÑозданнÑе ÑÑим полÑзоваÑелем)")53 # Documents54 perm = Permission.objects.create(code="documents_can_read")55 PermissionTranslation.objects.create(permission=perm, language_code="en", name="Can read document")56 PermissionTranslation.objects.create(permission=perm, language_code="ru", name="ÐÐ¾Ð¶ÐµÑ ÑиÑаÑÑ Ð´Ð¾ÐºÑменÑ")57 perm = Permission.objects.create(code="documents_can_edit")58 PermissionTranslation.objects.create(permission=perm, language_code="en", name="Can edit document")59 PermissionTranslation.objects.create(permission=perm, language_code="ru", name="ÐÐ¾Ð¶ÐµÑ ÑедакÑиÑоваÑÑ Ð´Ð¾ÐºÑменÑ")60 perm = Permission.objects.create(code="documents_can_delete")61 PermissionTranslation.objects.create(permission=perm, language_code="en", name="Can delete document")62 PermissionTranslation.objects.create(permission=perm, language_code="ru", name="ÐÐ¾Ð¶ÐµÑ ÑдалиÑÑ Ð´Ð¾ÐºÑменÑ")63 perm = Permission.objects.create(code="documents_can_edit_permissions")64 PermissionTranslation.objects.create(permission=perm, language_code="en", name="Can edit document permissions")65 PermissionTranslation.objects.create(permission=perm, language_code="ru", name="ÐÐ¾Ð¶ÐµÑ ÑедакÑиÑоваÑÑ Ð¿Ñава на докÑменÑ")66def reverse_func(apps, schema_editor):67 Permission = apps.get_model("permissions", "Permission")68 PermissionTranslation = apps.get_model("permissions", "PermissionTranslation")69 Permission.objects.all().delete()70 PermissionTranslation.objects.all().delete()71class Migration(migrations.Migration):72 dependencies = [73 ('permissions', '0001_initial'),74 ]75 operations = [76 migrations.RunPython(forwards_func, reverse_func),...
check_inits.py
Source:check_inits.py
1# coding=utf-82# Copyright 2020 The HuggingFace Inc. team.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15import collections16import os17import re18PATH_TO_TRANSFORMERS = "src/transformers"19# Matches is_xxx_available()20_re_backend = re.compile(r"is\_([a-z]*)_available()")21# Catches a line with a key-values pattern: "bla": ["foo", "bar"]22_re_import_struct_key_value = re.compile(r'\s+"\S*":\s+\[([^\]]*)\]')23# Catches a line if is_foo_available24_re_test_backend = re.compile(r"^\s*if\s+is\_[a-z]*\_available\(\)")25# Catches a line _import_struct["bla"].append("foo")26_re_import_struct_add_one = re.compile(r'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)')27# Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"]28_re_import_struct_add_many = re.compile(r"^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]")29# Catches a line with an object between quotes and a comma: "MyModel",30_re_quote_object = re.compile('^\s+"([^"]+)",')31# Catches a line with objects between brackets only: ["foo", "bar"],32_re_between_brackets = re.compile("^\s+\[([^\]]+)\]")33# Catches a line with from foo import bar, bla, boo34_re_import = re.compile(r"\s+from\s+\S*\s+import\s+([^\(\s].*)\n")35def find_backend(line):36 """Find one (or multiple) backend in a code line of the init."""37 if _re_test_backend.search(line) is None:38 return None39 backends = [b[0] for b in _re_backend.findall(line)]40 backends.sort()41 return "_and_".join(backends)42def parse_init(init_file):43 """44 Read an init_file and parse (per backend) the _import_structure objects defined and the TYPE_CHECKING objects45 defined46 """47 with open(init_file, "r", encoding="utf-8", newline="\n") as f:48 lines = f.readlines()49 line_index = 050 while line_index < len(lines) and not lines[line_index].startswith("_import_structure = {"):51 line_index += 152 # If this is a traditional init, just return.53 if line_index >= len(lines):54 return None55 # First grab the objects without a specific backend in _import_structure56 objects = []57 while not lines[line_index].startswith("if TYPE_CHECKING") and find_backend(lines[line_index]) is None:58 line = lines[line_index]59 single_line_import_search = _re_import_struct_key_value.search(line)60 if single_line_import_search is not None:61 imports = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(", ") if len(obj) > 0]62 objects.extend(imports)63 elif line.startswith(" " * 8 + '"'):64 objects.append(line[9:-3])65 line_index += 166 import_dict_objects = {"none": objects}67 # Let's continue with backend-specific objects in _import_structure68 while not lines[line_index].startswith("if TYPE_CHECKING"):69 # If the line is an if is_backend_available, we grab all objects associated.70 backend = find_backend(lines[line_index])71 if backend is not None:72 line_index += 173 objects = []74 # Until we unindent, add backend objects to the list75 while len(lines[line_index]) <= 1 or lines[line_index].startswith(" " * 4):76 line = lines[line_index]77 if _re_import_struct_add_one.search(line) is not None:78 objects.append(_re_import_struct_add_one.search(line).groups()[0])79 elif _re_import_struct_add_many.search(line) is not None:80 imports = _re_import_struct_add_many.search(line).groups()[0].split(", ")81 imports = [obj[1:-1] for obj in imports if len(obj) > 0]82 objects.extend(imports)83 elif _re_between_brackets.search(line) is not None:84 imports = _re_between_brackets.search(line).groups()[0].split(", ")85 imports = [obj[1:-1] for obj in imports if len(obj) > 0]86 objects.extend(imports)87 elif _re_quote_object.search(line) is not None:88 objects.append(_re_quote_object.search(line).groups()[0])89 elif line.startswith(" " * 8 + '"'):90 objects.append(line[9:-3])91 elif line.startswith(" " * 12 + '"'):92 objects.append(line[13:-3])93 line_index += 194 import_dict_objects[backend] = objects95 else:96 line_index += 197 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend98 objects = []99 while (100 line_index < len(lines)101 and find_backend(lines[line_index]) is None102 and not lines[line_index].startswith("else")103 ):104 line = lines[line_index]105 single_line_import_search = _re_import.search(line)106 if single_line_import_search is not None:107 objects.extend(single_line_import_search.groups()[0].split(", "))108 elif line.startswith(" " * 8):109 objects.append(line[8:-2])110 line_index += 1111 type_hint_objects = {"none": objects}112 # Let's continue with backend-specific objects113 while line_index < len(lines):114 # If the line is an if is_backemd_available, we grab all objects associated.115 backend = find_backend(lines[line_index])116 if backend is not None:117 line_index += 1118 objects = []119 # Until we unindent, add backend objects to the list120 while len(lines[line_index]) <= 1 or lines[line_index].startswith(" " * 8):121 line = lines[line_index]122 single_line_import_search = _re_import.search(line)123 if single_line_import_search is not None:124 objects.extend(single_line_import_search.groups()[0].split(", "))125 elif line.startswith(" " * 12):126 objects.append(line[12:-2])127 line_index += 1128 type_hint_objects[backend] = objects129 else:130 line_index += 1131 return import_dict_objects, type_hint_objects132def analyze_results(import_dict_objects, type_hint_objects):133 """134 Analyze the differences between _import_structure objects and TYPE_CHECKING objects found in an init.135 """136 def find_duplicates(seq):137 return [k for k, v in collections.Counter(seq).items() if v > 1]138 if list(import_dict_objects.keys()) != list(type_hint_objects.keys()):139 return ["Both sides of the init do not have the same backends!"]140 errors = []141 for key in import_dict_objects.keys():142 duplicate_imports = find_duplicates(import_dict_objects[key])143 if duplicate_imports:144 errors.append(f"Duplicate _import_structure definitions for: {duplicate_imports}")145 duplicate_type_hints = find_duplicates(type_hint_objects[key])146 if duplicate_type_hints:147 errors.append(f"Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}")148 if sorted(set(import_dict_objects[key])) != sorted(set(type_hint_objects[key])):149 name = "base imports" if key == "none" else f"{key} backend"150 errors.append(f"Differences for {name}:")151 for a in type_hint_objects[key]:152 if a not in import_dict_objects[key]:153 errors.append(f" {a} in TYPE_HINT but not in _import_structure.")154 for a in import_dict_objects[key]:155 if a not in type_hint_objects[key]:156 errors.append(f" {a} in _import_structure but not in TYPE_HINT.")157 return errors158def check_all_inits():159 """160 Check all inits in the transformers repo and raise an error if at least one does not define the same objects in161 both halves.162 """163 failures = []164 for root, _, files in os.walk(PATH_TO_TRANSFORMERS):165 if "__init__.py" in files:166 fname = os.path.join(root, "__init__.py")167 objects = parse_init(fname)168 if objects is not None:169 errors = analyze_results(*objects)170 if len(errors) > 0:171 errors[0] = f"Problem in {fname}, both halves do not define the same objects.\n{errors[0]}"172 failures.append("\n".join(errors))173 if len(failures) > 0:174 raise ValueError("\n\n".join(failures))175if __name__ == "__main__":...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!