Django的休息框架 - 删除ajax调用失败由于不正确的CSFR令牌 [英] Django Rest Framework - DELETE ajax call failure due to incorrect CSFR token

查看:245
本文介绍了Django的休息框架 - 删除ajax调用失败由于不正确的CSFR令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用剩下的Django框架,可以轻松地处理一些模型作为RESTful资源。 这是code,我有:

I'm trying to use the django rest framework to to easily handle some models as restful resources. this is the code that I have:

Django: 1.7.1

Django REST Framework: 2.4.4

jQuery: 2.1.1

# models.py

class DocumentNodeTemplate(MPTTModel):
    """

    """
    document_template = models.ForeignKey(
        DocumentTemplate,
        related_name="nodes",
        verbose_name="Document template"
    )
    parent = TreeForeignKey(
        'self',
        null=True, blank=True,
        related_name='children'
    )
    section_template = models.ForeignKey(
        'SectionTemplate',
        related_name="node_templates",
        verbose_name="Section template"
    )

    def __unicode__(self):
        return  self.section_template.name

    def get_class(self):
        type = self.section_template.type
        return import_string(type)


# serializers.py

class DocumentNodeTemplateSerializer(serializers.ModelSerializer):
    class Meta:
        model = DocumentNodeTemplate
        fields = ('document_template', 'parent', 'section_template')


# views.py

class DocumentNodeTemplateAPIView(CreateAPIView, RetrieveUpdateDestroyAPIView):
    queryset = DocumentNodeTemplate.objects.all()
    serializer_class = DocumentNodeTemplateSerializer


<!-- HTML (section - admin's change form customization)-->
<fieldset class="module aligned">
    <h2>{{ node_fieldset_title }}</h2>
    <div class="form-row document-nodes">
        <div
        style="width: 100%; min-height: 450px;" id="general-container"
        data-document_model="{{ document_model }}"
        >
            <form id="changelist-form" action="" method="post" novalidate>{% csrf_token %}
                <div id="tree-container">
                    <div id="tree"
                         data-url="{{ tree_json_url }}"
                         data-save_state="{{ app_label }}_{{ model_name }}"
                         data-auto_open="{{ tree_auto_open }}"
                         data-autoescape="{{ autoescape }}"
                            >
                    </div>
                    <div class="add-node">
                        <a href="/admin/document/{{ model_name }}/add/?_to_field=id&document_id={{ object_id }}" class="add-another"
                            onclick="return showCustomAddAnotherPopup(event, this);">
                            <img src="/sitestatic/admin/img/icon_addlink.gif" width="10" height="10"
                                 alt="Add another node"> Add another node
                        </a>
                    </div>
                    <ul class='node-custom-menu'>
                        <li data-action="delete">Delete node</li>
                    </ul>
                </div>
            </form>
            <div id="node-container">
                <h3 id="node-name"></h3>
                <br/>

                <div id="node-content"></div>
            </div>
        </div>
    </div>
</fieldset>


// javascript 
var performCRUDaction = function(action, api_url, callback) {
var csfrtoken = $('input[name="csrfmiddlewaretoken"]').prop('value');
var _reloadNodeTree = function () {
    window.nodeTree.tree('reload');
}
var _performAction = function () {
    jQuery.ajax({
            type: actionType,
            url: api_url,
            data: { 'csrfmiddlewaretoken': csfrtoken },
            success: function () {
                console.log("action " + action + " successfully performed on resource " + api_url);
                _reloadNodeTree();
            },
            error: function () {
                console.log("action " + action + " failed on resource " + api_url);
            }
        });
    }


    var actionType,
        documentModel = null;
    var nodeDataObj = {};
    switch (action) {
        case "delete":
            actionType = "DELETE";
            break;
        case "update":
            actionType = "PUT";
            break;
        case "create":
            actionType = "POST";
            break;
        case "retrieve":
            actionType = "GET";
            break;
    }
    _performAction();
    callback();
}

我并没有公布所有的code,反正当Ajax调用被触发时,我得到一个403错误:

I didn't posted all the code, anyway when that ajax call is triggered, I obtain a 403 error:

// headers

Remote Address:127.0.0.1:8050
Request URL:http://127.0.0.1:8050/api/documentnodetemplates/46
Request Method:DELETE
Status Code:403 FORBIDDEN
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-GB,en;q=0.8,en-US;q=0.6,it;q=0.4
Cache-Control:no-cache
Connection:keep-alive
Content-Length:52
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:djdt=hide; sessionid=x5cw6zfifdene2p7h0r0tbtpkaq7zshq; csrftoken=NyMqLlKxeeAdc4Eq2nFpFOebh0SUBBVY
Host:127.0.0.1:8050
Origin:http://127.0.0.1:8050
Pragma:no-cache
Referer:http://127.0.0.1:8050/admin/document/documenttemplate/1/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36
X-CSRFToken:NyMqLlKxeeAdc4Eq2nFpFOebh0SUBBVY
X-Requested-With:XMLHttpRequest
Form Dataview sourceview URL encoded
csrfmiddlewaretoken:NyMqLlKxeeAdc4Eq2nFpFOebh0SUBBVY
Response Headersview source
Allow:GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
Content-Type:application/json
Date:Thu, 20 Nov 2014 09:52:31 GMT
Server:WSGIServer/0.1 Python/2.7.6
Vary:Accept, Cookie
X-Frame-Options:SAMEORIGIN

// response
{"detail": "CSRF Failed: CSRF token missing or incorrect."}

任何人都经历过同样或类似的问题,可以帮助?

Anybody experienced the same or similar problem and can help?

谢谢 卢克

推荐答案

您应该删除所有Cookies和其他网站数据和插件数据和缓存的图像和文件通过进入历史选项卡,然后清除浏览数据...另一个选择是使用@csrf_exempt装饰与类为本次。

You should delete all your Cookies and other site and plug-in data and Cached images and files by going into history tab and then clear browsing data...ANother option is to use @csrf_exempt decorator with your class based views..

这篇关于Django的休息框架 - 删除ajax调用失败由于不正确的CSFR令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆