requst.Post与MultiValueDictKeyError

本文介绍了在使用Django服务端处理Android客户端发送的JSON POST请求时,如何避免出现MultiValueDictKeyError的问题。当尝试用request.POST['key']获取数据时,如果请求体数据类型是application/json,需要先将数据转化为JSON。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Bug奇遇记

环境
客户端:android
服务端:django

问题产生
当你明明使用post方法发起了一个request到服务器,而在服务器那端使用request.POST[‘key’]的方法来获取value的时候,你可能会遇到MultiValueDictKeyError错误。

解决办法
先提取body里面的json,再通过json获取数据

json_request = json.loads(request.body) 
value = json_request['key']

产生原因
1.request.POST[‘key’]获取数据的时候,body数据类型应该是
application/x-www-form-urlencoded,浏览器原生的form表单数据类型,即浏览器提交的数据格式一般是这样。
2.而如果你的body数据类型是application/json:json,你想获取其中数据必须要先转换为json样式。

参考

1.https://stackoverflow.com/questions/20206656/sending-post-json-from-android-and-receiving-on-django
2.https://blog.youkuaiyun.com/weixin_30295091/article/details/96148574

(venv) PS D:\bishe2\django0209\myproject> python manage.py runserver 8081 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). March 11, 2025 - 00:28:58 Django version 5.1.7, using settings 'myproject.settings' Starting development server at http://127.0.0.1:8081/ Quit the server with CTRL-BREAK. Not Found: / [11/Mar/2025 00:29:06] "GET / HTTP/1.1" 404 2413 Internal Server Error: /login/ Traceback (most recent call last): File "D:\bishe2\django0209\myproject\venv\Lib\site-packages\django\utils\datastructures.py", line 84, in __getitem__ list_ = super().__getitem__(key) ^^^^^^^^^^^^^^^^^^^^^^^^ KeyError: 'username' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\bishe2\django0209\myproject\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "D:\bishe2\django0209\myproject\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\bishe2\django0209\myproject\myapp\views.py", line 16, in login_view user = User.objects.get(username=request.POST['username']) ~~~~~~~~~~~~^^^^^^^^^^^^ File "D:\bishe2\django0209\myproject\venv\Lib\site-packages\django\utils\datastructures.py", line 86, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'username' [11/Mar/2025 00:29:14] "GET /login/ HTTP/1.1" 500 75778
最新发布
03-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值