Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does WTForms know to use validate_<field name> if it is defined to validate a field?

When I use WTForms to define a form, I can add a validate_<field name> method to the subclass, and WTForms knows to use it to validate the named field. I find this interesting because the name of the method depends on the name of the field class attribute. How does it figure this out?

class UploadForm(Form):
    image = FileField("image file")
    submit = SubmitField("Submit")

    def validate_image(self,field):
        if field.data.filename[-4:].lower() != ".jpg":
            raise ValidationError("nope not allowed")
like image 406
Zion Avatar asked Dec 20 '25 20:12

Zion


1 Answers

WTForms inspects the class when it is called (calling a class creates an instance: form = Form()) and records the fields and their names. Then during validation, it looks if the instance has a method validate_<field_name>.

Within FormMeta.__call__, it uses the dir function to list the names defined on the class object and record the fields.

for name in dir(cls):  # look at the names on the class
    if not name.startswith('_'):  # ignore names with leading _
        unbound_field = getattr(cls, name)  # get the value
        if hasattr(unbound_field, '_formfield'):  # make sure it's a field
            fields.append((name, unbound_field))  # record it

Within Form.validate it uses the getattr function to try to get the value of the name validate_<field name> for each field it recorded.

for name in self._fields:  # go through recorded field names
    # get method with name validate_<field name> or None
    inline = getattr(self.__class__, 'validate_%s' % name, None)
    if inline is not None:  # if there is such a method record it
        extra[name] = [inline]
like image 138
davidism Avatar answered Dec 23 '25 08:12

davidism



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!