Environment
Django 1.8.3
Error Description
POST http://localhost:8000/ajax_query_data/ 403 (FORBIDDEN)
Solutions
The Django official documentation reads as follows:
https://docs.djangoproject.com/en/dev/ref/csrf/#ajax
Ajaxwhile the above method can be used for AJAX POST requests, it has some inconveniences:you had to remember to pass th e CSRF token in as post data with every POST request. For this reason, there are an alternative method:on each xmlhttprequest, set a custom X-csrftoken header to the value of T He CSRF token. This is often easier, because many JavaScript frameworks provide hooks the Allow headers to be set on every request. As a first step, you must get the CSRF token itself. The recommended source for the token is the Csrftoken cookie, which'll be set if you've enabled CSRF protection for your Views as outlined above.
There is an example in the official document, the basic principle is to add csrf information in the post data
Summarize and try the next, add the following code to the JS file inside the problem can be resolved:
function GetCookie (name) {var cookievalue = null; if (document.cookie && document.cookie! = ") {var cookies = Document.cookie.split (';'); for (var i = 0; i < cookies.length; i++) {var cookie = Jquery.trim (Cookies[i]); Does this cookie, string begin with the name we want? if (cookie.substring (0, name.length + 1) = = (name + ' = ')) {cookievalue = decodeURIComponent (Cookie.substri Ng (Name.length + 1)); Break }}} return cookievalue;} var csrftoken = GetCookie (' csrftoken '); function Csrfsafemethod (method) {//These HTTP methods do not require CSRF prot Ection return (/^ (get| head| options| TRACE) $/.test (method));} $.ajaxsetup ({beforesend:function (XHR, settings) {if (!csrfsafemethod (settings.type) &&!this.crossdom Ain) {Xhr.setrequestheader ("X-csrftoken", Csrftoken); } }});
Copyright NOTICE: This article for Bo Master original article, welcome reprint, reproduced please indicate the source.
Django Ajax Request 403 (FORBIDDEN) workaround