Forbidden (csrf Token Missing Or Incorrect.) | Django And Ajax
:( I am making ajax requests, but I get this error: Forbidden (CSRF token missing or incorrect.): /manager/ajax/ [23/Jun/2020 00:00:46] 'POST /manager/ajax/ HTTP/1.1' 403 2517 [23/
Solution 1:
Take a look of the source code below, you need explicitly tell Django this request if called using XMLHttpRequest
. better avoid to use is_ajax
to detect ajax, since it will be deprecated in future versions
defis_ajax(self):
warnings.warn(
'request.is_ajax() is deprecated. See Django 3.1 release notes ''for more details about this deprecation.',
RemovedInDjango40Warning,
stacklevel=2,
)
returnself.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
Add these lines in your header, use of X-CSRFToken
is prefered for ajax request since it also support other request method like DELETE
, PUT
, etc
# django internllay change '-' to '_' and add prefix HTTP in front of the value# so 'X-Requested-With' becomes HTTP_X_REQUESTED_WITH, which is used by is_ajax function
{
'X-Requested-With': 'XMLHttpRequest',
'X-CSRFToken': <your_csrftoken_value>
}
EDIT
$('#sub-btn').click(function(e){
e.preventDefault();
$.ajax(
{
type:"POST",
beforeSend: function (xhr) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('X-CSRFToken', <your_csrftoken_value>);
},
url: <your_url>,
data: {test: 'test'},
success: function(data){
console.log(data)
}
});
})
Also, if you use jQuery
and send data using this format, you could receive data in request.POST
Post a Comment for "Forbidden (csrf Token Missing Or Incorrect.) | Django And Ajax"