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

时间:2022-06-06 12:49:38

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

我正在尝试在Django中获得一个模型的X-Editable内联编辑。我只是试图更改模型实例的属性(在本例中是数据集对象的名称)。

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

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

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

urls . py

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

detail.html

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

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?

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

** EDIT 2:

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

3 个解决方案

#1


21  

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();

#2


4  

The correct name for csrf form field is csrfmiddlewaretoken.

csrf表单字段的正确名称是csrfmiddlewaretoken。

#3


1  

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.

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

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

#1


21  

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();

#2


4  

The correct name for csrf form field is csrfmiddlewaretoken.

csrf表单字段的正确名称是csrfmiddlewaretoken。

#3


1  

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.

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

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