Swastik Goyal
Swastik Goyal

Reputation: 23

Getting MultiValueDictError in fetch POST data django

I am trying to fetch GET data receiving from an HTML form.

But it is giving me MultiValueDictError. It is also saying

During handling of the above exception, another exception occurred:

My HTML code :

<!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>

My views.py :

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

Upvotes: 2

Views: 91

Answers (2)

Riyas Ac
Riyas Ac

Reputation: 1613

In you html i remove action and script. Like this:

<!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>

Here we checking the method is POST then redirect to your 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})

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477200

In your <form> you specify:

<form action="home_redirect/fd" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="text" value={{user}} name="user">
    <input type="submit">
</form>

so you make a POST request, and the data is encoded in the payload of the request. You access this data through request.POST:

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

Upvotes: 0

Related Questions