L.P.
L.P.

Reputation: 3

Checkbox checked flask

I have a problem with a checkbox in a form

<form id="form" action="/findPkgInstalled" role="form" method = "POST">
    <div class="input-group col-xs-4">
      <input type="text" name="pkgSearch" placeholder="Ricerca applicazione non installate..">
      <div class="input-group-btn">
        <button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
      </div>
    </div>
    <h6><input type="checkbox" name="filterName" checked>Filtra per nome</h6>
</form>

while in Python I have:

@app.route('/findPkgInstalled', methods=['POST'])
def findPkgInstalled():
    error = None
    pkg = request.form['pkgSearch']
    if not pkg:
        flash(u'Operazione errata, impossibile ricercare stringa vuota','warning')
        return redirect(url_for('listInstalled'))
    else:
        if request.form['filterName'] is 'on':
            appFound = aptsearch(pkg,True)
            return render_template('find-pkg-not-installed.html', appFound = appFound)
        else:
            appFound = aptsearch(pkg,False)
            return render_template('find-pkg-not-installed.html', appFound = appFound)
    return redirect(url_for('listInstalled'))
    box = request.form['filterName']

but this does not work. The error reported is 400 Bad Request. How can I do? Can you help me, please?

Upvotes: 0

Views: 4797

Answers (2)

erdoganb
erdoganb

Reputation: 65

you can add value, to your checkboxes. if its checked, you get that value, else you get None.

Ive solved my problem with

    if request.form.get("check") == None:
        value = 0
    else:
        value = 1

and also it is ok if i dont use the else statement if only

    <input type="checkbox" name="check" value="1">

Upvotes: 0

Artsiom Praneuski
Artsiom Praneuski

Reputation: 2329

This error means that you're trying to fetch an object from your post request using incorrect key. For example if you uncheck filterName checkbox - this will cause this error:

request.form['filterName']

My advises:

0) Always check your post body to know what keys you can use to retrieve values from this body.

1) Use

request.form.get('filterName')

instead of

request.form['filterName']

because .get() returns None is there is no such key instead of throwing an exception inside flask that leads to 400 error

2) Use

request.form.get('filterName') == 'on'

instead of

request.form['filterName'] is 'on'

because is returns True if two variables point to the same object in memory. I'm not sure if you already have 'on' object in process memory

Upvotes: 2

Related Questions