Flask WTForm render selected with Bootstrap
flask, flask-wtforms, twitter-bootstrap, wtforms
Solution
This is not done in the template, you have to do it on the `Form` object before you call `render_template()`.
For example:
form.gender.data = 'male'
Problem
This is a really simple question but I cannot seem to find a good answer. I have existing data stored about a user's selection and want to render that selection as selected in the dropdown. ``` {% macro render_bootstrap_field(field) %} <div class="form-group {% if field.errors %} error {% endif %}"> <label class="col-lg-2 control-label">{{ field.label }}</label> <div class="col-lg-8"> {{ field(class='form-control')|safe }} {% if field.errors %} {% for error in field.errors %} <span class="help-inline">[{{ error }}]</span><br> {% endfor %} {% endif %} </div> </div> {% endmacro %}} ``` And here is how this is rendered: ``` {{ render_bootstrap_field(form.gender) }} ``` It doesn't show what's selected and I cannot think of a way besides using jquery to add the class manually, but that would be a pain. Thanks so much for the help! Edit: forgot to include my view.py function! So I did set it ``` @app.route('/edit_user', methods=['GET', 'POST']) @login_required def edit_user(): form = UserInfoForm(g.user.nickname) form.gender.choices = app.config['GENDER'] form.year.choices = app.config['BIRTH_YEAR'] form.education.choices = app.config['EDUCATION'] if request.method == 'POST' and form.validate_on_submit(): flash("submitting") g.user.nickname = form.nickname.data g.user.gender = form.gender.data g.user.education = form.education.data g.user.year = form.year.data g.user.info_complete = True db.session.add(g.user) db.session.commit() return redirect(url_for('edit_user')) elif request.method != "POST": form.nickname.data = g.user.nickname form.gender.data = g.user.gender form.education.data = g.user.education form.year.data = g.user.year return render_template('edit_user.html', form=form, user=g.user) ``` Problem found! In case you are running into the same problem --- check your encoding! My unicode was throwing normal string off.