首页 > 解决方案 > 在获取 POST 数据 django 中获取 MultiValueDictError

问题描述

我正在尝试获取从 HTML 表单接收的 GET 数据。

但它给了我 MultiValueDictError。这也是说

During handling of the above exception, another exception occurred:

我的 HTML 代码:

<!DOCTYPE html>
<html>
<head>
    <title>Document</title>
</head>
<body>
    <form action="home_redirect/fd" id="redirect" method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        <input type="text" value={{user}} name="user">
        <input type="submit">
    </form>
    <script>
        document.getElementById("redirect").submit()
    </script>
</body>
</html>

我的意见.py:

def home(request):
    user = request.POST['user']
    return render(request, 'main.html', {'login': user})

标签: javascripthtmlpython-3.xdjangodjango-views

解决方案


在您的 html 中,我删除action并编写脚本。像这样:

<!DOCTYPE html>
<html>
<head>
    <title>Document</title>
</head>
<body>
    <form  id="redirect" method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        <input type="text" value={{user}} name="user">
        <input type="submit">
    </form>
</body>
</html>

在这里我们检查的方法是POST然后redirect到你的url.

def home(request):
    user = request.POST
    if request.method =="POST":
        return redirect('home_redirect') # home_redirect is the redirected url
    return render(request, 'afl_announcement/main.html', {'login': user})

推荐阅读