如何为POST请求编写Django视图 [英] How to write a Django view for a POST request

查看:105
本文介绍了如何为POST请求编写Django视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了一个很小的例子:一个junit按钮,发送一个POST请求和一对值:

  ;!doctype html> 

< html lang =en>
< head>
< meta charset =utf-8/>
< title> jQuery UI按钮 - 默认功能< / 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 =stylesheethref ={{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请求到同一个视图我现在是
window.alert(Hello world!); //知道它正在工作
});
});
< / script>
< / head>
< body>

< button>提交< / 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



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

当GET请求完成后,视图正确显示,我也可以在Django控制台中读取这些行:

 收到的请求:GET< ----这行是因为我的打印
[28 / May / 2013 05:20:30]GET / button / HTTP / 1.1200 140898
[28 / May / 2013 05:20:30]GET /static/js/jquery-1.9.1.js HTTP / 1.1304 0
[ 28 / May / 2013 05:20:30]GET /static/js/jquery-ui-1.10.3.custom.js HTTP / 1.1304 0
[28 / May / 2013 05:20:30 ]GET /static/css/jquery-ui-1.10.3.custom.css HTTP / 1.1304 0
...

当按下按钮时,我可以看到:

  [28 / May / 2013 05:20:34]POST / register / HTTP / 1.1403 142238 

但是接收请求:POST从不打印。既不是你好。当POST到达时,看起来urls.py不会提供视图,因为在Firebug中,我可以看到POST状态为403 FORBIDDEN。



这可能是一个愚蠢的新手错误,但我不知道我失踪了什么。我已经阅读了关于高级URLConf和Views 的 django书一章,它看起来像它应该通过检查request.method值来工作。

这是设计的。您的POST数据必须包含 csrfmiddlewaretoken 值。您可以从Cookie获取它,然后使用POST请求发送。 此处的详细信息。对于您的情况,您可以执行此操作 -

 < 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 (cookie [i]);
//这个cookie字符串是否以我们想要的名字开头?
if(cookie.substring(0,name.length + 1)==(name +'=' )){
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
返回cookieValue ;
}
var csrftoken = getCookie('csrftoken');

$(button)
.button()
.click (事件){
var postdata = {
'value1':7,
'value2':5,
'csrfmiddlewaretoken':csrftoken
};
$ .post('',postdata); // POST请求到同一个视图我现在是
window.alert(Hello world!); //知道它正在工作
});
});
< / script>


I have written a very small example: a junit button which sends a POST request with a pair of values:

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

So, the view is rendered when a GET request is sent to localhost:8000/button/, and when the button is pushed a POST request is also sent to 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')

When the GET request is done, the view is displayed correctly and I can also read at Django console the lines:

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

And when the button is pushed, I can see:

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

But "RECEIVED REQUEST: POST" is never printed. Neither is "Hello". It seems like the urls.py is not serving the view when a POST arrived, because in Firebug I can see that POST status is 403 FORBIDDEN.

This is probably a silly newbie mistake, but I don't know what am I missing. I have read the django book chapter about advanced URLConf and Views, and it looks like it should work just by checking request.method value.

解决方案

This is by design. Your POST data must contain csrfmiddlewaretoken value. You can get it from your cookies and then send it with POST requests. Details here. For your case, you can do this -

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

这篇关于如何为POST请求编写Django视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆