[Fixed]-Deleting an object with Ajax in Django not working

1👍

Your ajax url isn’t a valid url

 $.ajax({
         type: "POST",
         url: "{% url 'del_dept' %}",
         data: { 'id':id },
         beforeSend: function(xhr) {
            xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
         },
         success: function(response){
         alert(response.success);
        }
        });

Note I have changed del_dept to use the django url template tag. You may need to include a namespace here but it doesn’t look like you do from what you have shown

For post requests, you will also need to include a csrf token.

Also, your view is looking in the wrong place for the id, post data goes into request.POST so your query becomes the following

department = Department.objects.get(pk=int(request.POST['id']))

You may not need to cast the id as an int since it might already be one.

👤Sayse

Leave a comment