django -- ajax 403 错误

早知如此绊人心,何如当初莫相识。 ——秋风词


在使用 ajax 实现文章点赞功能的时候,请求出现了 403 的错误

POST http://localhost:8000/likes/1 403 (FORBIDDEN)


在官网上已经有了相应的解决方法和实例,出现这个问题的主要原因是没有添加 csrf 认证,解决的基本原理就是在post数据里面添加csrf信息

While the above method can be used for AJAX POST requests, it has some inconveniences: you have to remember to pass the CSRF token in as POST data with every POST request. For this reason, there is an alternative method: on each XMLHttpRequest, set a custom X-CSRFToken header to the value of the CSRF token. This is often easier, because many JavaScript frameworks provide hooks that 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 will be set if you’ve enabled CSRF protection for your views as outlined above.

将下面的代码添加到同一个 ajax js 文件中或代码片段中即可解决问题

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.substring(name.length + 1));  
    return cookieValue;  

function csrfSafeMethod(method) {  
    // these HTTP methods do not require CSRF protection  
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));  
    beforeSend: function(xhr, settings) {  
    var csrftoken = getCookie('csrftoken');       
    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {  
            xhr.setRequestHeader("X-CSRFToken", csrftoken);