मैं एक बहुत ही छोटा सा उदाहरण लिखा है के लिए एक Django दृश्य लिखने के लिए कैसे: एक 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>
तो, दृश्य प्रदान की गई है जब एक अनुरोध प्राप्त करें स्थानीयहोस्ट को भेजा गया: 8000/बटन /, और जब बटन दबाया जाता है तो POST अनुरोध स्थानीयहोस्ट को भी भेजा जाता है: 8000/बटन /।
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')
जब 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
लेकिन "अनुरोध प्राप्त: पोस्ट" कभी मुद्रित नहीं किया जाता है। न तो "हैलो" है। ऐसा लगता है कि urls.py एक पोस्ट आने पर दृश्य की सेवा नहीं कर रहा है, क्योंकि फ़ायरबग में मैं देख सकता हूं कि पोस्ट स्थिति 403 FORBIDDEN है।
यह शायद एक मूर्ख नौसिखिया गलती है, लेकिन मुझे नहीं पता कि मुझे क्या याद आ रही है। मैंने django book chapter about advanced URLConf and Views पढ़ा है, और ऐसा लगता है कि इसे request.method मान जांचकर काम करना चाहिए।
अपने टेम्पलेट में सीएसआरएफ टोकन जोड़ें .. – Rajeev