post請求根據 request header 中的 Content-Type 的不同,相應的處理也不同
1、Content-Type : multipart/form-data 或者 application/x-www-form-urlencoded 類型。
x-www-form-urlencoded 類型必須 符合 key=value&key=value 的書寫方式,可以在前端 import qs,通過qs.stringify(object) 方式將js對象轉換為 key=value&key=value ,並對其中的一些特殊字符進行了轉化。
通過 request.POST.get('key') 或者 request.POST['key'] 獲取 值。
# form-data / application/x-www-form-urlencoded print(request.body) print(request.POST.get('username')) admin print(request.POST['username']) admin
django 對 request.body 的數據做了處理,然后填充到 request.POST 中。
2、Content-Type 為 application/json 或者 postman 中 的 raw /json 類型時。
此時 ajax傳入的參數為 js對象。 request.body 中是 btypes 類型的數據, request.POST 中為 空的 QueryDict 數據。django沒有從body中處理數據並填充POST,需要手動處理。
使用 import json , json.loads(request.body) 解析body, 然后使用 json.loads(request.body).get(key) 或 json.loads(request.body)[key]獲取數據。
# application/json print(request.body) # b"{username:admin}" print(json.loads(request.body)) #admin print(json.loads(request.body).get('username')) #admin