分页器
#views.py from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def add(request): Booklist=[] for i in range(100): book_obj=models.Book(name="book"+str(i),price=60+i*i) boklist.append(book_obj) models.Book.objects.bulk_create(Booklist) return HttpRenponse("OK") def index(request): book_list=models.Book.objects.all() paginator=Paginator(book_list,8) # 8 是每页的记录数 ''' print(paginator.count) # 总的数据 100 print(paginator.num_pages) # 总的页数 13 print(paginator.page_range) # 页数范围 range(1,14) ''' page_range = paginator.page_range try: num = int(request.GET.get("p",1)) page = paginator.page(num) except Exception as e: page = paginator.page(1) ''' print(page.next_page_number()) print(page.previous_page_number()) print(page.has_next()) print(page.has_previous()) ''' return render(request,"index.html",{"page":page,"page_range":page_range,"num":num})
#index.html <html> <head> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script> <link rel="stylesheet" href="/static/dist/css/bootstrap.css"> </head> <style> </style> <body> <ul> {% for i in page %} <li>{{ i.name }}</li> {% endfor %} </ul> <nav aria-label="Page navigation"> <ul class="pagination"> {% if page.has_previous %} <li><a href="/?p={{ page.previous_page_number }}">上一页</a></li> {% else %} <li class="disabled"><a href="#">上一页</a></li> {% endif %} {% for i in page_range %} {% if i==num %} <li class="active"><a href="/?p={{ i }}">{{ i }}</a></li> {% else %} <li><a href="/?p={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if page.has_next %} <li><a href="/?p={{ page.next_page_number }}">下一页</a></li> {% else %} <li class="disabled"><a href="#">下一页</a></li> {% endif %} </ul> </nav> </body> </html>
自定义分页器
Cookie & Session
cooike是保留在客户端(浏览器)的妇女放键值对的容器
session是保留在服务器上的容器 {}
#models.py class UserInfo(models.Model): name=models.CharField(max_length=32) pwd=models.CharField(max_length=32)
#urls.py url(r'^login/',views.login) url(r'^index/',views.index) url(r'^logout/',views.log_out) url(r'^addBook/',views.addBook)
#views.py from app01 import models def login(request): if request.method=='POST': username=request.POST.get('name') password=request.POST.get('pwd') ret=models.UserInfo.objects.filter(name=username,pwd=password) if ret: request.session['is_login']=True request.session['username']=username return redirect('/index/') else: return redirect('/login/') return render(request,'login.html') def index(request): if not request.session.get('is_login'): return redirect('/login/') name=request.session.get('uername') return render(request,'index.html',{"name":name}) def addBook(request): return render(request,'addBook.html') def log_out(request); request.session.flush() return redirect("/login/")
#login.html <form action='/login/' method='post'> {% csrf_token %} <p>姓名<input type='text' name='user'></p> <p>密码<input type='pwd' name='pwd'></p> <input type='submit'> </form> #index.html <h3>welcome {{ name }}</h3> <a href="/logout/">注销</a> #addBook.html <form action='/login/' method='post'> {% csrf_token %} <p>书名<input type='text' name='user'></p> <p>价格<input type='pwd' name='pwd'></p> <input type='submit'> </form>
auth认证模块
不用这个模块,用session和cooike也可以
只是这个模块更加简单
#urls.py url(r'^login',views.login) url(r'^index',views.index) url(r'^logout',views.log_out) url(r'^reg',views.reg)
#views.py from django.contrib import auth from django.contrib.auth.models import User def login(request): if request.method == "POST": username=request.POST.get('user') password=request.POST.get('pwd') user=auth.authenticate(username=username,password=password) if user: auth.login(request,user) return redirect('/index/') else: return redirect('/login/') return render(request,"login.html") def index(request): if not request.user.is_authenticated(): return redirect('/login/') return render(request,'index.html') def log_out(request): auth.logout(request) return redirect('/login/') def reg(request): if request.method=="POST": user=request.POST.get('user') pwd=request.POST.get('pwd') User.objects.create_user(username=user,password=pwd) return redirect('/login/') return render(request,"reg.html")
#login.html <form action='/login/' method='post'> {% csrf_token %} <p>姓名<input type='text' name='user'></p> <p>密码<input type='pwd' name='pwd'></p> <input type='submit'> </form> #index.html <li><a href="#">welcome {{ request.user }}</a></li> <li><a href="/logout/">注销</a></li> #reg.html <h3>注册</h3> <form action='/reg/' method='post'> {% csrf_token %} <p>姓名<input type='text' name='user'></p> <p>密码<input type='pwd' name='pwd'></p> <input type='submit'> <a href='/reg/'><input type='button' value='注册'></a> </form>
Django-Ajax
序列化操作:
1.JSON.parse() # 将一个Json字符串转换为js对象
2.JSON.stringify() # 将js转换为json字符串
AJAX:
1.异步
2.局部刷新
#urls.py url(r'^index/',views.index) url(r'^send_ajax/',views.send_ajax) url(r'^cal/',views.cal) url(r'^login/',views.login)
#views.py def index(request): return render(request,'index.html') def send_ajax(request): return HttpResponse("OK") def cal(request): num1=request.GET.get("num1") num2=request.GET.get("num2") ret=int(num1)+int(num2) return HttpResponse(ret) def login(request): user=request.POST.get("user") pwd=request.POST.get("pwd") loginResponse={"user":None,"errorMsg":None} if user=="tom" and pwd=="123": loginResponse["user"]="tom" else: loginResponse["errorMsg"]="用户名或密码错误" import json return HttpResponse(json.dumps(loginResponse))
#index.html <html> <head> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script> </head> <body> <button>ajaxSend</button><span class='error'></span> {% csrf_token %} <p><input type="text" class="num1">+<input type="text" class="num2">=<input type="text" class="ret"><button class="cal">计算</button></p> <form action=""> <p>姓名 <input type="text" class="user"></p> <p>密码 <input type="password" class="pwd"></p> <input type="button" value="submit" class="loginBtn"><span class="login_error"></span> </form> <script> //ajax实现 $('button').click(function(){ $.ajax({ url:"/send_ajax/", type:"get", success:function(data){ $(".error").html(data) } }) }); //ajax计算 $(".cal").click(function(){ var num1=$(".num1").val(); var num2=$(".num2").val(); $.ajax(function(){ url:"/cal/", type:"post", data:{ "num1":num1, "num2":num2, csrfmiddlewaretoken:$('[name="csrfmiddlewaretoken"]').val() }, success:function(data){ $(".ret").val(data) } }) }); //ajax登陆 $(".loginBtn").click(function(){ $.ajax(function(){ url:"/login/", type:"POST", data:{ user:$(".user").val(), pwd:$(".pwd").val(), csrfmiddlewaretoken:$('[name="csrfmiddlewaretoken"]').val() }, success:function(data){ console.log(typeof data); //string var data= JSON.parse(data); console.log(typeof data); //object if(data["user"]){ location.href="/index/" //成功后跳转 } else{ var error_msg=data["error_Msg"]; $(".login_error").html(error_msg).css("color","red"); setTimeout(function(){ $(".login_error").html("") //3s后清空文本 },3000) } } }) }); </script> </body> </html>