WTForms: How to render an HTML5 Widget?

Viewed 1356

I'm trying to use the WTForms color input field.

This is how I define the form:

from wtforms.widgets.html5 import ColorInput

class ColoursForm(Form):
   background_color = ColorInput()

This is the view:

@app.route("/colours/<token>/", methods=['GET', 'POST'])
def edit_colours(token):
   form = ColoursForm(request.form)
   if request.method == 'GET':
       return render_template('colours_edit.html', form=form, token=token)
   else:  # Request = post

      return redirect(url_for('view_scoreboard', token=token))

In my Jinja2 Template (colours_edit.html) I do this:

<p> {{ form.background_color }} Pick a color here </p>

However, it doesn't render an HTML Color-picker as expected, instead I see this in the rendered HTML:

<wtforms.widgets.html5.ColorInput object at 0x10b836e90> Pick a color here

Why is the input not being rendered?

1 Answers

I worked it out. There were 2 problems with my code:

I was missing () here:

<p> {{ form.background_color() }} Pick a color here </p>

The form should look this:

class ColoursForm(Form):
"""Used when editing scoreboard colours"""
   background_color = StringField(widget=ColorInput())

From this Stackoverflow answer.

Finally, I've got to say that the WTForms documentation is not very good on this. Some examples would certainly help.

Related