2013-05-28 10 views
7

ho scritto un piccolo esempio: un pulsante JUnit che invia una richiesta POST con una coppia di valori:Come scrivere una vista Django per una richiesta POST

<!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> 

Quindi, la vista è resa quando un GET request viene inviata a localhost: 8000/button /, e quando viene premuto il pulsante viene inviata anche una richiesta POST a localhost: 8000/button /.

urls.py

from django.conf.urls import patterns, url 

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

views.py

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

Quando la richiesta GET è fatto, la vista è visualizzata correttamente e posso anche leggere a Django consolare le linee:

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

E quando si preme il pulsante, posso vedere:

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

Ma "RICHIESTA RICEVUTA: POST" non viene mai stampato. Né è "Ciao". Sembra che urls.py non stia servendo la visualizzazione quando è arrivato un POST, perché in Firebug posso vedere che lo stato POST è 403 FORBIDDEN.

Questo è probabilmente uno stupido errore newbie, ma non so cosa mi manca. Ho letto lo django book chapter about advanced URLConf and Views e sembra che dovrebbe funzionare solo controllando il valore request.method.

+0

Aggiungi token csrf al modello di ur .. – Rajeev

risposta

8

Questo è di progettazione. I tuoi dati POST devono contenere il valore csrfmiddlewaretoken. Puoi ottenerlo dai tuoi cookies e poi inviarlo con le richieste POST. Details here. Per il vostro caso, si può fare questo -

<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

Potresti fornire un esempio? Ho appena aggiunto la riga 'csrfmiddlewaretoken' = $ .cookie ('csrftoken'), 'alla variabile postdara, e il POST non viene più inviato –

+0

Risposta aggiornata. dai un'occhiata. –

+1

BTW, usando '$ .cookie' richiede il plugin per i cookie jQuery. –

3

Hai ricevuto un 403 a causa della protezione CSRF - non è stato fornito un token. The documentation ti dice tutto ciò che devi sapere.

+2

Il collegamento non è disponibile ora. Per favore aggiornare. –

Problemi correlati