Commits

Maciej Wiatrzyk committed 6f30256

allow `form` and `field` additional keyword args of SA validators to be optional

This allows to use model_form with `use_sa_validators=True` without any change
on the model side (unless it is required to access form or field - then both
arguments must be specified). Examples:

If you don't need to acces form or field (i.e. you don't care from where
your validator is called), your model can look like this:

class Model(object):
@validates('foo')
def validate_foo(self, key, value):
pass

But if you do, you must provide additional args:

class Model(object):
@validates('foo')
def validate_foo(self, key, value, form=None, field=None):
pass

  • Participants
  • Parent commits 5b93a4f

Comments (0)

Files changed (1)

wtforms/ext/sqlalchemy/orm.py

         (via `validates` decorator). Using this option will allow the user to
         have common validation routines - both for model and form created for
         the model. Using this option requires `obj` parameter of `Form` class
-        to be set to instance of `model` class and the SQLAlchemy validators to
-        accept additional keyword arguments: ``form`` and ``field``, both
-        initialized with ``None``, but set to concrete :class:`Form` and
-        :class:`Field` instances once called by WTForms.  This option is
+        to be set to instance of `model` class. SQLAlchemy validators can be
+        supplied with additional ``form`` and ``field`` keyword args
+        initialized to ``None``, providing functionality of standard WTForms
+        validators (if validator is called in WTForms context).  This option is
         disabled by default (for backward compatibility).
     """
     class ModelForm(base_class):
             raise TypeError(
                 "form.obj: expecting instance of %s, found %s" %
                 (model, type(form.obj)))
-        validator(form.obj, field.name, field.data,
-            form=form, field=field)
+        # Changed: allow `form` and `field` additional params to be optional
+        argspec = inspect.getargspec(validator)
+        if 'form' in argspec[0] and 'field' in argspec[0]:
+            validator(form.obj, field.name, field.data, form=form, field=field)
+        else:
+            validator(form.obj, field.name, field.data)
 
     __sa_validator.func_name = validator.func_name
     return __sa_validator