djangodatabasedjango-modelsdjango-formsdjango-errors

MultiValueDictKeyError at /savepost/


I know this has been asked before but I'm facing this MultiValueDictKeyError. Basically I'm trying to take an input from the user, the input tag has this name="usercaption" attribute. While I click on submit it pops up the MultiValueDictKeyError. Here's my HTML form:

<div class="post">
    <form action="/savepost/" method="GET">
        <input type="text" name="usercaption" placeholder="Write Something...">
        <div class="attach">
            <button class="upload-image"><i class="fal fa-image"></i> Image</button>
            <button><i class="fal fa-video"></i> Video</button>
            <button><i class="fal fa-smile-beam"></i> Mood</button>
            <button type="submit">Upload</button>
        </div>
    </form>
</div>

Here's my view function:

def savepost(request):
    caption = request.GET["usercaption"]
    Post = post(caption=caption)
    Post.save()
    return redirect('usersfeed')

The error is on this line caption = request.GET["usercaption"]


Solution

  • You have to provide a default value for if it doesn't exist, so for example:

     caption = request.GET.get["usercaption", ""]
    

    And you have to add the user as well:

    user = request.user
    Post = post(caption=caption, user=user)