Ajax POST not sending data when calling 'request.POST' in Django view

后端 未结 2 814
礼貌的吻别
礼貌的吻别 2020-12-06 07:31

I am attempting to get an Ajax POST to to send data to my view so I can manipulate my data there, when I click on a div with class up-arrow

相关标签:
2条回答
  • 2020-12-06 07:41

    When posting JSON data with application/json you need to use request.body instead of request.POST.

    Like so:

    class VoteUpPost(View):
        def post(self, request):
            print(request.body)
            data = json.loads(request.body)
            return JsonResponse({'status': True})
    

    Also as Jacques mentioned, make sure to update your js to pass a JSON string.

    Change:

    data: {'dane': 123456789101112},
    

    To:

    data: JSON.stringify({'dane': 123456789101112}),
    
    0 讨论(0)
  • 2020-12-06 07:52

    Django request can only parse application/x-www-form-urlencoded and multipart/form-data to request.POST. For other content types you have to use request.body property. for assertion of content type you can get the content type from request.META.get('CONTENT_TYPE')

    def sample_view(request):
        if request.META.get('CONTENT-TYPE') == 'application/json':
            data = json.loads(request.body)
            return JsonResponse({'any-message':'Hello'})
    
    0 讨论(0)
提交回复
热议问题