17

I am trying to get X-Editable inline editing of a model in Django. I am simply trying to change attributes of a model instance (in this case, the name of a Dataset object).

I am not sure how to write the view so that it correctly captures the information from the ajax request:

POST /datasets/9/update_name/
{
    pk:    3            //primary key (record id)
    value: 'The Updated Name' //new value
}

Then save the new name to the Dataset object.

urls.py

# ex: /datasets/3/update_name
url(r'^(?P<pk>\d+)/update_name/$', update_name ,
    name='update_name'),

detail.html

<h1 class="page-title center">
    <a href="#" id="datasetName">{{ dataset.name }}</a>
</h1>
<script>
$('#datasetName').editable({
  type: 'text',
  pk: {{ dataset.pk }},
  url: '{% url 'datasets:update_name' dataset.pk %}',
  title: 'Edit dataset name'
  params: { csrf: '{% csrf_token %}'} # // This isn't working
});
</script>

views.py

def update_name(request, dataset_id):   
    # ... Update Dataset object ...
    json = simplejson.dumps(request.POST)
    return HttpResponse(json, mimetype='application/json')  

EDIT:

I believe the problem is that there is no CSRF protection. How can I add this in the X-editable form?

** EDIT 2:

I have also tried this, as per the docs:

<h1 class="page-title center">
  <a href="#" id="datasetName">{{ dataset.name }}</a>
</h1>

<script>
// 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) {
   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;
             }
             if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
           // Only send the token to relative URLs i.e. locally.
           xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
         }
       } 
     });
$('#datasetName').editable({
  type: 'text',
  pk: {{ dataset.pk }},
  url: '{% url 'datasets:update_name' dataset.pk %}',
  title: 'Edit dataset name',
});
</script>
Shubhamoy
  • 3,718
  • 2
  • 19
  • 24
Steve L
  • 1,704
  • 1
  • 20
  • 29
  • Thanks for sharing what you're doing, but what is the question? – Krzysztof Szularz Dec 08 '12 at 22:00
  • Sorry. Edited. I am just not sure how to write the view to capture and save the information from the request – Steve L Dec 08 '12 at 22:05
  • 1
    Is the view code being called? What does request.POST look like? Is `request.is_ajax()` true? Do you get the success response in the front end? What is the result of `form.is_valid()`? – dokkaebi Dec 08 '12 at 22:15
  • Hm,it doesn't look like the post method in DatasetDetail is even getting called. I tried putting `print repr(request.POST)` in the post method above, and nothing showed up when I tried to make the inline edit. However, in the server output, I see that the POST request was made: [08/Dec/2012 16:33:10] "POST /datasets/3/ HTTP/1.1" 403 152221 – Steve L Dec 08 '12 at 22:35

4 Answers4

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();
johnbarr
  • 460
  • 4
  • 6
4

The correct name for csrf form field is csrfmiddlewaretoken.

Krzysztof Szularz
  • 5,151
  • 24
  • 35
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'));
    }           
}
Shubhamoy
  • 3,718
  • 2
  • 19
  • 24
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'

        });
Mohamed Sami
  • 866
  • 10
  • 22