Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a html form has a specific key in Flask?

I have a form which has a input radio like the following:

<form class="search" action="{{ url_for('np.bkg') }}" method="post">

    <input type="text" name="query" style="max-width:700px" placeholder="Search over bkg..." id="query" value="{{query}}" autocomplete="on" required>
    <button type="submit"><i class="fa fa-search"></i></button>
    <div>
    <input type="radio" name="searchType" id="kmatch" value="kmatch" > match </input>
    <input type="radio" name="searchType" id="kextraction" value="kextraction"> extract </input>
    </div>
    
</form>

There is no default value for the radio button. Then I have this line:

  search_type = request.form['searchType', None]

However, it reports this error when making a reqeust:

File "/bkg/myenv/lib/python3.7/site-packages/werkzeug/datastructures.py", line 443, in __getitem__
    raise exceptions.BadRequestKeyError(key)
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: ('searchType', None)

I thought the default None value can prevent this error, but it didn't.

How to fix it?

like image 235
marlon Avatar asked Dec 05 '25 18:12

marlon


1 Answers

For those who still have this problem it should be like this,

search_type = request.form.get('searchType', None)
like image 82
MarArcz Avatar answered Dec 09 '25 18:12

MarArcz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!