flask_admin.model
¶
-
class
BaseModelView
(model, name=None, category=None, endpoint=None, url=None, static_folder=None, menu_class_name=None, menu_icon_type=None, menu_icon_value=None)[source]¶ Base model view.
This view does not make any assumptions on how models are stored or managed, but expects the following:
- The provided model is an object
- The model contains properties
- Each model contains an attribute which uniquely identifies it (i.e. a primary key for a database model)
- It is possible to retrieve a list of sorted models with pagination applied from a data source
- You can get one model by its identifier from the data source
Essentially, if you want to support a new data store, all you have to do is:
- Derive from the BaseModelView class
- Implement various data-related methods (get_list, get_one, create_model, etc)
- Implement automatic form generation from the model representation (scaffold_form)
-
can_create
= True¶ Is model creation allowed
-
can_edit
= True¶ Is model editing allowed
-
can_delete
= True¶ Is model deletion allowed
-
list_template
= 'admin/model/list.html'¶ Default list view template
-
edit_template
= 'admin/model/edit.html'¶ Default edit template
-
create_template
= 'admin/model/create.html'¶ Default create template
-
column_list
¶ Collection of the model field names for the list view. If set to None, will get them from the model.
For example:
class MyModelView(BaseModelView): column_list = ('name', 'last_name', 'email')
(Added in 1.4.0) SQLAlchemy model attributes can be used instead of strings:
class MyModelView(BaseModelView): column_list = ('name', User.last_name)
- When using SQLAlchemy models, you can reference related columns like this::
- class MyModelView(BaseModelView):
- column_list = (‘<relationship>.<related column name>’,)
-
column_exclude_list
¶ Collection of excluded list column names.
For example:
class MyModelView(BaseModelView): column_exclude_list = ('last_name', 'email')
-
column_labels
¶ Dictionary where key is column name and value is string to display.
For example:
class MyModelView(BaseModelView): column_labels = dict(name='Name', last_name='Last Name')
-
column_descriptions
= None¶ Dictionary where key is column name and value is description for list view column or add/edit form field.
For example:
class MyModelView(BaseModelView): column_descriptions = dict( full_name='First and Last name' )
-
column_formatters
¶ 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): column_formatters = dict(price=lambda v, c, m, p: m.price*2)
or using Jinja2 macro in template:
from flask_admin.model.template import macro class MyModelView(BaseModelView): column_formatters = dict(price=macro('render_price')) # in template {% macro render_price(model, column) %} {{ model.price * 2 }} {% endmacro %}
The Callback function has the prototype:
def formatter(view, context, model, name): # `view` is current administrative view # `context` is instance of jinja2.runtime.Context # `model` is model instance # `name` is property name pass
-
column_type_formatters
¶ Dictionary of value type formatters to be used in the list view.
By default, three types are formatted:
None
will be displayed as an empty stringbool
will be displayed as a checkmark if it isTrue
list
will be joined using ‘, ‘
If you don’t like the default behavior and don’t want any type formatters applied, just override this property with an empty dictionary:
class MyModelView(BaseModelView): column_type_formatters = dict()
If you want to display NULL instead of an empty string, you can do something like this. Also comes with bonus date formatter:
from datetime import date from flask_admin.model import typefmt def date_format(view, value): return value.strftime('%d.%m.%Y') MY_DEFAULT_FORMATTERS = dict(typefmt.BASE_FORMATTERS) MY_DEFAULT_FORMATTERS.update({ type(None): typefmt.null_formatter, date: date_format }) class MyModelView(BaseModelView): column_type_formatters = MY_DEFAULT_FORMATTERS
Type formatters have lower priority than list column formatters.
The callback function has following prototype:
def type_formatter(view, value): # `view` is current administrative view # `value` value to format pass
-
column_display_pk
¶ Controls if the primary key should be displayed in the list view.
-
column_sortable_list
¶ Collection of the sortable columns for the list view. If set to None, will get them from the model.
For example:
class MyModelView(BaseModelView): column_sortable_list = ('name', 'last_name')
If you want to explicitly specify field/column to be used while sorting, you can use a tuple:
class MyModelView(BaseModelView): column_sortable_list = ('name', ('user', 'user.username'))
When using SQLAlchemy models, model attributes can be used instead of strings:
class MyModelView(BaseModelView): column_sortable_list = ('name', ('user', User.username))
-
column_searchable_list
¶ A collection of the searchable columns. It is assumed that only text-only fields are searchable, but it is up to the model implementation to decide.
Example:
class MyModelView(BaseModelView): column_searchable_list = ('name', 'email')
-
column_default_sort
= None¶ Default sort column if no sorting is applied.
Example:
class MyModelView(BaseModelView): column_default_sort = 'user'
You can use tuple to control ascending descending order. In following example, items will be sorted in descending order:
class MyModelView(BaseModelView): column_default_sort = ('user', True)
-
column_choices
= None¶ Map choices to columns in list view
Example:
class MyModelView(BaseModelView): column_choices = { 'my_column': [ ('db_value', 'display_value'), ] }
-
column_filters
= None¶ Collection of the column filters.
Can contain either field names or instances of
BaseFilter
classes.Example:
class MyModelView(BaseModelView): column_filters = ('user', 'email')
-
form
= None¶ Form class. Override if you want to use custom form for your model. Will completely disable form scaffolding functionality.
For example:
class MyForm(Form): name = StringField('Name') class MyModelView(BaseModelView): form = MyForm
-
form_base_class
= <class 'flask_admin.form.BaseForm'>¶ Base form class. Will be used by form scaffolding function when creating model form.
Useful if you want to have custom constructor or override some fields.
Example:
class MyBaseForm(Form): def do_something(self): pass class MyModelView(BaseModelView): form_base_class = MyBaseForm
-
form_columns
= None¶ Collection of the model field names for the form. If set to None will get them from the model.
Example:
class MyModelView(BaseModelView): form_columns = ('name', 'email')
(Added in 1.4.0) SQLAlchemy model attributes can be used instead of strings:
class MyModelView(BaseModelView): form_columns = ('name', User.last_name)
SQLA Note: Model attributes must be on the same model as your ModelView or you will need to use inline_models.
-
form_excluded_columns
¶ Collection of excluded form field names.
For example:
class MyModelView(BaseModelView): form_excluded_columns = ('last_name', 'email')
-
form_args
= None¶ Dictionary of form field arguments. Refer to WTForms documentation for list of possible options.
Example:
from wtforms.validators import DataRequired class MyModelView(BaseModelView): form_args = dict( name=dict(label='First Name', validators=[DataRequired()]) )
-
form_overrides
= None¶ Dictionary of form column overrides.
Example:
class MyModelView(BaseModelView): form_overrides = dict(name=wtf.FileField)
-
form_widget_args
= None¶ Dictionary of form widget rendering arguments. Use this to customize how widget is rendered without using custom template.
Example:
class MyModelView(BaseModelView): form_widget_args = { 'description': { 'rows': 10, 'style': 'color: black' }, 'other_field': { 'disabled': True } }
Changing the format of a DateTimeField will require changes to both form_widget_args and form_args.
Example:
form_args = dict( start=dict(format='%Y-%m-%d %I:%M %p') # changes how the input is parsed by strptime (12 hour time) ) form_widget_args = dict( start={ 'data-date-format': u'yyyy-mm-dd HH:ii P', 'data-show-meridian': 'True' } # changes how the DateTimeField displays the time )
-
form_extra_fields
= None¶ Dictionary of additional fields.
Example:
class MyModelView(BaseModelView): form_extra_fields = { 'password': PasswordField('Password') }
You can control order of form fields using
form_columns
property. For example:class MyModelView(BaseModelView): form_columns = ('name', 'email', 'password', 'secret') form_extra_fields = { 'password': PasswordField('Password') }
In this case, password field will be put between email and secret fields that are autogenerated.
-
form_ajax_refs
= None¶ Use AJAX for foreign key model loading.
Should contain dictionary, where key is field name and value is either a dictionary which configures AJAX lookups or backend-specific AjaxModelLoader class instance.
For example, it can look like:
class MyModelView(BaseModelView): form_ajax_refs = { 'user': { 'fields': ('first_name', 'last_name', 'email'), 'page_size': 10 } }
Or with SQLAlchemy backend like this:
class MyModelView(BaseModelView): form_ajax_refs = { 'user': QueryAjaxModelLoader('user', db.session, User, fields=['email'], page_size=10) }
If you need custom loading functionality, you can implement your custom loading behavior in your AjaxModelLoader class.
-
form_create_rules
= None¶ Customized rules for the create form. Override form_rules if present.
-
form_edit_rules
= None¶ Customized rules for the edit form. Override form_rules if present.
-
action_disallowed_list
¶ Set of disallowed action names. For example, if you want to disable mass model deletion, do something like this:
- class MyModelView(BaseModelView):
- action_disallowed_list = [‘delete’]
-
page_size
= 20¶ Default page size for pagination.
-
can_set_page_size
= False¶ Allows to select page size via dropdown list
-
action_form
(obj=None)[source]¶ Instantiate model action form and return it.
Override to implement custom behavior.
-
after_model_change
(form, model, is_created)[source]¶ Perform some actions after a model was created or updated and committed to the database.
Called from create_model after successful database commit.
By default does nothing.
Parameters: - form – Form used to create/update model
- model – Model that was created/updated
- is_created – True if model was created, False if model was updated
-
after_model_delete
(model)[source]¶ Perform some actions after a model was deleted and committed to the database.
Called from delete_model after successful database commit (if it has any meaning for a store backend).
By default does nothing.
Parameters: model – Model that was deleted
-
can_export
= False¶ Is model list export allowed
-
can_view_details
= False¶ Setting this to true will enable the details view. This is recommended when there are too many columns to display in the list_view.
-
column_details_exclude_list
= None¶ Collection of fields excluded from the details view.
-
column_details_list
= None¶ Collection of the field names included in the details view. If set to None, will get them from the model.
-
column_display_actions
= True¶ Controls the display of the row actions (edit, delete, details, etc.) column in the list view.
Useful for preventing a blank column from displaying if your view does not use any build-in or custom row actions.
This column is not hidden automatically due to backwards compatibility.
Note: This only affects display and does not control whether the row actions endpoints are accessible.
-
column_editable_list
= None¶ Collection of the columns which can be edited from the list view.
For example:
class MyModelView(BaseModelView): column_editable_list = ('name', 'last_name')
-
column_export_exclude_list
= None¶ Collection of fields excluded from the export.
-
column_export_list
= None¶ Collection of the field names included in the export. If set to None, will get them from the model.
-
column_extra_row_actions
= None¶ List of row actions (instances of
BaseListRowAction
).Flask-Admin will generate standard per-row actions (edit, delete, etc) and will append custom actions from this list right after them.
For example:
from flask_admin.model.template import EndpointLinkRowAction, LinkRowAction class MyModelView(BaseModelView): column_extra_row_actions = [ LinkRowAction('glyphicon glyphicon-off', 'http://direct.link/?id={row_id}'), EndpointLinkRowAction('glyphicon glyphicon-test', 'my_view.index_view') ]
-
column_formatters_export
= None¶ Dictionary of list view column formatters to be used for export.
Defaults to column_formatters when set to None.
Functions the same way as column_formatters except that macros are not supported.
-
column_type_formatters_export
= None¶ Dictionary of value type formatters to be used in the export.
By default, two types are formatted:
None
will be displayed as an empty stringlist
will be joined using ‘, ‘
Functions the same way as column_type_formatters.
-
create_form
(obj=None)[source]¶ Instantiate model creation form and return it.
Override to implement custom behavior.
-
create_modal
= False¶ Setting this to true will display the create_view as a modal dialog.
-
create_modal_template
= 'admin/model/modals/create.html'¶ Default create modal template
-
create_model
(form)[source]¶ Create model from the form.
Returns the model instance if operation succeeded.
Must be implemented in the child class.
Parameters: form – Form instance
-
delete_form
()[source]¶ Instantiate model delete form and return it.
Override to implement custom behavior.
The delete form originally used a GET request, so delete_form accepts both GET and POST request for backwards compatibility.
-
delete_model
(model)[source]¶ Delete model.
Returns True if operation succeeded.
Must be implemented in the child class.
Parameters: model – Model instance
-
details_modal
= False¶ Setting this to true will display the details_view as a modal dialog.
-
details_modal_template
= 'admin/model/modals/details.html'¶ Default details modal view template
-
details_template
= 'admin/model/details.html'¶ Default details view template
-
edit_form
(obj=None)[source]¶ Instantiate model editing form and return it.
Override to implement custom behavior.
-
edit_modal
= False¶ Setting this to true will display the edit_view as a modal dialog.
-
edit_modal_template
= 'admin/model/modals/edit.html'¶ Default edit modal template
-
export_max_rows
= 0¶ Maximum number of rows allowed for export.
Unlimited by default. Uses page_size if set to None.
-
export_types
= ['csv']¶ A list of available export filetypes. csv only is default, but any filetypes supported by tablib can be used.
Check tablib for https://github.com/kennethreitz/tablib/blob/master/README.rst for supported types.
-
form_rules
= None¶ List of rendering rules for model creation form.
This property changed default form rendering behavior and makes possible to rearrange order of rendered fields, add some text between fields, group them, etc. If not set, will use default Flask-Admin form rendering logic.
Here’s simple example which illustrates how to use:
from flask_admin.form import rules class MyModelView(ModelView): form_rules = [ # Define field set with header text and four fields rules.FieldSet(('first_name', 'last_name', 'email', 'phone'), 'User'), # ... and it is just shortcut for: rules.Header('User'), rules.Field('first_name'), rules.Field('last_name'), # ... # It is possible to create custom rule blocks: MyBlock('Hello World'), # It is possible to call macros from current context rules.Macro('my_macro', foobar='baz') ]
-
get_action_form
()[source]¶ Create form class for a model action.
Override to implement customized behavior.
-
get_column_name
(field)[source]¶ Return a human-readable column name.
Parameters: field – Model field name.
-
get_column_names
(only_columns, excluded_columns)[source]¶ Returns a list of tuples with the model field name and formatted field name.
Parameters: - only_columns – List of columns to include in the results. If not set, scaffold_list_columns will generate the list from the model.
- excluded_columns – List of columns to exclude from the results if only_columns is not set.
-
get_create_form
()[source]¶ Create form class for model creation view.
Override to implement customized behavior.
-
get_delete_form
()[source]¶ Create form class for model delete view.
Override to implement customized behavior.
-
get_details_columns
()[source]¶ Uses get_column_names to get a list of tuples with the model field name and formatted name for the columns in column_details_list and not in column_details_exclude_list. If column_details_list is not set, the columns from scaffold_list_columns will be used.
-
get_edit_form
()[source]¶ Create form class for model editing view.
Override to implement customized behavior.
-
get_export_columns
()[source]¶ Uses get_column_names to get a list of tuples with the model field name and formatted name for the columns in column_export_list and not in column_export_exclude_list. If column_export_list is not set, it will attempt to use the columns from column_list or finally the columns from scaffold_list_columns will be used.
-
get_export_value
(model, name)[source]¶ Returns the value to be displayed in export. Allows export to use different (non HTML) formatters.
Parameters: - model – Model instance
- name – Field name
-
get_filter_arg
(index, flt)[source]¶ Given a filter flt, return a unique name for that filter in this view.
Does not include the flt[n]_ portion of the filter name.
Parameters: - index – Filter index in _filters array
- flt – Filter instance
-
get_filters
()[source]¶ Return a list of filter objects.
If your model backend implementation does not support filters, override this method and return None.
-
get_form
()[source]¶ Get form class.
If
self.form
is set, will return it and will callself.scaffold_form
otherwise.Override to implement customized behavior.
-
get_list
(page, sort_field, sort_desc, search, filters, page_size=None)[source]¶ Return a paginated and sorted list of models from the data source.
Must be implemented in the child class.
Parameters: - page – Page number, 0 based. Can be set to None if it is first page.
- sort_field – Sort column name or None.
- sort_desc – If set to True, sorting is in descending order.
- search – Search query
- filters – List of filter tuples. First value in a tuple is a search index, second value is a search value.
- page_size – Number of results. Defaults to ModelView’s page_size. Can be overriden to change the page_size limit. Removing the page_size limit requires setting page_size to 0 or False.
-
get_list_columns
()[source]¶ Uses get_column_names to get a list of tuples with the model field name and formatted name for the columns in column_list and not in column_exclude_list. If column_list is not set, the columns from scaffold_list_columns will be used.
-
get_list_form
()[source]¶ Get form class for the editable list view.
Uses only validators from form_args to build the form class.
Allows overriding the editable list view field/widget. For example:
from flask_admin.model.widgets import XEditableWidget class CustomWidget(XEditableWidget): def get_kwargs(self, subfield, kwargs): if subfield.type == 'TextAreaField': kwargs['data-type'] = 'textarea' kwargs['data-rows'] = '20' # elif: kwargs for other fields return kwargs class MyModelView(BaseModelView): def get_list_form(self): return self.scaffold_list_form(widget=CustomWidget)
-
get_list_row_actions
()[source]¶ Return list of row action objects, each is instance of
BaseListRowAction
-
get_list_value
(context, model, name)[source]¶ Returns the value to be displayed in the list view
Parameters: - context –
jinja2.runtime.Context
- model – Model instance
- name – Field name
- context –
-
get_one
(id)[source]¶ Return one model by its id.
Must be implemented in the child class.
Parameters: id – Model id
-
get_save_return_url
(model, is_created=False)[source]¶ Return url where user is redirected after successful form save.
Parameters: - model – Saved object
- is_created – Whether new object was created or existing one was updated
For example, redirect use to object details view after form save:
class MyModelView(ModelView): can_view_details = True def get_save_return_url(self, model, is_created): return self.get_url('.details_view', id=model.id)
-
get_sortable_columns
()[source]¶ Returns a dictionary of the sortable columns. Key is a model field name and value is sort column (for example - attribute).
If column_sortable_list is set, will use it. Otherwise, will call scaffold_sortable_columns to get them from the model.
-
handle_filter
(filter)[source]¶ Postprocess (add joins, etc) for a filter.
Parameters: filter – Filter object to postprocess
-
init_search
()[source]¶ Initialize search. If data provider does not support search, init_search will return False.
-
is_action_allowed
(name)[source]¶ Override this method to allow or disallow actions based on some condition.
The default implementation only checks if the particular action is not in action_disallowed_list.
-
is_sortable
(name)[source]¶ Verify if column is sortable.
Not case-sensitive.
Parameters: name – Column name.
-
is_valid_filter
(filter)[source]¶ Verify that the provided filter object is valid.
Override in model backend implementation to verify if the provided filter type is allowed.
Parameters: filter – Filter object to verify.
-
list_form
(obj=None)[source]¶ Instantiate model editing form for list view and return it.
Override to implement custom behavior.
-
named_filter_urls
= False¶ Set to True to use human-readable names for filters in URL parameters.
False by default so as to be robust across translations.
Changing this parameter will break any existing URLs that have filters.
-
on_form_prefill
(form, id)[source]¶ Perform additional actions to pre-fill the edit form.
Called from edit_view, if the current action is rendering the form rather than receiving client side input, after default pre-filling has been performed.
By default does nothing.
You only need to override this if you have added custom fields that depend on the database contents in a way that Flask-admin can’t figure out by itself. Fields that were added by name of a normal column or relationship should work out of the box.
Parameters: - form – Form instance
- id – id of the object that is going to be edited
-
on_model_change
(form, model, is_created)[source]¶ Perform some actions before a model is created or updated.
Called from create_model and update_model in the same transaction (if it has any meaning for a store backend).
By default does nothing.
Parameters: - form – Form used to create/update model
- model – Model that will be created/updated
- is_created – Will be set to True if model was created and to False if edited
-
on_model_delete
(model)[source]¶ Perform some actions before a model is deleted.
Called from delete_model in the same transaction (if it has any meaning for a store backend).
By default do nothing.
-
scaffold_filters
(name)[source]¶ Generate filter object for the given name
Parameters: name – Name of the field
-
scaffold_form
()[source]¶ Create form.BaseForm inherited class from the model. Must be implemented in the child class.
-
scaffold_list_columns
()[source]¶ Return list of the model field names. Must be implemented in the child class.
Expected return format is list of tuples with field name and display text. For example:
['name', 'first_name', 'last_name']
-
scaffold_list_form
(widget=None, validators=None)[source]¶ Create form for the index_view using only the columns from self.column_editable_list.
Parameters: - widget – WTForms widget class. Defaults to XEditableWidget.
- validators – form_args dict with only validators {‘name’: {‘validators’: [DataRequired()]}}
Must be implemented in the child class.
-
scaffold_sortable_columns
()[source]¶ Returns dictionary of sortable columns. Must be implemented in the child class.
Expected return format is a dictionary, where keys are field names and values are property names.
-
simple_list_pager
= False¶ Enable or disable simple list pager. If enabled, model interface would not run count query and will only show prev/next pager buttons.