如何为POST请求编写Django视图

Rom*_*dgz 15 python django post

我写了一个非常小的例子:一个junit按钮,它发送一个带有一对值的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>
Run Code Online (Sandbox Code Playgroud)

因此,当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'),
    )
Run Code Online (Sandbox Code Playgroud)

views.py

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

完成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
...
Run Code Online (Sandbox Code Playgroud)

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

[28/May/2013 05:20:34] "POST /register/ HTTP/1.1" 403 142238
Run Code Online (Sandbox Code Playgroud)

但是"收到请求:POST"从未打印过.也不是"你好".当POST到达时,似乎urls.py没有为视图服务,因为在Firebug中我可以看到POST状态是403 FORBIDDEN.

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

Bib*_*ath 11

这是设计的.您的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(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>
Run Code Online (Sandbox Code Playgroud)