Today's Overview:
1. The difference between Related_name and Related_query_name
2, the use of Through_fields
3. Django Transaction Submission
4. The animation effect of liking
5, the principle of multi-level review
6. Uploading Files
7. Request.post Usage
8. If you keep the original page
The difference between Related_name and Related_query_name
Related_name, the name of the field used when defining the inverse association
Related_query_name Query Related_query_name + _set for reverse query
Example:
Class A:title = models. Charfield () obj = models. A.objects.get (id=1) Obj.b_set.all () Obj.xxxxxx_set.all () # related_query_name= ' xxxxxx ' Obj.uuuu.all () # Related_ Name= ' uuuu ' Obj.xobj.uclass b:xx. XXFK1 = models. Forignkey (related_name= ' x ') FK2 = models. Manytomany (related_name= ' U ') models. B.objects.filter (fk__title= ' xx ')
Second, the use of Through_fields
Through_fields = (the name of the field in the relationship table that establishes the FK relationship with the current table, the FK relationship field name that is established in the relational table with the target table)
Example:
Likes = models. Manytomanyfield (to='UserInfo', through="like", Through_ fields= ('new','user') #当前表是new表
Third, Django's transaction commit
Keep two SQL correct for insert action
From django.db import Transactionwith transaction.atomic (): models. Like.objects.create (NNEW_ID=NEW_ID,UUSER_ID=UID) models. News.objects.filter (id=new_id). Update (Like_count=f (' like_count ') + 1) Response.code = 999
The return value is encapsulated:
Class Baseresponse (object):d EF __init__ (self): Self.status = Falseself.data = Noneself.msg = Nonedef get_dict (self): Return Self.__dict__class likeresponse (baseresponse):d ef __init__ (self): Self.code = 0super (likeresponse,self). __ Init__ () Json.dumps (object. __dict__) Json.dumps (object. Get_dict ())
Four, likes the animation effect
* The $ (this) in the operation callback function in Ajax is not the original $ (this)
Workaround: Pass a variable to
Application content: Position:fixed,absolute,relative setinterval in CSS: Timers
JS Code:
$ (function () {bindlikeevent ();}); function Bindlikeevent () {$ ('. New-like '). Click (function () {///get current news id var newId = $ (this). attr (' New-i d '); var $this = $ (this); $.ajax ({url: '/do_like.html ', type: ' POST ', data: {' newId ': NewId}, DataType: ' JSON ', Success:function (ARG) {if (Arg.status) {var origin = $this. Text (); var count = parseint (origin); if (Arg.code = = 666) {$this. Text (count-1); Showlikecount ($this, '-1 '); }else if (Arg.code = = 999) {$this. Text (count + 1); Showlikecount ($this, ' +1 '); }}else{alert (arg.msg); }})})}function Showlikecount ($this, text) {var fontSize = 5; var top = 0; var right = 0; var opacity= 1; var tag = document.createelement (' span '); Tag.innertext = text; Tag.style.position = "absolute"; Tag.style.fontSize = fontSize + "px"; Tag.style.top = top + "px"; Tag.style.right = right + "px"; Tag.opacity = opacity; $this. After (tag); var obj = setinterval (function () {fontSize + = 5; Top-= 5; Right-= 5; opacity-= 0.1; Tag.style.fontSize = fontSize + "px"; Tag.style.top = top + "px"; Tag.style.right = right + "px"; Tag.style.opacity = opacity; if (opacity <= 0) {clearinterval (obj); Tag.remove ()}},100)}</script>
The principle of multi-level commentary
Knowledge Points: Dictionaries and lists, assignment by reference, changes all
Recursive
#!/usr/bin/python#-*-coding:utf-8-*-def Build_comment_data (li): dic = {} #定义一个空字典dic for item in Li:ite m[' children ' = [] #列表字典中新增一个key叫children, value is null dic[item[' ID ']] = Item #给空字典dic赋值 key is a dictionary in the list id,value is a list dictionary result = [] #定义一个空列表, save the final result for the item in Li: #item是li列表中的每一行字典 pid = item[' parent_id ') #pid是取每一行字典中parent_id Value if PID: #如果每一行字典中parent_id有值 dic[pid][' Children '].append (item) #则找到字典中pid的那一行, add item to children Else:result.append (item) #否则把parent_id没有值的加到result列表中 # for I in Result: # print (i) return R Esultdef Build_comment_tree (com_list1): TPL = "" "<div class=" item> <div class= "title" >{0 }:{1}</div> <div class= "body>{2}</div> </div>" "" #这里的 {0}{1}{2} are placeholder HT Ml= "" # Print (com_list1) # for I in Com_list1: # print (i) for item in com_list1:if not item[' child Ren ']: #如果字典中没有children HTML + = Tpl.format (item[' user '],item[' content '], "") #format给占位符传值, the third value is empty else:html + = Tpl.f Ormat (item[' user '], item[' content '), Build_comment_tree (item[' Children ']) #如果有子children则把build_comment_tree函数自 have done it again, pass the child in (the child is also a complete dictionary) return Htmldef comment_list (): Li = [{' id ': 1, ' user ': ' Silver Qiu Liang ', ' content ': ' Fill me up ', ' parent_id ': none}, {' id ': 2, ' user ': ' Silver Fall good ', ' content ': ' Tube my bird thing ', ' parent_id ': none}, {' id ': 3, ' user ': ' Type spectrum ', ' Content ': ' You illiterate ', ' parent_id ': 1}, {' id ': 4, ' user ': ' detailed ', ' content ': ' Envy you people who are disgraced ', ' parent_id ': 2}, {' id ': 5, ' user ': ' Silver Autumn good ', ' content ': ' You are rogue ', ' parent_id ': 3}, {' id ': 6, ' user ': ' Silver Autumn good ', ' content ': ' You cold-hearted ', ' parent_id ': 5}, {' id ': 7, ' user ': ' Silver Autumn good ', ' content ': ' You are ruthless ', ' parent_id ': 4}, {' id ': 8, ' user ': ' Silver Autumn good ', ' content ': ' You unreasonable take Noise ', ' parent_id ': 4},] com_list = Build_comment_data (li) html = build_comment_tree (com_list) print (HTML) if __n ame__ = = ' __main__ ':Comment_list ()
Knowledge Review:
L = [1,2,4,5,6] #迭代器for i in L: #迭代器对象 # iterator Error l.__iter__ () next () null case, iterator object not for J in L: print (i)
Reference type Application:
Li = [{' user ': ' xxx ', ' pwd ': ' xxx ', ' id ': 1, ' children ': [], ' parent_id ': None}, {' user ': ' xxx ', ' pwd ': ' xxx ', ' id ': 2, ' Children ": [], ' parent_id ': None}, {' user ': ' xxx ', ' pwd ': ' xxx ', ' ID ': 3, ' children ': [], ' parent_id ': 1}, {' user ': ' xxx ', ' PWD ': ' xxx ', ' ID ': 4, ' children ': [], ' parent_id ': 2}, {' user ': ' xxx ', ' pwd ': ' xxx ', ' ID ': 5, ' children ': [], ' parent_id ': 1}, { ' User ': ' xxx ', ' pwd ': ' xxx ', ' ID ': 6, ' children ': [], ' parent_id ': 3}, ' #结果: # result = [# {' user ': ' xxx ', ' pwd ': ' xxx ', ' id ': 1, ' Children ": [{' user ': ' xxx ', ' pwd ': ' xxx ', ' ID ': 3, ' children ': [{' user ': ' xxx ', ' pwd ': ' xxx ', ' ID ': 6, ' children ': [], ' parent ' _id ': 3},], ' parent_id ': 1},{' user ': ' xxx ', ' pwd ': ' xxx ', ' ID ': 5, ' children ': [], ' parent_id ': 1},], ' parent_id ': none},# {' User ': ' xxx ', ' pwd ': ' xxx ', ' id ': 2, ' children ': [{' user ': ' xxx ', ' pwd ': ' xxx ', ' ID ': 4, ' children ': [], ' parent_id ': 2},], ' parent_id ': none},#]dict = {}for I in li:dict[i[' id ']] = IA = []for k,v in Dict.items (): If v[' parent_id ']: dict[v[' parent_id ']]["Children"].append (v) else:a.append (v) print (a)
JavaScript implements multilevel Comments:
<! DOCTYPE html>Vi. Uploading Files-Based on Formdata
-Disadvantages, poor compatibility
-Advantages, Ajax direct Send
-Pseudo-Ajax for better compatibility
-IFRAME, natural local Refresh
-form, natural full page refresh
Vii. usage of Request.post-How do I send post data through Python code? url:http://127.0.0.1:8003/asset.html Client: Import requests# response = Requests.get (' http://127.0.0.1:8003/asset.html ') # print (response.text) data_dict = {' K1 ': ' v1 ', ' K2 ': ' v2 '}# content-type:application/x-www-form-urlencoded# response = Requests.post (' http://127.0.0.1:8003/asset.html ', data=data_dict) # print (response.text) # content-type:appcation/ Jsonresponse = Requests.post (' http://127.0.0.1:8003/asset.html ', json=data_dict) print (Response.text) Server Django:from DJANGO.VIEWS.DECORATORS.CSRF Import csrf_exempt,csrf_protect@csrf_exemptdef Asset (Request): if Request.method = = "Get": Return HttpResponse (' Received: Get ') else:print (request. Post) print (Request.body) return HttpResponse (' Received: Post ')
Viii. if the original page is retainedRequest. Getfrom django.http.request Import querydict Important: POST, do not write action
Example:
def host_list (Request): print (Request. Get,type (Request. GET) # request. get._mutable = True obj = querydict (mutable=true) obj[' _zhaofengfeng '] = Request. Get.urlencode () # page=10&id=1 Url_param = Obj.urlencode () hosts = [' c1.com ', ' c2.com ', ' c3.com '] return render (Request, ' host_list.html ', {' hosts ': Hosts, ' Url_param ': Url_param}) def add_host (request): if Request.method = = "GET": return render (Request, ' add.html ') else: url_params = Request. Get.get (' _zhaofengfeng ') host = Request. Post.get (' hostname ') URL = "/host_list.html?" +url_params return redirect (URL)
Python Automation Dev-[22nd day]-bbs Multi-level comments, likes, upload files