Django裏面,經過Html頁面提交的數據,能夠經過在View裏面定義的函數經過request參數獲取。簡單的說,主要能夠分出3種狀況。
html
HTML頁面傳遞來的單個數據, 好比radiobox或者text 能夠經過request.POST.get獲取python
HTML頁面傳遞來多個數據,好比checkbox或者option, 能夠經過request.POST.getlist獲取django
HTML頁面上傳了一個文件,html端須要代表enctype,表示這是一個文件而不是字符串;後臺須要經過request.FILES.get獲取這個文件的地址,而後經過chunk分塊寫入指定的地址ide
如今來看看實例:函數
HTML頁面
ui
upload.htmlspa
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/upload/" method="POST" enctype="multipart/form-data"> <p> <input type="text" name="user" placeholder="用戶名" /> </p> <p> <input type="password" name="pwd" placeholder="密碼" /> </p> <p> 性別: 男<input type="radio" name="gender" value="1"/> 女<input type="radio" name="gender" value="2"/> 中<input type="radio" name="gender" value="3"/> </p> <p> 愛好: 音樂<input type="checkbox" name="favor" value="11"/> 武術<input type="checkbox" name="favor" value="22"/> 電玩<input type="checkbox" name="favor" value="33"/> </p> <p> <select name="city" multiple> <option value="sh">上海</option> <option value="bj">北京</option> <option value="tj">天津</option> </select> </p> <p> <input type="file" name="fafafa" enctype="multpart/form-data"/> </p> <input type="submit" value="提交"/> </form> </body> </html>
視圖函數orm
view.pyserver
def upload(request): if request.method == "GET": return render(request, 'upload.html') elif request.method == "POST": v=request.POST.get('user') print(v) # radio v = request.POST.get('gender') print(v) v = request.POST.getlist('favor') print(v) v = request.POST.getlist('city') print(v) obj = request.FILES.get('fafafa') print(obj, type(obj), obj.name) import os file_path = os.path.join('upload', obj.name) print(file_path) f = open(file_path, mode="wb") for i in obj.chunks(): f.write(i) f.close() from django.core.files.uploadedfile import InMemoryUploadedFile return render(request, 'upload.html') else: # PUT,DELETE,HEAD,OPTION... return redirect('/upload/')
界面htm
輸入下面的值進行提交
成功獲取結果
System check identified no issues (0 silenced). July 06, 2017 - 15:25:56 Django version 1.11, using settings 'Django.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. 阿拉丁 2 ['22', '33'] ['bj', 'tj'] statements.pdf <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> statements.pdf upload\statements.pdf [06/Jul/2017 15:26:10] "POST /upload/ HTTP/1.1" 200 1267
確認成功上傳文件