0

I want to make an if statement that deals with the case when a user doesn't select any radio options. if they don't select a radio option, it just prints out an error message. However, every time I don't select an option it just tells me:

werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'mysearch'


HTML:

<form class="anotherform" method="POST">
    <div class="myform">
        <input type="text" placeholder="Enter your text or leave empty" name="search_term">
    </div>

    <input type="radio" name="mysearch" value="option1">Option 1<br>
    <input type="radio" name="mysearch" value="option2">Option 2<br>
    <input type="radio" name="mysearch" value="option3">Option 3<br>
    <input type="radio" name="mysearch" value="option4">Option 4<br>

    <button class="button" type="submit">Search</button>
</form>

{{error_msg}}

routes.py

@app.route('/search', methods=['POST', 'GET'])
def search():

    if request.method == 'POST':
        search_filter = request.form["mysearch"]
        search_term = request.form["search_term"]

        if search_filter == "":
            error_msg = 'You didnt select an option'
            return render_template('/search.html', error_msg=error_msg)

    return render_template('/search.html')
Mikie
  • 125
  • 1
  • 7

1 Answers1

0

If I'm not mistaken request.form is a Multidict type which is like a Python dictionary.

So you can get a default value from dictionary if you are not sure if the key exists, and avoid throwing the error in your application like this:

search_filter = request.form.get("mysearch", "")
search_term = request.form.get("search_term", "")

And then check search_filterif it is empty or it has value.

Amin Alaee
  • 1,895
  • 17
  • 26