的X编辑联编辑在Django

的X编辑联编辑在Django

本文介绍了的X编辑联编辑在Django - 如何让CSRF保护?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得在Django模型的的X编辑的在线编辑。我只是试图改变模型实例的属性(在这种情况下,一个数据集对象的名称)。

我不知道如何写视图,以便它正确地从Ajax请求捕获的信息:

  POST /集/ 9 / update_name /
{
    PK:3 //主键(记录ID)
    值:更新的名称//新的价值
}
 

那么新的名称保存到数据集对象。

urls.py

 #例如:/集/ 3 / update_name
URL(R'^(P< PK> \ D +)/ update_name / $',update_name,
    NAME ='update_name'),
 

detail.html

 < H1类=页面标题中心>
    &所述; A HREF =#标识=数据集名称> {{dataset.name}}&所述; / a取代;
< / H1>
<脚本>
$('#数据集名称)。编辑({
  类型:文本,
  峰:{{dataset.pk}},
  网址:'{%URL数据集:update_namedataset.pk%}',
  标题:编辑数据集名称
  PARAMS:{CSRF:{%csrf_token%}'}#//这是行不通的
});
< / SCRIPT>
 

views.py

 高清update_name(请求,dataset_id):
    #...更新Dataset对象...
    JSON = simplejson.dumps(request.POST)
    返回的Htt presponse(JSON,MIMETYPE =应用/ JSON)
 

编辑:

我相信问题是不存在的CSRF保护。我怎样才能在X-编辑表单中添加呢?

**编辑2:

我也试过,按照文档:

 < H1类=页面标题中心>
  &所述; A HREF =#标识=数据集名称> {{dataset.name}}&所述; / a取代;
< / H1>

<脚本>
//使用jQuery
函数的getCookie(名字){
  VAR cookieValue = NULL;
  如果(document.cookie中和放大器;&安培;!的document.cookie =''){
    VAR饼干= document.cookie.split(';');
    对于(VAR I = 0; I< cookies.length;我++){
      VAR饼干= jQuery.trim(饼干[I]);
          //这是否cookie字符串与我们想要的名字么?
          如果(cookie.substring(0,name.length + 1)==(名称+'=')){
            cookieValue =去codeURIComponent(co​​okie.substring(name.length + 1));
            打破;
          }
        }
      }
      返回cookieValue;
    }
    VAR csrftoken =的getCookie('csrftoken');

    函数csrfSafeMethod(方法){
  //这些HTTP方法不需要CSRF保护
  返回(/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$ .ajaxSetup({
 beforeSend:功能(XHR,设置){
   函数的getCookie(名字){
     VAR cookieValue = NULL;
     如果(document.cookie中和放大器;&安培;!的document.cookie =''){
       VAR饼干= document.cookie.split(';');
       对于(VAR I = 0; I< cookies.length;我++){
         VAR饼干= jQuery.trim(饼干[I]);
                   //这是否cookie字符串与我们想要的名字么?
                   如果(cookie.substring(0,name.length + 1)==(名称+'=')){
                     cookieValue =去codeURIComponent(co​​okie.substring(name.length + 1));
                     打破;
                   }
                 }
               }
               返回cookieValue;
             }
             如果((/ ^的http:!* /测试(settings.url)|| /^https:.*/.test(settings.url))){
           //只发送令牌相对URL,即在本地。
           xhr.setRequestHeader(X-CSRFToken,的getCookie('csrftoken'));
         }
       }
     });
$('#数据集名称)。编辑({
  类型:文本,
  峰:{{dataset.pk}},
  网址:'{%URL数据集:update_namedataset.pk%}',
  标题:编辑数据集名称',
});
< / SCRIPT>
 

解决方案

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

该名单的版本是:

 < A HREF =#ID =项目名称{{project.id}}数据类型=文本数据PK ={{} project.id }数据标题=请输入项目名称数据URL ={%URLupdateprojectproject.id%}数据PARAMS ={csrfmiddlewaretoken:{{csrf_token}}'}> {{项目。名称}}&所述; / a取代;
 

然后,调用

  $('#项目名称{{project.id}}')可编辑的()。
 

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>
解决方案

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

这篇关于的X编辑联编辑在Django - 如何让CSRF保护?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 10:26