2014-11-20 2 views
0

django rest 프레임 워크를 사용하여 일부 모델을 안정적인 리소스로 쉽게 처리하려고합니다.Django Rest Framework - 잘못된 CSFR 토큰으로 인해 ajax 호출이 실패합니다.

// 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."} 

누구나이 같은 경험 : 나는 모든 코드를 게시하지 않은

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

그 아약스 호출이 트리거 될 때, 어쨌든, 나는 403 오류를 얻을 : 이 내가 가진 그 코드입니다 또는 비슷한 문제가 도움이 될 수 있습니까?

답변

0
당신은 모든 쿠키 및 기타 사이트를 삭제하고 기록 탭을 클릭 한 다음 인터넷 사용 정보 삭제로 이동하여 이미지 파일을 데이터 플러그 앤 캐시해야

... 또 다른 옵션은 @csrf_exempt 사용하는 것입니다

감사 누가 복음 클래스 기반의 데코레이터 ..

+0

Dev tooolbar가 열린 상태에서 크롬을 사용하고 있으므로 캐시가 비활성화되어 있으므로 플러시 기록을 다시 확인할 수 있습니다. '@ csrf_exempt'를 사용하는 것은 CSFR 보호 – Luke

+0

을 제거한 이후 해결책이 아니므로 시크릿 창을 사용하지 마십시오. – Pawan

+0

안돼. 파이어 폭스 witn 청소 된 역사, 같은 결과를 시도 – Luke