Commit 406ab211 authored by Serge S. Koval's avatar Serge S. Koval

Added support for list formatting callbacks in model admin. Fixed #43 and #23

parent 54b505ca
...@@ -94,6 +94,7 @@ class PostAdmin(sqlamodel.ModelView): ...@@ -94,6 +94,7 @@ class PostAdmin(sqlamodel.ModelView):
# Just call parent class with predefined model. # Just call parent class with predefined model.
super(PostAdmin, self).__init__(Post, session) super(PostAdmin, self).__init__(Post, session)
if __name__ == '__main__': if __name__ == '__main__':
# Create admin # Create admin
admin = admin.Admin(app, 'Simple Models') admin = admin.Admin(app, 'Simple Models')
......
...@@ -69,6 +69,24 @@ class BaseModelView(BaseView, ActionsMixin): ...@@ -69,6 +69,24 @@ class BaseModelView(BaseView, ActionsMixin):
excluded_list_columns = ('last_name', 'email') excluded_list_columns = ('last_name', 'email')
""" """
list_formatters = dict()
"""
Dictionary of list view column formatters.
For example, if you want to show price multiplied by
two, you can do something like this::
class MyModelView(BaseModelView):
list_formatters = dict(price=lambda m, p: m.price*2)
Callback function has following prototype::
def formatter(model, name):
# model is model instance
# name is property name
pass
"""
rename_columns = None rename_columns = None
""" """
Dictionary where key is column name and value is string to display. Dictionary where key is column name and value is string to display.
...@@ -647,6 +665,20 @@ class BaseModelView(BaseView, ActionsMixin): ...@@ -647,6 +665,20 @@ class BaseModelView(BaseView, ActionsMixin):
""" """
return name not in self.disallowed_actions return name not in self.disallowed_actions
def get_list_value(self, model, name):
"""
Returns value to be displayed in list view
`model`
Model instance
`name`
Field name
"""
if name in self.list_formatters:
return self.list_formatters[name](model, name)
return rec_getattr(model, name)
# Views # Views
@expose('/') @expose('/')
def index_view(self): def index_view(self):
...@@ -711,7 +743,7 @@ class BaseModelView(BaseView, ActionsMixin): ...@@ -711,7 +743,7 @@ class BaseModelView(BaseView, ActionsMixin):
# Stuff # Stuff
enumerate=enumerate, enumerate=enumerate,
get_pk_value=self.get_pk_value, get_pk_value=self.get_pk_value,
get_value=rec_getattr, get_value=self.get_list_value,
return_url=self._get_url('.index_view', return_url=self._get_url('.index_view',
page, page,
sort_idx, sort_idx,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment