2

I got an Ajax request using promise in my django project:

var path = window.location.pathname;
fetch('/getblogs/', {
  method: 'post',
  headers: {
    'Accept': 'application/json, text/plain, */*',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({'path': path})
}).then(function (response) {
  return response.json();
});

The request is in a js file and there is no form.

I'm trying to read data in my views.py like this:

@csrf_exempt
def get_blogs(request):
    cat_id = request.POST.get('path')
    print("RESULT: " + str(cat_id))

But in output I get:

RESULT: None

Am I missing somthing in reading post data or there is something wrong with my ajax request?

Ghasem
  • 14,455
  • 21
  • 138
  • 171

2 Answers2

3

I think you can try like this:

import json

@csrf_exempt
def get_blogs(request):
    cat_id = json.loads(request.body).get('path')
    print("RESULT: " + str(cat_id))
ruddra
  • 50,746
  • 7
  • 78
  • 101
1

From the Django documentation

HttpRequest.POST

A dictionary-like object containing all given HTTP POST parameters, providing that the request contains form data. See the QueryDict documentation below. If you need to access raw or non-form data posted in the request, access this through the HttpRequest.body attribute instead.

Try using json.loads(request.body)['path']

Community
  • 1
  • 1
nightgaunt
  • 890
  • 12
  • 30