Django补充知识点——用户管理
內(nèi)容概要
1、Form表單
2、Ajax
3、布局,Django母板
4、序列化
5、Ajax相關(guān)
6、分頁
7、XSS攻擊
8、CSRF
9、CBV、FBV
10、類中用裝飾器的兩種方法
11、上傳文件
?12、數(shù)據(jù)庫正向查詢、反向查詢、多對(duì)多查詢
13、jQuery對(duì)象和DOM對(duì)象可以互相轉(zhuǎn)換
14、cookie和session
?
用戶管理,功能:
1、用戶登錄
2、注冊(cè)
3、注銷
4、后臺(tái)管理菜單
5、班級(jí)操作
6、老師、學(xué)生
?
補(bǔ)充知識(shí)點(diǎn):
前端提交數(shù)據(jù)到后端的兩種方法:
——form表單
——ajax
?
1、Form表單? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
?
用法:
通過type=submit提交 一般表單提交通過type=submit實(shí)現(xiàn),input type="submit",瀏覽器顯示為button按鈕,通過點(diǎn)擊這個(gè)按鈕提交表單數(shù)據(jù)跳轉(zhuǎn)到/url.do <form action="/url.do" method="post"><input type="text" name="name"/><input type="submit" value="提交"> </form>學(xué)生管理的添加頁面中,下拉框選班級(jí)用select? ?option標(biāo)簽
add_student.html中 <form action="/add_student.html" method="POST"><p><input placeholder="學(xué)生姓名" type="text" name="name" /></p><p><input placeholder="學(xué)生郵箱" type="text" name="email" /></p><p><!-- <input placeholder="班級(jí)ID" type="text" name="cls_id" /> --> {# form表單提交時(shí)會(huì)將select里面選中的結(jié)果cls_id=value的值一起提交過去 #} <select name="cls_id">{% for op in cls_list %}<option value="{{ op.id }}">{{ op.caption }}</option>{% endfor %}</select></p><input type="submit" value="提交"/></form>views中的函數(shù)def add_student(request):if request.method == "GET":cls_list = models.Classes.objects.all()[0: 20]return render(request, 'add_student.html', {'cls_list': cls_list})elif request.method == "POST":name = request.POST.get('name')email = request.POST.get('email')cls_id = request.POST.get('cls_id')models.Student.objects.create(name=name,email=email,cls_id=cls_id)return redirect('/student.html')
?
詳細(xì)內(nèi)容:
表單標(biāo)簽<form>
? ? ? 表單用于向服務(wù)器傳輸數(shù)據(jù)。
1.表單屬性
HTML 表單用于接收不同類型的用戶輸入,用戶提交表單時(shí)向服務(wù)器傳輸數(shù)據(jù),從而實(shí)現(xiàn)用戶與Web服務(wù)器的交互。表單標(biāo)簽, 要提交的所有內(nèi)容都應(yīng)該在該標(biāo)簽中.
? ? ? ? ? ? action: 表單提交到哪. 一般指向服務(wù)器端一個(gè)程序,程序接收到表單提交過來的數(shù)據(jù)(即表單元素值)作相應(yīng)處理,比如https://www.sogou.com/web
? ? ? ? ? ? method: 表單的提交方式 post/get 默認(rèn)取值 就是 get(信封)
? ? ? ? ? ? ? ? ? ? ? ? ? get: 1.提交的鍵值對(duì).放在地址欄中url后面. 2.安全性相對(duì)較差. 3.對(duì)提交內(nèi)容的長度有限制.
? ? ? ? ? ? ? ? ? ? ? ? ? post:1.提交的鍵值對(duì) 不在地址欄. 2.安全性相對(duì)較高. 3.對(duì)提交內(nèi)容的長度理論上無限制.
? ? ? ? ? ? ? ? ? ? ? ? ? get/post是常見的兩種請(qǐng)求方式.
2.表單元素
? ? ? ? ? ?<input> ?標(biāo)簽的屬性和對(duì)應(yīng)值? ? ? ? ? ? ??
type: text 文本輸入框password 密碼輸入框radio 單選框checkbox 多選框 submit 提交按鈕 button 按鈕(需要配合js使用.) button和submit的區(qū)別?file 提交文件:form表單需要加上屬性enctype="multipart/form-data" name: 表單提交項(xiàng)的鍵.注意和id屬性的區(qū)別:name屬性是和服務(wù)器通信時(shí)使用的名稱;而id屬性是瀏覽器端使用的名稱,該屬性主要是為了方便客戶端編程,而在css和javascript中使用的value: 表單提交項(xiàng)的值.對(duì)于不同的輸入類型,value 屬性的用法也不同:1.type="button", "reset", "submit" - 定義按鈕上的顯示的文本2.type="text", "password", "hidden" - 定義輸入字段的初始值3.type="checkbox", "radio", "image" - 定義與輸入相關(guān)聯(lián)的值 checked: radio 和 checkbox 默認(rèn)被選中4.readonly: 只讀. text 和 password5.disabled: 對(duì)所用input都好使.上傳文件注意兩點(diǎn):
?1 請(qǐng)求方式必須是post
?2 enctype="multipart/form-data"
?
實(shí)例:接收文件的py文件
def index(request):print request.POSTprint request.GETprint request.FILESfor item in request.FILES:fileObj = request.FILES.get(item)f = open(fileObj.name, 'wb')iter_file = fileObj.chunks()for line in iter_file:f.write(line)f.close()return HttpResponse('ok')
2、Ajax? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
基于jQuery的ajax:
$.ajax({url:"//",data:{a:1,b:2}, /*當(dāng)前ajax請(qǐng)求要攜帶的數(shù)據(jù),是一個(gè)json的object對(duì)象,ajax方法就會(huì)默認(rèn)地把它編碼成某種格式(urlencoded:?a=1&b=2)發(fā)送給服務(wù)端;*/dataType: /*預(yù)期服務(wù)器返回的數(shù)據(jù)類型,服務(wù)器端返回的數(shù)據(jù)會(huì)根據(jù)這個(gè)值解析后,傳遞給回調(diào)函數(shù)。*/type:"GET",success:function(){}})
基于JS的ajax:
采用ajax異步方式,通過js獲取form中所有input、select等組件的值,將這些值組成Json格式,通過異步的方式與服務(wù)器端進(jìn)行交互,
一般將表單數(shù)據(jù)傳送給服務(wù)器端,服務(wù)器端處理數(shù)據(jù)并返回結(jié)果信息等
用法:
注:POST請(qǐng)求時(shí),要在send之前,open之后加請(qǐng)求頭
3、布局,Django母板? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
母板中:
{% block title(給這個(gè)block取一個(gè)名字) %}………………
{% endblock %}
?子模板中:
{% extends "base.html" %}#繼承自“base.html”{% block title %}Future time{% endblock %}{% block content %} <p>In {{ hour_offset }} hour(s), it will be {{ next_time }}.</p> {% endblock %}
?
?
?
?
?
?
?
?8.CSRF? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
{%csrf_token%}:csrf_token標(biāo)簽
? ? ?用于生成csrf_token的標(biāo)簽,用于防治跨站攻擊驗(yàn)證。注意如果你在view的index里用的是render_to_response方法,不會(huì)生效,而應(yīng)該用render。
???? 其實(shí),這里是會(huì)生成一個(gè)input標(biāo)簽,和其他表單標(biāo)簽一起提交給后臺(tái)的。
<form action="{% url "bieming"%}" ><input type="text"><input type="submit"value="提交">{%csrf_token%} </form>
?
?
9.FBV 和 CBV? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
views.py # 方法一:FBV def login(request):if request.method == "POST":user = request.POST.get("user")pwd = request.POST.get("pwd")c = models.Administrator.objects.filter(username=user,password=pwd).count()print(c)if c:#設(shè)置session中存儲(chǔ)的數(shù)據(jù)request.session["is_login"] = Truerequest.session["username"] = user#尤其注意跳轉(zhuǎn)到哪個(gè)頁面!!!return render(request,"index.html",{"username":user})else:msg = "用戶名或密碼錯(cuò)誤"return redirect("/login.html",{"msg":msg})return render(request,"login.html") ----------------------------------------------------------------- urs.py # url(r'^login.html$', views.login),cbv:
#CBV from django import views class Login(views.View):def get(self,request,*args,**kwargs):return render(request, "login.html")def post(self,request,*args,**kwargs):user = request.POST.get("user")pwd = request.POST.get("pwd")c = models.Administrator.objects.filter(username=user, password=pwd).count()print(c)if c:#設(shè)置session中存儲(chǔ)的數(shù)據(jù)request.session["is_login"] = Truerequest.session["username"] = user#尤其注意跳轉(zhuǎn)到哪個(gè)頁面!!!return render(request,"index.html",{"username":user})else:msg = "用戶名或密碼錯(cuò)誤"return redirect("/login.html",{"msg":msg}) ----------------------------------------------------- urs.pyurl(r'^login.html$', views.Login.as_view()),#以類的方式進(jìn)行創(chuàng)建?
10.類中用裝飾器? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
?方法一:自定義裝飾器
from django import views from django.utils.decorators import method_decorator#1.引入庫 #2.定義裝飾器函數(shù) def outer(func):def inner(request,*args,**kwargs):print(request.method)return func(request,*args,**kwargs)return innerclass Login(views.View):#3.使用裝飾器@method_decorator(outer)def get(self,request,*args,**kwargs):return render(request, "login.html")
?方法二:自定義dispatch方法,同時(shí)繼承父類該方法,等同于裝飾器
from django import viewsclass Login(views.View):#1.先執(zhí)行自定義的dispatch方法def dispatch(self, request, *args, **kwargs):print(11111)if request.method == "GET":return HttpResponse("ok")#2.再調(diào)用父類中的dispatch方法,dispatch方法類似路由分發(fā)ret = super(Login,self).dispatch(request, *args, **kwargs)print(22222)return retdef get(self,request,*args,**kwargs):return render(request, "login.html")def post(self,request,*args,**kwargs):user = request.POST.get("user")pwd = request.POST.get("pwd")c = models.Administrator.objects.filter(username=user, password=pwd).count()print(c)if c:#設(shè)置session中存儲(chǔ)的數(shù)據(jù)request.session["is_login"] = Truerequest.session["username"] = user#尤其注意跳轉(zhuǎn)到哪個(gè)頁面!!!return render(request,"index.html",{"username":user})else:msg = "用戶名或密碼錯(cuò)誤"return redirect("/login.html",{"msg":msg})?
11、上傳文件
文件上傳
----- Form表單上傳文件 基于FormData() (上傳后,頁面需要刷新后才能顯示)
----- Ajax上傳文件 基于FormData() (無需刷新頁面)
----- 基于form表單和iframe自己實(shí)現(xiàn)ajax請(qǐng)求 (因?yàn)橛行g覽器可能不兼容FormData())
a.form表單上傳
b. 悄悄的上傳(ajax)
?實(shí)例:讓用戶看到當(dāng)前上傳的圖片
三種ajax方法的實(shí)例:
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>上傳文件</title><style>.container img{width: 200px;height: 200px;}</style><script>function li(arg) {console.log(arg);}</script> </head> <body><h1>測(cè)試Iframe功能</h1><input type="text" id="url" /><input type="button" value="點(diǎn)我" οnclick="iframeChange();" /><iframe id="ifr" src=""></iframe><hr/><h1>基于iframe實(shí)現(xiàn)form提交</h1><form action="/upload.html" method="post" target="iframe_1" enctype="multipart/form-data"><iframe style="display: none" id="iframe_1" name="iframe_1" src="" οnlοad="loadIframe();"></iframe><input type="text" name="user" /><input type="file" name="fafafa" /><input type="submit" /></form><h1>圖片列表</h1><div class="container" id="imgs">{% for img in img_list %}<img src="/{{ img.path }}">{% endfor %}</div> <input type="file" id="img" /><input type="button" value="提交XML" οnclick="UploadXML()" /><input type="button" value="提交JQ" οnclick="Uploadjq()" /><script src="/static/jquery-2.1.4.min.js"></script><script>function UploadXML() {var dic = new FormData();dic.append('user', 'v1');dic.append('fafafa', document.getElementById('img').files[0]);var xml = new XMLHttpRequest();xml.open('post', '/upload.html', true);xml.onreadystatechange = function () {if(xml.readyState == 4){var obj = JSON.parse(xml.responseText);if(obj.status){var img = document.createElement('img');img.src = "/" + obj.path;document.getElementById("imgs").appendChild(img);}}};xml.send(dic);}function Uploadjq() {var dic = new FormData();dic.append('user', 'v1');dic.append('fafafa', document.getElementById('img').files[0]);$.ajax({url: '/upload.html',type: 'POST',data: dic,processData: false, // tell jQuery not to process the datacontentType: false, // tell jQuery not to set contentTypedataType: 'JSON',success: function (arg) {if (arg.status){var img = document.createElement('img');img.src = "/" + arg.path;$('#imgs').append(img);}}})}function iframeChange() {var url = $('#url').val();$('#ifr').attr('src', url);}function loadIframe() {console.log(1);// 獲取iframe內(nèi)部的內(nèi)容var str_json = $('#iframe_1').contents().find('body').text();var obj = JSON.parse(str_json);if (obj.status){var img = document.createElement('img');img.src = "/" + obj.path;$('#imgs').append(img);}}</script></body> </html>views.py文件:
import os def upload(request):if request.method == 'GET':img_list = models.Img.objects.all()return render(request,'upload.html',{'img_list': img_list})elif request.method == "POST":user = request.POST.get('user')fafafa = request.POST.get('fafafa')#只能獲取到文件名obj = request.FILES.get('fafafa')#必須這樣才能取到文件file_path = os.path.join('static','upload',obj.name)f = open(file_path, 'wb')for chunk in obj.chunks():f.write(chunk)f.close()models.Img.objects.create(path=file_path)ret = {'status': True, 'path': file_path}return HttpResponse(json.dumps(ret))
?12、數(shù)據(jù)庫正向查詢、反向查詢、多對(duì)多查詢
一、一對(duì)多(ForeignKey)
-------------------------------views.py----------------------------------------------def test(request): # 例一:# pro_list = models.Province.objects.all()# print(pro_list)# city_list = models.City.objects.all()# print(city_list) 正向查找(通過具有外鍵字段的類,City)# filter(故意寫錯(cuò),可以知道可以添加哪些字段)# v = models.City.objects.all()# print(v)反向查找(如_ _name)# v = models.Province.objects.values('id','name','city__name')# print(v)# pro_list = models.Province.objects.all()# for item in pro_list:# print(item.id,item.name,item.city_set.filter(id__lt=3)) #id<3return HttpResponse("OK")--------------------------------models.py---------------------------------- class Province(models.Model):name = models.CharField(max_length=32)class City(models.Model):name = models.CharField(max_length=32)pro = models.ForeignKey("Province")
二、多對(duì)多查詢(ManyToMany)
?
----------------------------------------views.py------------------------------------------------- # 例二: def test(request): 1、創(chuàng)建:多表操作時(shí),可以忽略manytomany,不影響單表的字段創(chuàng)建# 如:# models.Book.objects.create(name='書名')# models.Author.objects.create(name='人名')正向查找 第三張表(因?yàn)閙在author里面)# obj,人,金鑫# obj = models.Author.objects.get(id=1)# # 金鑫所有的著作全部獲取到# obj.m.all()反向查找 第三張表(用...._set)# 金品買# obj = models.Book.objects.get(id=1)# # 金鑫,吳超# obj.author_set.all()2、性能方面:# 正向查找# 10+1 以下方法查詢數(shù)據(jù)庫次數(shù)多,性能不高# author_list = models.Author.objects.all()# for author in author_list:# print(author.name,author.m.all())#推薦此方法,用values來傳值# author_list = models.Author.objects.values('id','name','m', "m__name")# for item in author_list:# print(item['id'],item['name'],'書籍ID:',item['m'],item['m__name'])3、添加、刪除、清空、set#正向操作:# obj = models.Author.objects.get(id=1)# 第三張表中增加一個(gè)對(duì)應(yīng)關(guān)系 1 5# 增加# obj.m.add(5) 第三張表中增加一個(gè)對(duì)應(yīng)關(guān)系 1 5# obj.m.add(*[4,5]) 第三張表中增加一個(gè)對(duì)應(yīng)關(guān)系 1 4和1 5# obj.m.add(5,6)# 刪除第三張表中.....的對(duì)應(yīng)關(guān)系# obj.m.remove(5)# obj.m.remove(5,6)# obj.m.remove(*[5,6])# 清空# obj.m.clear()# 更新對(duì)應(yīng)關(guān)系 id=1的只能對(duì)應(yīng)1和對(duì)應(yīng)2和對(duì)應(yīng)3,id=1的其他對(duì)應(yīng)關(guān)系會(huì)被自動(dòng)刪掉# obj.m.set([1,2,3])# 反向操作:# obj = models.Book.objects.get(id=1)# obj.author_set.add(1)# obj.author_set.add(1,2,3,4)# ...同上return HttpResponse("OK") -----------------------------models.py-----------------------------class Book(models.Model):name =models.CharField(max_length=32)class Author(models.Model):name = models.CharField(max_length=32)m = models.ManyToManyField('Book') 系統(tǒng)默認(rèn)生成第三張表(關(guān)系表)
?
三、等于和不等于(補(bǔ)充)
models.tb.objects.filter(name='root') name 等于models.tb.objects.exclude(name='root') name 不等于models.tb.objects.filter(id__in=[11,2,3]) 在models.tb.objects.exclude(id__in=[11,2,3]) 不在
13、jQuery對(duì)象和DOM對(duì)象可以互相轉(zhuǎn)換
?
obj = document.getElementById('sel') $(obj) dom轉(zhuǎn)為jQuery$('#sel') $('#sel')[0] jQuery轉(zhuǎn)成dom對(duì)象select標(biāo)簽的Dom對(duì)象中有 selectedOptions來獲得選中的標(biāo)簽op1 = $('#sel')[0].selectedOptions dom標(biāo)簽再用jQuery對(duì)象的appendTo()方法,就可將選中的標(biāo)簽加到右邊的空標(biāo)簽里面$(op1).appendTo("#none") jQuery標(biāo)簽
14、JSONP原理(面試重點(diǎn)):跨域用的
jsonp的本質(zhì)就是動(dòng)態(tài)的在head里面創(chuàng)建script標(biāo)簽,執(zhí)行完后,又將其刪除
用jsonp原因:
由于瀏覽器的同源策略,所以跨域請(qǐng)求不行,所以要想跨域請(qǐng)求,需要用jsonp,jsonp不是一個(gè)技術(shù),而是一種策略,是小機(jī)智,由于script擴(kuò)展src不受同源策略保護(hù),所以可以動(dòng)態(tài)的生成一個(gè)script標(biāo)簽,加上src屬性,請(qǐng)求完成后就立即將此script標(biāo)簽刪除。
?
?自己寫一個(gè)jsonp:
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><input type="button" οnclick="jsonpRequest();" value="跨域請(qǐng)求" /><script>TAG = null;/* 定義一個(gè)全局變量tag*/function jsonpRequest() {TAG = document.createElement('script'); TAG.src = "http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403"; // 返回值是list([11,22,33,44])document.head.appendChild(TAG);}function list(arg) {console.log(arg); document.head.removeChild(TAG);}</script> </body> </html>14、cookie和session
Cookie:
就是保存在瀏覽器端的鍵值對(duì)
可以利用做登錄
1、保存在用戶瀏覽器
2、可以主動(dòng)清楚
3、也可以被“偽造”
4、跨域名cookie不共享
5、瀏覽器設(shè)置不接受cookie后,就登錄不上了
Cookie是什么?
客戶端瀏覽器上保存的鍵值對(duì)
客戶端瀏覽器上操作cookie 客戶端瀏覽器上操作cookiedom --> 麻煩jquery插件 --> 先準(zhǔn)備:(1)jquery.cookie.js(2)jquery.cookie.js用法:$.cookie()一個(gè)參數(shù):$.cookie(k) 獲得值兩個(gè)參數(shù):$.cookie(k,v) 設(shè)置值
?
Session:
session是服務(wù)器端的一個(gè)鍵值對(duì)
session內(nèi)部機(jī)制依賴于cookie
?
轉(zhuǎn)載于:https://www.cnblogs.com/tangtingmary/p/7994148.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的Django补充知识点——用户管理的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android studio发布项目到g
- 下一篇: oracle查询包含某个字段的表