I am trying to send a DELETE request from a form in Django taking help from jQuery referring following link below;
https://baxeico.wordpress.com/2014/06/25/put-and-d
It's probably the ordering of your middleware. When the request is received, the middleware is processed in the order that it is specified in the settings. In your case, that means the CSRF middleware is run first, sees that the request is a POST without a CSRF token, and raises the error.
Try moving your HttpPostTunnelingMiddleware before the CsrfViewMiddleware.
The problem is with your javascript code. You are submitting the form as a regular POST request and not using the $.ajax javascript code at all.
You should include jquery in a separate script tag, like this:
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
Then in another script tag you put your code:
<script>
$('#delete').submit(function(e) {
// do NOT submit the form as a regular POST request
e.preventDefault();
var object_to_delete_id = $('#object_to_delete_id').val();
$.ajax({
type: 'POST',
url: '/your-view-url/' + object_to_delete_id,
success: function() {
alert('Object deleted!')
},
headers: { 'X_METHODOVERRIDE': 'DELETE' }
});
});
<script>
Here I'm assuming that you have the id of the object you want to delete in a form field like this:
<form method="post" id="delete" name="delete" action="">
{% csrf_token %}
<input type="text" id="object_to_delete_id" />
<input type="submit" value="Delete" />
</form>
Please pay attention to Django CSRF protection on your Ajax call, you should write some javascript to set your CSRF cookie value in the request, as explained in the Django documentation.
Also returning a HttpResponseRedirect to an Ajax call doesn't make much sense, because the browser will not redirect to that page as it would happen with a regular POST request.
I'd suggest to study a little bit more how jquery and Ajax requests work, before digging in more complex examples like this. ;)