Provide some default readonly form field renderers

This commit is contained in:
Lance Edgar 2018-01-10 20:46:49 -06:00
parent 485c96fec1
commit bfa398bee1

View file

@ -286,7 +286,7 @@ class Form(object):
""" """
def __init__(self, fields=None, schema=None, request=None, readonly=False, readonly_fields=[], def __init__(self, fields=None, schema=None, request=None, readonly=False, readonly_fields=[],
model_instance=None, model_class=None, nodes={}, enums={}, labels={}, renderers={}, model_instance=None, model_class=None, nodes={}, enums={}, labels={}, renderers=None,
widgets={}, defaults={}, validators={}, required={}, helptext={}, widgets={}, defaults={}, validators={}, required={}, helptext={},
action_url=None, cancel_url=None): action_url=None, cancel_url=None):
@ -304,6 +304,9 @@ class Form(object):
self.nodes = nodes or {} self.nodes = nodes or {}
self.enums = enums or {} self.enums = enums or {}
self.labels = labels or {} self.labels = labels or {}
if renderers is None and self.model_class:
self.renderers = self.make_renderers()
else:
self.renderers = renderers or {} self.renderers = renderers or {}
self.widgets = widgets or {} self.widgets = widgets or {}
self.defaults = defaults or {} self.defaults = defaults or {}
@ -334,6 +337,31 @@ class Form(object):
return fields return fields
def make_renderers(self):
"""
Return a default set of field renderers, based on :attr:`model_class`.
"""
if not self.model_class:
raise ValueError("Must define model_class to use make_renderers()")
mapper = orm.class_mapper(self.model_class)
renderers = {}
for field in self.fields:
if mapper.has_property(field):
prop = mapper.get_property(field)
if isinstance(prop, orm.ColumnProperty):
if len(prop.columns) == 1:
column = prop.columns[0]
if isinstance(column.type, sa.DateTime):
renderers[field] = self.render_datetime
elif isinstance(column.type, sa.Boolean):
renderers[field] = self.render_boolean
return renderers
def append(self, field): def append(self, field):
self.fields.append(field) self.fields.append(field)