Search code examples
pythonajaxdjangoes6-promise

Read Ajax post data in django


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?


Solution

  • 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))