2013-05-28 5 views
7

POST 요청에 대한 장고보기 작성하는 방법 : 값의 쌍을 가진 POST 요청을 보내는의 JUnit 버튼 :나는 아주 작은 예를 작성한

<!doctype html> 

<html lang="en"> 
<head> 
    <meta charset="utf-8" /> 
    <title>jQuery UI Button - Default functionality</title> 
    <script src="{{STATIC_URL}}js/jquery-1.9.1.js"></script> 
    <script src="{{STATIC_URL}}js/jquery-ui-1.10.3.custom.js"></script> 
    <link rel="stylesheet" href="{{STATIC_URL}}css/jquery-ui-1.10.3.custom.css"> 

    <script> 
    $(function() { 
    $("button") 
     .button() 
     .click(function(event) { 
     var postdata = { 
      'value1': 7, 
      'value2': 5 
     }; 
     $.post('', postdata); // POST request to the same view I am now 
     window.alert("Hello world!"); // To know it is working 
     }); 
    }); 
    </script> 
</head> 
<body> 

<button>Submit</button> 


</body> 
</html> 

그래서, 뷰가 렌더링을 GET 요청은 localhost : 8000/button /에 보내지고, 버튼을 누르면 POST 요청도 localhost : 8000/button /으로 전송됩니다.

urls.py

from django.conf.urls import patterns, url 

urlpatterns = patterns('', 
    url(r'^button/$', 'helloworld.views.buttonExample'), 
    ) 

views.py GET 요청이 완료되면

def buttonExample(request): 
    print 'RECEIVED REQUEST: ' + request.method 
    if request.method == 'POST': 
     print 'Hello' 
    else: #GET 
     return render(request, 'buttonExample.html') 

는, 뷰가 올바르게 표시되고 나는 또한 라인 콘솔 장고에서 읽을 수 있습니다

RECEIVED REQUEST: GET <---- This line is because of my print 
[28/May/2013 05:20:30] "GET /button/ HTTP/1.1" 200 140898 
[28/May/2013 05:20:30] "GET /static/js/jquery-1.9.1.js HTTP/1.1" 304 0 
[28/May/2013 05:20:30] "GET /static/js/jquery-ui-1.10.3.custom.js HTTP/1.1" 304 0 
[28/May/2013 05:20:30] "GET /static/css/jquery-ui-1.10.3.custom.css HTTP/1.1" 304 0 
... 
그리고 단추를 누르면, 내가 볼 수

[28/May/2013 05:20:34] "POST /register/ HTTP/1.1" 403 142238 

그러나 "RECEIVED REQUEST : POST"는 절대로 인쇄되지 않습니다. "안녕하세요"도 아닙니다. Firebug에서 POST 상태가 403 FORBIDDEN 인 것을 볼 수 있기 때문에 urls.py가 POST가 도착했을 때보기를 제공하지 않는 것 같습니다.

이것은 어리석은 초보자 실수 일뿐입니다. 그러나 나는 무엇이 실종되었는지 모르겠습니다. django book chapter about advanced URLConf and Views을 읽었으며 request.method 값을 확인하여 올바르게 작동하는 것처럼 보입니다.

+0

ur 템플릿에 csrf 토큰 .. – Rajeev

답변

8

이것은 의도적으로 설계된 것입니다. POST 데이터에 csrfmiddlewaretoken 값이 있어야합니다. 쿠키에서 가져 와서 POST 요청으로 보낼 수 있습니다. Details here. 사건의 경우이 작업을 수행 할 수 있습니다 - 당신 때문에 CSRF 보호의 (403)를 받고

<script> 
$(function() { 
    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'); 

    $("button") 
     .button() 
     .click(function (event) { 
      var postdata = { 
       'value1': 7, 
       'value2': 5, 
       'csrfmiddlewaretoken': csrftoken 
      }; 
      $.post('', postdata); // POST request to the same view I am now 
      window.alert("Hello world!"); // To know it is working 
     }); 
}); 
</script> 
+0

예제를 제공해 주시겠습니까? 방금 'csrfmiddlewaretoken'= $ .cookie ('csrftoken') 줄을 postdara 변수에 추가했으며 POST가 더 이상 전송되지 않습니다 –

+0

업데이트 된 답변. 검사. –

+1

BTW,'$ .cookie'를 사용하려면 jQuery 쿠키 플러그인이 필요합니다. –

3

- 당신은 토큰을 제공하지 않았습니다. The documentation은 알 필요가있는 모든 정보를 제공합니다.

+2

링크를 사용할 수 없습니다. 업데이트하십시오. –

관련 문제