Search code examples
jquerydjango-formsdjango-rest-frameworkdjango-csrf

Django Rest Framework CSRF token failed


First of all I must to say that all solutions, which I found here, didn't help me.

My error

detail: "CSRF Failed: CSRF token missing or incorrect."

My react form

    render: function(){
    return(
    <div className="col-lg-12 mrg">
        <h3 className="ui dividing header">Add comment</h3>
        <form method="POST" role="form" className="ui reply form" onSubmit={this.handleSubmit}>
            <div className="field">
                <textarea ref="text"></textarea>
            </div>
            <button className="ui blue labeled submit icon button" type="submit" value="SUBMIT" name="submit"><i className="icon edit"></i> Send</button>
        </form>
    </div>
    );
}

My ajax POST

$.ajax({
        url: '/news/' + this.props.id,
        dataType: 'json',
        type: 'POST',
        data: comment,
        headers: {
            HTTP_X_CSRFTOKEN: getCookie('csrftoken')
        },
        success: function(data) {
            this.setState({data: data});
            }.bind(this),
        error: function(xhr, status, err) {
            console.error('/news/' + this.props.id, status, err.toString());
        }.bind(this)
    });

My headers

POST http://my.site/news/5 HTTP/1.1
Host: my.site
Proxy-Connection: keep-alive
Content-Length: 29
Origin: http://my.site
HTTP_X_CSRFTOKEN: GpCrHfeG7im7EObtiL6g56f5QvTJJRHZ
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Accept: application/json, text/javascript, */*; q=0.01
X-Requested-With: XMLHttpRequest
Referer: http://my.site/news/5
Accept-Encoding: gzip, deflate

Could you please to give me an advice why I still have this error? And what is the best practice to use django forms in frontend frameworks?


Solution

  • You are adding the wrong header. In your $.ajax() call you should do instead:

      headers: {
        'X-CSRFToken': getCookie('csrftoken')
      },
    

    For more details, check out the "How can I add a custom HTTP header to ajax request with js or jQuery?" question.