Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forbidden (CSRF token missing or incorrect) Django error

I am very new to Django. The name of my project is rango and I have created a URL named '/rango/tagger' that is supposed to send an object.

In my java-script, I have tried to communicate with this route by sending it an ajax request as follows:

function send()
{
  obj = {content:$("#content").val()};
  $.post('/rango/tagger',obj,function(data){
    console.log(data);
  })
}

I have included the {% csrf_token %} in my template. However, it gives me the error as follows:

Forbidden (CSRF token missing or incorrect.): /rango/tagger
[31/Jan/2016 09:43:29] "POST /rango/tagger HTTP/1.1" 403 2274

My function tagger in views.py is as follows:

def tagger(request):
return render(request,'rango/index.html',RequestContext(request))

And I have also defined it in my URL pattern. I suspect my function tagger returns an incorrect value or data (made the change from HttpResponse(request) to the line above based on other SO solutions).

However, it does not seem to work for me. Where am I wrong?

like image 416
nerdier.js Avatar asked Jan 31 '16 09:01

nerdier.js


2 Answers

The AJAX request must include the csrf, because it's another HTTP request, so please copy this code:

// using jQuery
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));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

After you setup that before sending AJAX request to set the csrf.

source

like image 138
Emad Mokhtar Avatar answered Sep 18 '22 12:09

Emad Mokhtar


Or you can do it in a short way (without the codes written above), but sending all the data in the inputs field:

$.post(
    '/rango/tagger',
    $("#id_of_your_form").serialize(),
    function(data) {
        console.log(data);
    }
)
like image 30
Yaaaaaaaaaaay Avatar answered Sep 22 '22 12:09

Yaaaaaaaaaaay