【问题标题】:Only Django request.body contains data (not request.POST)只有 Django request.body 包含数据(不是 request.POST)
【发布时间】:2022-01-15 23:39:37
【问题描述】:

我在 Django 中使用表单并尝试使用request.POST 取回数据,但这会为我返回一个空字典:<QueryDict: {}>。然而,当使用request.body 时,我得到了原始数据。我怎样才能从request.POST 获取数据,因为我不想使用原始数据。打印语句的控制台输出放在它们旁边的 cmets 中。

forms.py

class NameForm(forms.Form):
    first_name = forms.CharField(label='First name:', max_length=100)
    last_name = forms.CharField(label='Last name:')

views.py

@csrf_exempt
def blank(request):
    form = NameForm()
    print(f"request.body: {request.body}") # request.body: b'first_name=Adam&last_name=Smith'
    print(f"request.POST: {request.POST}") # request.POST: <QueryDict: {}>

    return render(request, 'blank.html', {'form': form})

空白.html

<!DOCTYPE html>
<html lang="en">
    <head>
    </head>
    <body>
        <form action="" method="post">
            {{ form }}
            <input type="submit" value="Submit">
        </form>
    </body>
</html>

【问题讨论】:

  • 如何提交表单?
  • @NKSM 你是什么意思?
  • 在输入中按下提交按钮,类型为 submit
  • 使用if request.method == "POST": print(f"request.POST: {request.POST}")
  • 打印request.methodrequest.content_type会得到什么?

标签: python html django forms request


【解决方案1】:

从 django 表单中检索数据

form = NameForm(request.POST or None)
    if form.is_valid():
        first_name= form.cleaned_data.get("first_name")
        last_name= form.cleaned_data.get("last_name")

【讨论】:

    猜你喜欢
    • 2012-08-28
    • 2019-02-01
    • 2021-01-22
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 2015-05-09
    • 1970-01-01
    • 2022-10-24
    相关资源
    最近更新 更多