diff --git a/tailbone/forms2/types.py b/tailbone/forms2/types.py index 977b8bc6..e9fcdb59 100644 --- a/tailbone/forms2/types.py +++ b/tailbone/forms2/types.py @@ -2,7 +2,7 @@ ################################################################################ # # Rattail -- Retail Software Framework -# Copyright © 2010-2017 Lance Edgar +# Copyright © 2010-2018 Lance Edgar # # This file is part of Rattail. # @@ -26,8 +26,12 @@ Form Schema Types from __future__ import unicode_literals, absolute_import +from rattail.db import model + import colander +from tailbone.db import Session + class JQueryTime(colander.Time): """ @@ -52,3 +56,59 @@ class JQueryTime(colander.Time): # re-try first format, for "better" error message return colander.timeparse(cstruct, formats[0]) + + +class ObjectType(colander.SchemaType): + """ + Custom schema type for scalar ORM relationship fields. + """ + model_class = None + + @property + def model_title(self): + self.model_class.get_model_title() + + @property + def session(self): + return Session() + + def serialize(self, node, appstruct): + if appstruct is colander.null: + return colander.null + return six.text_type(appstruct) + + def deserialize(self, node, cstruct): + if not cstruct: + return None + obj = self.session.query(self.model_class).get(cstruct) + if not obj: + raise colander.Invalid(node, "{} not found".format(self.model_title)) + return obj + + +class StoreType(ObjectType): + """ + Custom schema type for store field. + """ + model_class = model.Store + + +class CustomerType(ObjectType): + """ + Custom schema type for customer field. + """ + model_class = model.Customer + + +class ProductType(ObjectType): + """ + Custom schema type for product relationship field. + """ + model_class = model.Product + + +class UserType(ObjectType): + """ + Custom schema type for user field. + """ + model_class = model.User