mango
mango

Reputation: 553

Using google app engine and python, how do I check if a checkbox is marked?

I want to display some items that the user wants to buy in a cart, using checkboxes.

In the db.Model class for items for sale I have included:

amount = db.StringProperty(required = True)
price = db.StringProperty(required = True)
checked = db.BooleanProperty(default = False)

the db.Model class html:

<tr>
<td class = "checkbox">
        <input type = "checkbox" name = "check">
    {{s.checked}}
</td>

<td class = "entry_amount" name = "entry">
    {{s.amount}}
</td>

<td class = "entry_price" name = "entry">
    {{s.price}}
</td>
</tr>

Each time the user accesses the buy page, the checked attribute is set to False for each item. On the post method of the buy page I have the following, for when the user hits submit; check is the name of the checkbox; the checkbox is not assigned a value in the html

sells = SellModel.all()
boxcount = 0

for sell in sells:
    check = self.request.get('check')
    if check:
        sell.checked = True
        sell.put()
        boxcount += 1

if boxcount == 0:
    error = "check at least one box"
    self.render("buy.html", error = error, sells = sells)
else:     
    self.redirect('/cart')

the buy.html includes:

<tr class = "table_label">
            <th></th>
            <th>amount of mp</th>
            <th>price per mp</th>
            </tr>
            {% for sell in sells %}
                {{ sell.render() | safe }}
                </input>
            {% endfor %}

self.redirect leads to the cart page, where the get method has

 cart = SellModel.all()
    cart.filter("checked = ", True)
    self.render("newbuy.html", cart = cart)

When I go to the cart page, every single item listed for sale is selected, instead of just the ones whose box was checked. Why is this happening?

Help.

Upvotes: 1

Views: 498

Answers (1)

Prahlad Yeri
Prahlad Yeri

Reputation: 3663

Try checking whether the dict actually has that key using the has_key() python function:

check = self.request.has_key('check') #you may also use ('check' in self.request) - see my comment below.
if check:
    sell.checked = True
    sell.put()
    boxcount += 1

The above should work. If it doesn't, change your checkbox markup, so that it actually has some value:

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

The standard behavior of html checkbox is that the value is posted only if checkbox is checked. See this link for more info.

Upvotes: 1

Related Questions