QueryDict is always empty from AJAX POST

I saw several of these questions, but I tried to implement their solutions, and it did not work for me.

I am trying to send the main AJAX request to a django view using POST. Here is my jQuery:

$('#save-button').click(function() { var names = ['BLOGGS Joe', 'SMITH John']; data = JSON.stringify(names); $.ajax({ "contentType": "application/json; charset=utf-8", "data": data, "url" : "/ajax/myteam/save/", "type": "POST", "success": function(response) { } }); }); 

And here is my view of Django:

 def myteam_save(request): if request.method == 'POST': if request.POST: print 'Hurray' else: print 'Boo' response = HttpResponse(json.dumps({'code':'ok'}), content_type='application/json') return response 

When I examine what is happening in Firebug, I see that the message is created when I intend, but the QueryDict object is from the query. POST is always empty.

I was careful about csrf tokens, I think, and even tried to disable "django.middleware.csrf.CsrfViewMiddleware" in my settings, but this does not seem to have an effect.

What am I doing wrong?

Thanks for your help!

+5
source share
1 answer

Django does not de-serialize JSON payload for you. request.POST intended for use for the hosted HTML-forms, etc.

For JSON payloads, you must disinfect the request body yourself, for example: json.loads(request.body) .

( request.body is how you access the raw payload).

+5
source

Source: https://habr.com/ru/post/1202355/


All Articles