Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get checkbox "on" using Python Flask without causing a 400 bad request error?

I've got a form which is submitting a post request to Flask. It all works perfectly except when a checkbox is not ticked which causes a 400 error unless I have a try: except: catch for each option.

The challenge is that I have a lot of checkboxes and it seems like there would be a better way than just having a dozen try: except: checks.

Is there a more Pythonic way of doing this please?

Currently the HTML looks like this:

<div class="control">
  <label class="checkbox">
    <input name="option_1" type="checkbox">
     Option 1
    </label>
</div>

My Python code looks like:

try:
    print(request.form['option_1'])

except:
    print("option_1 not selected")
like image 455
Johnny John Boy Avatar asked Jan 26 '26 11:01

Johnny John Boy


1 Answers

When a key might not exist, use .get(...) instead of accessing it directly, for example:

print(request.form.get('option_1'))
like image 97
janos Avatar answered Jan 27 '26 23:01

janos



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!