RoyalTS
RoyalTS

Reputation: 10203

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?

Upvotes: 7

Views: 4299

Answers (2)

nsfyn55
nsfyn55

Reputation: 15363

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()

Upvotes: 19

aifrey
aifrey

Reputation: 62

you can use the custom validators

https://docs.djangoproject.com/en/dev/ref/validators/

from django.core.exceptions import ValidationError

def validate_max(value, **kwargs):   
    min = kwargs.get('min', 0)
    max = kwargs.get('max', 10)
    if str(value).isnum() and int(value) > max:
        raise ValidationError('%s is not in the range [%s..%s]' % (value, min, max))

or declare method clean for a field1

def clean_field1(self):
    value = self.cleaned_data['field1']
    try:
       ...
    except:
       raise ValidationError(...)
    return value

Upvotes: -6

Related Questions