day18-django 單選框,多選框,文件上傳后台獲取數據


一、引子

  之前我們學了django 往后台提交數據的方法,get(在url 中拼接),post (request中POST) ,后台獲取數據的方法用get方法獲取數據(renquest.GET.get/request.POST.get)。

今天我們學習,當往后台提交單選框,多選框,文件上傳時,后台如何獲取數據。

二、單選框,多選框后台獲取數據

  2.1 單選框后台一樣用get 獲取數據,

  2.2 多選框 后台使用 getlist 獲取數據,獲取到一個列表,

  html文件:  

  

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6 </head>
 7 <body>
 8     <h1> 注冊頁面</h1>
 9     <h5> 多選框,單選框,文件傳送到后台</h5>
10     <h5>多選框后台用 getlist,之前學習的都是get 方法</h5>
11 
12     <form action="\login\" method="post" enctype="multipart/form-data">
13         性別選項:
14         <p></p>
15         <!--  單選框 互斥 使用同一個  name 之前在html已經有學習到了,-->
16         <p>男:<input type="radio" name="gender" value="1"></p>
17         <p>女:<input type="radio" name="gender"  value="0"></p>
18 
19         <p></p>
20 
21         愛好選項:
22             <!--  多選框 使用同一個  name 之前在html已經有學習到了,-->
23         <p>籃球:<input type="checkbox" name="aihao" value="LQ"></p>
24         <p> 排球:<input type="checkbox" name="aihao" value="PQ"></p>
25         <p>足球:<input type="checkbox" name="aihao" value="ZQ"></p>
26         <p>看球:<input type="checkbox" name="aihao" value="KQ"></p>
27 
28         <p></p>
29 
30         文件上傳
31 
32         <input type="file" value="fa" name="wj">
33         <p></p>
34         <input type="submit" value="提交">
35     </form>
36 
37 </body>
38 </html>

后台獲取數據:

后台代碼

 1 def login(request):
 2     if request.method=="POST":
 3         gender=request.POST.get("gender")
 4         AH=request.POST.getlist("aihao")
 5         
 6         print(gender)
 7         print(AH)
 8         return HttpResponse("ok")
 9 
10     return render(request,"login.html")

三、上傳文件到后台

  3.1 文件上傳后台,需要在 form 標簽中添加  

    enctype="multipart/form-data"

  views 代碼

 1 def login(request):
 2     if request.method=="POST":
 3         gender=request.POST.get("gender")
 4         AH=request.POST.getlist("aihao")
 5         # print(gender)
 6         # print(AH)
 7         obj=request.FILES.get("wj")   
 8         print(type(obj))
 9         filepath=os.path.join("upload",obj.name)
10         f=open(filepath,mode='wb')
11         for i in obj.chunks():
12             f.write(i)
13         f.close()
14 
15         return HttpResponse("ok")
16 
17     return render(request,"login.html")

四、總結

  1.  request.GET/POST/FILES(后台獲取文件的)
  2. request.GET/POST.getlist("name")   獲取chekcbox等多選內容
  3. 上傳文件,form標簽做特殊處理(enctype="multipart/form-data")
1
2
3
4
5
6
7
8
9
obj  =  request.FILES.get( "name" )
 
obj.name
 
=  open (obj.name,mode = "wb" )
 
for  item  in  obj.chunks():
     f.write(item)
f.close()

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM