获取发送到 Python/Django 的 POST 请求的 None 值(通过 Axios 库)

Getting None values for POST request (via the Axios library) sent to Python/Django

我正在使用 Django/Python 构建一个网络应用程序,并尝试使用 Axios 库(在 Vue.js 代码内)通过 POST 请求将数据发送到控制器。

POST QueryDict 似乎是空的,我不明白为什么会这样:

changeCountry: function(e, id){
  console.log("Let's change the country")
  console.log(e.target.value) // is printing correctly
  console.log(id) // also printing correctly

  axios({
    method: 'post',
    url: '/template/country',
    data: {
      id: id,
      country: e.target.value
    },
    headers: {
      'X-CSRFToken': "{{csrf_token}}"
      }
    })
    .then(function (response) {
      alert(response.data); // this is returning what I expect
    })
    .catch(function (error) {
      console.log(error);
    })
  },

Python 方法如下所示:

def update_template_country(request):

  pprint(request.POST) # prints an empty QueryDict

  id = request.POST.get('id')
  country = request.POST.get('country')

  print(id, country) #prints None None

  return HttpResponse("The country is changed") # this is being returned back to the client

顶部的 console.log 消息打印出了我的预期,并且由于没有错误,我假设 CSRF header 令牌没有问题。我是不是错过了一些明显的东西或者误解了它是如何工作的?

编辑:查看 Chrome 网络选项卡,数据似乎 'POSTed' 正确:

显示的是:

{"id":"593ff2270098e6e8d3292b60","country":"US"} 

这正是我所期望的,所以我怀疑问题出在 Django 上。但我看不出那可能是什么。

这样写您的 python POST 请求:

def update_template_country(request):
  data = json.loads(request.body)
  id = data["id"]
  country = data["country"]
  '''Any other function you want to perform'''
  return HttpResponse(json.dumps({'message':'The country is changed'},status=200)

基本上问题出在 POST 请求的格式上,Django 无法正确解析它,这就是为什么当您打印 POST 请求时 return 一个空字典。