gamer
gamer

Reputation: 613

Cant get Ajax Post data in view

I am sending a post request to view . everything is fine but no data is sent by ajax. In ajax call i checked variable there is data exist but not when its sent in view.

my ajax is

  $.post({
                url: '/projpost/message/{{project.id}}',
                data: {
                'message': message
                },
                success: function (data) {
                    alert(message);   //working perfect


                }
            });

In view

@csrf_exempt
def message(request,id):
    print(request.POST['message'])
    return HttpResponse(content_type="application/json" )

But I am getting error

MultiValueDictKeyError at /projpost/message/5/
'message'

Upvotes: 1

Views: 208

Answers (2)

Rich Tier
Rich Tier

Reputation: 9441

The data is in request.data.

request.POST is only populated for when forms are submitted, or when you set the header to look like a form submission.

Upvotes: 1

Zollie
Zollie

Reputation: 1211

Try:

@csrf_exempt
def message(request,id):
    print(request.POST.get('message'))
    # or print(request.POST.get('message', ''))
    return HttpResponse(content_type="application/json" )

But if you will find that request.POST is empty, then you will have to work with only the request, not with request.POST

Upvotes: 1

Related Questions