【问题标题】:how receive http post in django如何在 django 中接收 http 帖子
【发布时间】:2018-08-20 22:19:45
【问题描述】:

发送http帖子

import requests
payload =  [{'name': 'pippo', 'age':'7'}, {'name':'luca', 'age':'12'}]
r = requests.post("http://127.0.0.1:8000", data=payload)
print(r.url)

在 django 中接收 Http 帖子

from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from home.models import Post


@csrf_exempt
def home(request):
    all_post = Post.objects.all()
    context = {'request_method': request.method}
    if request.method == 'POST':
        context['request_payload'] = request.POST.dict()
        post_data = dict(request.POST)
        print(post_data)
    if request.method == 'GET':
        context['request_payload'] = request.GET.dict()
    return render(request, 'main/index.html', context, {'all_post':all_post})

在 print(post_data) 中我没有看到 [{'name': 'pippo', 'age':'7'}, {'name':'luca', 'age':'12'}]

为什么?我的错误在哪里?

【问题讨论】:

  • 你看到了什么
  • 如果我没记错的话,data 应该是一个字典,将 request.POST 中的键映射到一个值,而不是一个列表...
  • in print(post_data) 正在返回一个我不期望的结果。
  • in print(post_data) 我期望 [{'name': 'pippo', 'age':'7'}, {'name':'luca', 'age':'12' }]
  • @Marco 你能发布 print(post_data) 的结果吗?

标签: django python-3.x request http-post


【解决方案1】:

您应该为要通过请求发布的数据命名。像这样:

payload =  {'data': [{'name': 'pippo', 'age':'7'}, {'name':'luca', 'age':'12'}]}

当你想获取数据时,这样做:

post_data = request.POST['data']

【讨论】:

    猜你喜欢
    • 2021-09-21
    • 2014-07-08
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 2019-06-18
    • 2018-05-01
    相关资源
    最近更新 更多