Ajax POST to view not displaying content..

Hello, first time here and I’ve seen like 300 StackOverflow issues and couldn’t solve it.

I want something simple, send this POST request:

    headers: { 'content-type': 'application/json;charset=UTF-8'},
    method: 'post',
    url: 'http://localhost:8000/ledger/store',
    data: {
        ledger_id: "dxglowjdnomy",
        transactions: [{
            id: ".z9ditcvddqf", 
            section: 3, 
            description: "fasfd", 
            subsection: 8, 
            value: 4234, 
            date: "18/04/2020"}]

JSON is well formatted, if there is any issue is because it just an example of the data I’m sending.

And here is my Django view, nothing fancy:

def store(request):
    req_data = request.POST.get('ledger_id')                                                                                                   
    return JsonResponse({ 'data' : req_data })

But all i get in return is {data:null}.

I tried serializers.serialize('json', request.POST.get('ledger_id')), but I got MultiValueDictKeyError at /ledger/store 'ledger_id'

In the frontend I’ve also tried stringifying the json object, but no luck either…

May it be a problem with CORS? I’m using different servers for this app…

I really don’t know what I’m doing wrong. If someone can please help me at least to point in the right direction, it will be really appreciated.

Thanks in advance.


This isn’t a CORS problem since you’re getting the content back.

Did you try print(request.POST.keys()), or using PDB to trace in your view?

If axios posts data through as JSON rather than form data, you’ll want to retrieve it with json.loads(request.body), rather than through request.POST.

Hope that helps,


1 Like

Great! json.loads(request.body) was the answer.

I’ll write the view so it might be helpful for others in the future:

def store(request):
    req_data = json.loads(request.body)
    return JsonResponse({ 'data' : req_data })

I still don’t know why all the tutorials and youtube videos that I watched used the request.POST.get() approach… maybe because in django 2 was different?

Thanks a lot!

I believe the answer has to do with the content type of the request. The request you listed used application/json so the body of the HTTP POST request would be expected in JSON format (i.e. non-form data). request.POST is for data submitted with an application/x-www-form-urlencoded type (which is the default for web forms).

The relevant Django documentation is here:

If you need to access raw or non-form data posted in the request, access this through the HttpRequest.body attribute instead.