Skip to content

Commit

Permalink
Add support for validator disabling, fixes #75
Browse files Browse the repository at this point in the history
  • Loading branch information
kvesteri committed Oct 14, 2014
1 parent 4a49568 commit 27457d1
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
13 changes: 13 additions & 0 deletions docs/validators.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ By default WTForms-Alchemy ModelForm assigns the following validators:
* TimeRange validator if column is of type Time and info parameter has min or max arguments defined
* Unique validator if column has a unique index
* Length validator for String/Unicode columns with max length
* Optional validator for all nullable columns


Unique validator
Expand Down Expand Up @@ -215,3 +216,15 @@ Here is the full list of configuration options you can use to override default v
* time_range_validator

* optional_validator


Disabling validators
--------------------

You can disable certain validators by assigning them as `None`. Let's say you want to disable nullable columns having `Optional` validator. This can be achieved as follows::


class UserForm(ModelForm):
class Meta:
model = User
optional_validator = None
16 changes: 15 additions & 1 deletion tests/test_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def test_not_nullable_fields_with_defaults_are_not_required(self):
self.init(nullable=False, default=u'default')
self.assert_not_required('test_column')

def test_assigns_not_nullable_integers_as_optional(self):
def test_assigns_nullable_integers_as_optional(self):
self.init(sa.Integer, nullable=True)
self.assert_optional('test_column')

Expand Down Expand Up @@ -226,6 +226,20 @@ class Meta:
form = ModelTestForm()
assert form.test_column.validators[1].message == 'Wrong length'

def test_override_optional_validator_as_none(self):
class ModelTest(self.base):
__tablename__ = 'model_test'
id = sa.Column(sa.Integer, primary_key=True)
test_column = sa.Column(sa.Boolean, nullable=True)

class ModelTestForm(ModelForm):
class Meta:
model = ModelTest
optional_validator = None

form = ModelTestForm()
assert form.test_column.validators == []

def test_override_unique_validator(self):
class ModelTest(self.base):
__tablename__ = 'model_test'
Expand Down
3 changes: 3 additions & 0 deletions wtforms_alchemy/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -519,6 +519,9 @@ def required_validator(self, column):
def get_validator(self, name, **kwargs):
attr_name = '%s_validator' % name
attr = getattr(self.meta, attr_name)
if attr is None:
return attr

if inspect.ismethod(attr):
return six.get_unbound_function(attr)(**kwargs)
else:
Expand Down

0 comments on commit 27457d1

Please sign in to comment.