Reputation: 1011
I am getting a 403 forbidden error and WARNING csrf.py _reject: Forbidden (CSRF token missing or incorrect.)
is django logs.
Here is my html, jquery-
function req() {
var server_id = $( "#server option:selected" ).val();
$.post("/sp/add_req", JSON.stringify({ cir: {{ cir }}, server_id: server_id, csrfmiddlewaretoken: {{ csrf_token }}}), function (data) {
console.log(data)
});
}
and views.py-
def add_request(request):
....
return JsonResponse({'success': True})
I have the 'django.middleware.csrf.CsrfViewMiddleware' in settings. What is wrong and how to solve this?
Upvotes: 1
Views: 1020
Reputation: 3108
{% csrf_token %}
will render as <input type="hidden" name="csrfmiddlewaretoken" value="xxxxxx">
. Therefore, you could render it separately and then create the JSON object with javascript.
var csrfToken = $('[name="csrfmiddlewaretoken"]').val();
var data = {'csrfmiddlewaretoken': csrfToken);
and then send the data along on your post. I prefer to use the Fetch API to post.
Upvotes: 2
Reputation: 3022
When using AJAX, you need to pass the CSRF token along with your requests. See more at the official guide: https://docs.djangoproject.com/en/2.1/ref/csrf/#ajax
Upvotes: 0