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.
Aggiungi token csrf al modello di ur .. – Rajeev