【问题标题】:Getting None values for POST request (via the Axios library) sent to Python/Django获取发送到 Python/Django 的 POST 请求的 None 值(通过 Axios 库)
【发布时间】:2019-11-22 16:06:01
【问题描述】:

我正在使用 Django/Python 构建一个 Web 应用程序,并尝试使用 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 标头令牌很好。我是否遗漏了一些明显或误解了它的工作原理?

编辑:查看 Chrome 网络选项卡,似乎数据正在正确“发布”:

它显示了这个:

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

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

【问题讨论】:

    标签: javascript python django http-post axios


    【解决方案1】:

    像这样编写你的 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 请求时它返回一个空字典。

    【讨论】:

    • 成功了,谢谢!出于我的好奇……您能否解释一下为什么 Django 无法解析请求正文?使用 Django REST 框架时,body 似乎很容易解析。
    猜你喜欢
    • 2018-09-13
    • 2018-04-25
    • 2020-11-15
    • 2019-11-06
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    相关资源
    最近更新 更多