[Fixed]-X-editable inline editing in Django – how to get CSRF protection?

27👍

Wow, I spent so much time on this problem!

The shortlist version would be:

<a href="#" id="projectname{{project.id}}" data-type="text" data-pk="{{project.id}}" data-title="Enter project name" data-url="{% url 'updateproject' project.id %}" data-params="{csrfmiddlewaretoken:'{{csrf_token}}'}">{{ project.name }}</a>

And then, call

$('#projectname{{project.id}}').editable();

4👍

The correct name for csrf form field is csrfmiddlewaretoken.

2👍

I faced this in my PHP Project and I solved it by using the ajaxOptions option. Picked up the CSRF Token from the meta tag and added it to the request header.

ajaxOptions: {
  dataType: 'json',
  beforeSend: function(xhr){
    xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]')
       .attr('content'));
    }           
}

0👍

I think the correct one especially if you are working with rails to add

        ajaxOptions: {
            beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))}, 
        },

inside editable function to be

        $('#projectname').editable({
            showbuttons: 'bottom',
            ajaxOptions: {
                beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))}, 
            },              
            type: 'textarea',
            url: '/url/url'

        });

Leave a comment