1

Trying to do a simple todo app with flask and sqlalchemy and since I have never worked with checkboxes in flask before, i have the following problem.

App is

class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.String(200))
    complete = db.Column(db.Boolean)


@app.route('/update', methods=['POST'])
def update():
    print(request.form)
    return redirect(url_for('index'))

HTML IS:

<ul>
    {% for todo in incomplete %}
    <li><input id="checkbx" name="{{ todo.id }}" type="checkbox"> {{ todo.text }} </li>
    {% endfor %}    
</ul>

when I,

print(request.form) 

after selecting the checkbox to complete the todo task and clicking the update button, console prints out:

ImmutableMultiDict([('11', u'on')])

how can i update the DB to change the complete value from '0' to '1'?

print(request.form['checkbx']) 

gives a 400 Bad Request

request.form.get('checkbx') 

returns None

todo = request.form.getlist('checkbx')

returns []

I'm guessing i need to do something like:

todo = Todo.query.filter_by(int(id)).first()

so then I can

todo.complete = True
db.session.commit()

how can i get the id from that ImmutableMultiDict (in this case it's '11') ???

April
  • 31
  • 4
  • I specifically changed the id to "checkbx" from "checkbox" to see where i'm going wrong. also adding a value doesn't change a thing. request.form.getlist('checkbox')[1] continues to return [] – April Feb 17 '18 at 03:48

1 Answers1

0

you can convert the ImmutableMultiDict to dict

todo = dict(request.form).keys[0]

and then filter by it, complete and commit.

2milli
  • 50
  • 8
  • data = request.form.to_dict() might be easier – 2milli Feb 17 '18 at 04:09
  • Thanks. Your answer helped, I also found this website after your comment. http://www.seanbehan.com/how-to-get-a-dict-from-flask-request-form/ – April Feb 17 '18 at 04:11