How to create a single checkbox in WTForms?
Asked Answered
S

1

6

Most of the info I find online is for multiple checkboxes. I just want 1.

I have:

class CategoryForm(FlaskForm):
    category = StringField('category',validators=[DataRequired()])
    checkbox = BooleanField('Private?')

@app.route('/category/<categoryid>',methods=('GET','POST'))
def category(categoryid):
    category = Category.query.get(categoryid)
    if request.method == 'POST':
        if request.form.get('category'):
            category.name = request.form['category']
            category.private = request.form['private']
            db.session.add(category)
            db.session.commit()
            return redirect(url_for('index'))

    c_form = CategoryForm()
    c_form.category.data = category.name
    return render_template('category.html',form =c_form,category=category)

And my 'category' template:

<form method="post">
    {{ form.hidden_tag() }}
    {{ form.checkbox }}
    <button type="submit">Go!</button>
</form>

right now my browser renders this:

<peewee.BooleanField object at 0x105122ad0> Go!

Obviously I would like it to render the checkbox instead. How can I do this? Do I need a widget ?

Szombathely answered 10/8, 2017 at 0:28 Comment(2)
The code works fine. At least in my computer.Choirboy
The code also works fine in my computer. From where you are importing the field?Kurgan
C
9

I'm having the impression that you're using the fields from peewee as the fields in your form, that isn't going to work. The most likely case is that you're importing both and one import is overwriting the other.

If you need to have both the model and the form in the same file, use aliases.

from peewee import BooleanField as PeeBool

from wtforms import BooleanField as WTBool
Clachan answered 12/8, 2017 at 14:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.