我已經寫一個非常小的例子Django視圖:一個JUnit按鈕,它發送POST請求與一對值:如何寫一個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>
因此,該視圖中呈現時一GET請求被髮送到localhost:8000/button /,當按鈕被按下時,POST請求也被髮送到localhost:8000/button /。
urls.pyfrom 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')
當GET請求完成後,被正確顯示的視圖,我還可以在Django的讀安慰行:
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
但是「接收到的請求:POST」從不打印。也不是「你好」。看起來urls.py在POST到達時沒有提供視圖,因爲在Firebug中,我可以看到POST狀態爲403 FORBIDDEN。
這可能是一個愚蠢的新手錯誤,但我不知道我錯過了什麼。我已閱讀django book chapter about advanced URLConf and Views,它看起來應該只是通過檢查request.method值來工作。
將csrf標記添加到您的模板中。 – Rajeev