pythonhtmlgoogle-app-enginecheckboxwebapp2

How to Take Checkboxes in Python


I am trying to use checkboxes in my HTML, return these checkboxes to my python backend, and then increment three counters if the box is clicked.

Right now my HTML is as follows and works fine:

<form method="post">
    <input type="checkbox inline" name="adjective" value="entertaining">Entertaining
    <input type="checkbox inline" name="adjective" value="informative">Informative
    <input type="checkbox inline" name="adjective" value="exceptional">Exceptional
</form>

and then on my python backend I have the following:

def post(self):
    adjective = self.request.get('adjective ')

    if adjective :
        #somehow tell if the entertaining box was checked
        #increment entertaining counter
        #do the same for the others

Solution

  • When your form has multiple checkboxes with the same name attribute, the request will have multiple values for that name when the form is submitted.

    Your current code uses Request.get to get a value, but this will only retrieve the first value if there is more than one. Instead, you can get all the values using Request.get_all(name) (in webapp) or Request.get(name, allow_multiple=True) (in webapp2). This will return a (possibly empty) list with all the values for that name.

    Here's how you could use in in your code:

    def post(self):
        adjectives = self.request.get('adjective', allow_multiple=True)
        for a in adjectives:
            # increment count
            self.adjective_count[a] += 1 # or whatever
    
            # do more stuff with adjective a, if you want
    
        # do other stuff with the request