AJAX call to Django View returns None to data

Viewed 202

I have been trying to get data that I send using AJAX with a Django view. I have this AJAX call

$.ajax({
    method: "POST",
    url: "{% url 'change_publish_status' %}",
    value: {"company_id": company_id, "published": published},
    dataType: 'json',
    headers: {"X-CSRFToken": '{{ csrf_token }}'}
});

and I'd like to access the company_id and the published variables from the django view. I have tried many things

  • self.request.POST.get('company_id') --> returns None
  • self.request.POST.get('company_id', None) --> returns None
  • self.request.body --> returns b''

This is my view right now

@method_decorator(login_required, name='dispatch')
class ChangePublishStatus(TemplateView):
    def post(self, *args, **kwargs):
        company_id = self.request.POST.get('company_id', None)
        published_status = self.request.POST.get('published') == "true"

        print(company_id)

        return JsonResponse({"status": "ok"})

    def get(self, *args, **kwargs):
        return redirect("list")
1 Answers

To send the data in the POST call, pass the data in the data argument rather than value.

$.ajax({
    method: "POST",
    url: "{% url 'change_publish_status' %}",
    data: {"company_id": company_id, "published": published},
    dataType: 'json',
    headers: {"X-CSRFToken": '{{ csrf_token }}'}
});
Related