2

I have trouble getting the data from an ajax request.I can access the data through Djangos' request.GET (and other POST, DELETE etc. headers), but not with the REST request.data (or request.body) which returns an empty dict. My ajax call:

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'

    });
}

My 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')    

1 Answer 1

4

From 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.

As long as you pass data into your views through query parameters, irrespective of the verb that you use (be it GET, POST or any other), they will be available in your request.query_params instead of request.data.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the answer and additional explanation. The problem was solved in a sec. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.