Django Post请求未收到数据 [英] Django Post request not receiving data

查看:104
本文介绍了Django Post请求未收到数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了几个小时查找这个问题,但无济于事.

I've spent hours looking up this issue with no avail.

我在发送来自 html 页面的帖子数据时遇到问题我正在发送 {'username': 'username'} 但是当我执行 request.POST.get('username') 它返回 none,我也试过 {username, 'username'}

I am having issue with post data from an html page I am sending {'username': 'username'} but when I do request.POST.get('username') it returns none, I alos tried {username, 'username'}

def test_post(request):
    if request.method == 'POST':
        print(request.POST.get('username'))
        return HttpResponse("Good!")
    else:
        return HttpResponse("Bad.")

控制台开发服务器

None <<<<

[12/Feb/2018 19:39:53] "POST /test_post HTTP/1.1" 200 5
(edited)

我将数据作为 {'username': 'username'}这工作正常,为什么我无法让它显示出来?

I am sending the data as {'username': 'username'} That works correctly how come I am unable to get it to show up?

这是从页面调用的 Javascript 代码:

This is the Javascript code that calls from the page:

document.getElementById('submit').addEventListener('click', function(e) {
    e.preventDefault();
   var username = document.getElementById("username").value;

   data = {username: username};
   console.log(data);
   var request = new XMLHttpRequest();
   request.open('POST', '/getuser', true);
   request.setRequestHeader('Content-Type', 'x-www-form-urlencoded');
   request.send(data);
});

推荐答案

在 django 视图 test_post 中,request.POST 是一个查询字典(又名字典).

In the django view test_post, request.POST is a Query Dict (aka Dictionary).

当你使用.get(key)方法时,它会在字典中查找key并返回对应于key的值.

When you use the method .get(key), it looks for the key in the dictionary and returns you the value corresponding to the key.

test_post 方法中,您编写了 request.POST.get('username') 表示字符串 'username' 作为POST 字典中应该有一个键.

In the test_post method, you have written request.POST.get('username') which means the string 'username' as a key should be present in the POST dictionary.

当您使用 Javascript 执行 POST 并执行 data = {username: username}; 时,您实际上是在使密钥动态化.

When you do a POST using Javascript, and do data = {username: username}; you are essentially making the key dynamic.

例如.当您在用户名中输入Bob"并单击提交时,变量 data将是 {'Bob': 'Bob'}

Eg. when you input "Bob" in username and click on submit, the variable data will be {'Bob': 'Bob'}

你应该这样做:

 data = {'username': username}        //This ensures that the key remains same

这篇关于Django Post请求未收到数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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