Django中的X可编辑内联编辑 - 如何获得CSRF保护?

时间:2012-12-08 21:56:31

标签: ajax django x-editable

我正在尝试在Django中对{* 3}}内联编辑模型。我只是想尝试更改模型实例的属性(在本例中,是数据集对象的名称)。

我不确定如何编写视图以便正确捕获来自ajax请求的信息:

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

然后将新名称保存到数据集对象。

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')  

修改

我认为问题在于没有CSRF保护。如何以X-editable形式添加?

**编辑2:

我也尝试了这个,根据文档:

<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>

4 个答案:

答案 0 :(得分:23)

哇,我在这个问题上花了很多时间!

候选名单将是:

<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>

然后,拨打

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

答案 1 :(得分:4)

csrf表单字段的正确名称为csrfmiddlewaretoken

答案 2 :(得分:2)

我在PHP项目中遇到过这个问题,我使用ajaxOptions选项解决了这个问题。从元标记中选取CSRF令牌并将其添加到请求标头中。

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

答案 3 :(得分:0)

我认为是正确的,特别是如果您正在使用Rails添加

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

内置可编辑功能

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

        });