17

我正在尝试在 Django 中对模型进行X-Editable内联编辑。我只是想更改模型实例的属性(在本例中为 Dataset 对象的名称)。

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

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

然后将新名称保存到 Dataset 对象。

网址.py

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

详细信息.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>

视图.py

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

编辑:

我认为问题在于没有 CSRF 保护。如何在 X 可编辑表单中添加它?

** 编辑 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

4 回答 4

27

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

入围版本将是:

<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();
于 2014-01-28T14:14:53.270 回答
4

csrf 表单域的正确名称是csrfmiddlewaretoken.

于 2012-12-09T09:25:42.937 回答
2

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

ajaxOptions: {
  dataType: 'json',
  beforeSend: function(xhr){
    xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]')
       .attr('content'));
    }           
}
于 2016-05-04T19:14:24.783 回答
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'

        });
于 2018-11-28T23:05:44.000 回答