Python 如何为 POST 请求编写 Django 视图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16789988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:41:42  来源:igfitidea点击:

How to write a Django view for a POST request

pythondjangopost

提问by Roman Rdgz

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

我写了一个非常小的例子:一个 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>

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

因此,当 GET 请求被发送到 localhost:8000/button/ 时,视图会被渲染,当按钮被按下时,POST 请求也会被发送到 localhost:8000/button/。

urls.py

网址.py

from django.conf.urls import patterns, url

urlpatterns = patterns('',
    url(r'^button/$', 'helloworld.views.buttonExample'),
    )

views.py

视图.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:

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

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.

但是永远不会打印“收到的请求:POST”。“你好”也不行。当 POST 到达时,urls.py 似乎没有为视图提供服务,因为在 Firebug 中我可以看到 POST 状态为 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.

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

采纳答案by Bibhas Debnath

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

这是设计使然。您的 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>

回答by Daniel Roseman

You are receiving a 403 because of CSRF protection - you have not provided a token to protect yourself from attacks. The documentationtells you all you need to know.

由于 CSRF 保护,您收到 403 - 您没有提供令牌来保护自己免受攻击。该文档会告诉您所有您需要知道的信息。