Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a HiddenField to coerce integer data in WTForms?

I have a WTForm class like so:

class MyForm(Form):
    field1 = HiddenField(default=0, validators=NumberRange(min=0, max=20)])

consider this markup as rendered by WTForms

<input type='hidden' name='field1' value='5'></input>

This does not pass the NumberRange validation. This is because HiddenFields widget class coerces the value attribute into a string. How can I get WTForms to produce this markup such that I can perform numeric validation on the subsequent POST?

like image 824
RoyalTS Avatar asked May 21 '14 09:05

RoyalTS


1 Answers

The recommended trick is to use an IntegerField and change the widget to a HiddenInput

class MyForm(Form):
    field1 = IntegerField(widget=HiddenInput())

you can also subclass

class HiddenInteger(IntegerField):
    widget = HiddenInput()
like image 130
nsfyn55 Avatar answered Sep 16 '22 13:09

nsfyn55