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 Noneself.request.POST.get('company_id', None) --> returns Noneself.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")
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 }}'}
});