python - Django Rest request.data 对象为空

标签 python ajax django django-rest-framework

我无法从ajax请求获取数据。我可以通过Django的request.GET(和其他POST、DELETE等 header )访问数据,但不能使用REST request.data(或request.body)它返回一个空字典。 我的 ajax 调用:

function getMeal(event)
{
  var tmp       = event._id.split("_")
  var database  = tmp[0]
  var mealId    = tmp[1]
  $.ajax(
  {
    type: "GET",
      url: "{% url 'updateEatenMealAjax' %}",
      data:
      {
          'database': database,
          'mealId'  : mealId,

      },
      success: function(data, textStatus, jqXHR)
      {
        $('#update_EatenMeal_FormBody').html(data);
      },
      dataType : 'html',
      async: 'false',
      contentType: 'application/json'

    });
}

我的 Django View :

@login_required
@api_view(["PUT", "GET", "DELETE"])
@csrf_protect
@ensure_csrf_cookie
def updateEatenMealAjax(request):

    args = {}
    eaten_object = None
    # WHICH DATABASE DOES THIS FOOD ITEM BELONG TO
    database = request.data.get('database')
    mealId  = request.data.get('mealId')    

最佳答案

来自 Django-REST-framework documentation :

request.data returns the parsed content of the request body. This is similar to the standard request.POST and request.FILES attributes

request.query_params is a more correctly named synonym for request.GET. For clarity inside your code, we recommend using request.query_params instead of the Django's standard request.GET. Doing so will help keep your codebase more correct and obvious - any HTTP method type may include query parameters, not just GET requests.

只要你通过 query parameters 将数据传入你的 View 中即可,无论您使用什么动词(GETPOST 或任何其他动词),它们都将在您的 request.query_params 中提供request.data

关于python - Django Rest request.data 对象为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37161513/

相关文章:

ajax - 无效的 JSON GET 请求 Express.js

python - 为什么 'django.contrib.admin.sites' 没有属性 'register' ?

python - 生成随机数以获得固定和(python)

python - 如何在 python 中加入 2 个字典列表?

php - 使用 AJAX/jQuery 设置 $_SESSION | PHP session 不工作?

django - 函数内的 Postgres 咨询锁允许并发执行

python - Django 模板 : accessing the previous and the following element of the list

python - 在平局的情况下,Python 选择哪个最大值?

python - 删除 3D numpy 数组中的行

jquery - 如何使用 jquery 和 ajax 从数据库中的数据创建 HTML 表格