diff --git a/tailbone/forms/validators.py b/tailbone/forms/validators.py index eb81833b..013a70d1 100644 --- a/tailbone/forms/validators.py +++ b/tailbone/forms/validators.py @@ -2,7 +2,7 @@ ################################################################################ # # Rattail -- Retail Software Framework -# Copyright © 2010-2015 Lance Edgar +# Copyright © 2010-2016 Lance Edgar # # This file is part of Rattail. # @@ -24,53 +24,70 @@ Custom FormEncode Validators """ -from __future__ import unicode_literals +from __future__ import unicode_literals, absolute_import from rattail.db import model -import formencode -from formencode import validators +import formencode as fe from tailbone.db import Session -class ValidCustomer(validators.FancyValidator): +class ModelValidator(fe.validators.FancyValidator): + """ + Generic validator for data model reference fields. + """ + model_class = None + + @property + def model_name(self): + self.model_class.__name__ + + def _to_python(self, value, state): + if value: + obj = Session.query(self.model_class).get(value) + if obj: + return obj + raise formencode.Invalid("{} not found".format(self.model_name), value, state) + + +class ValidStore(ModelValidator): + """ + Validator for store field. + """ + model_class = model.Store + + +class ValidCustomer(ModelValidator): """ Validator for customer field. """ - - def _to_python(self, value, state): - if not value: - return None - customer = Session.query(model.Customer).get(value) - if not customer: - raise formencode.Invalid("Customer not found", value, state) - return customer + model_class = model.Customer -class ValidProduct(validators.FancyValidator): +class ValidDepartment(ModelValidator): + """ + Validator for department field. + """ + model_class = model.Department + + +class ValidEmployee(ModelValidator): + """ + Validator for employee field. + """ + model_class = model.Employee + + +class ValidProduct(ModelValidator): """ Validator for product field. """ - - def _to_python(self, value, state): - if not value: - return None - product = Session.query(model.Product).get(value) - if not product: - raise formencode.Invalid("Product not found", value, state) - return product + model_class = model.Product -class ValidUser(validators.FancyValidator): +class ValidUser(ModelValidator): """ - Validator for product field. + Validator for user field. """ - - def to_python(self, value, state): - if not value: - return None - user = Session.query(model.User).get(value) - if not user: - raise formencode.Invalid("User not found.", value, state) - return user + model_class = model.User