flask.ext.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')
-
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.ext.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, two types are formatted: 1.
None
will be displayed as an empty string 2.bool
will be displayed as a checkmark if it isTrue
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:
from flask.ext.admin.model import typefmt MY_DEFAULT_FORMATTERS = dict(typefmt.BASE_FORMATTERS) MY_DEFAULT_FORMATTERS.update({ type(None): typefmt.null_formatter }) 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 contructor 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')
-
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 required class MyModelView(BaseModelView): form_args = dict( name=dict(label='First Name', validators=[required()]) )
-
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' } }
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.
-
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
-
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')
-
create_form
(obj=None)[source]¶ Instantiate model creation form and return it.
Override to implement custom behavior.
-
create_model
(form)[source]¶ Create model from the form.
Returns True 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
-
edit_form
(obj=None)[source]¶ Instantiate model editing form and return it.
Override to implement custom behavior.
-
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.ext.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_column_name
(field)[source]¶ Return a human-readable column name.
Parameters: field – Model field name.
-
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_edit_form
()[source]¶ Create form class for model editing view.
Override to implement customized behavior.
-
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)[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.
-
get_list_columns
()[source]¶ Returns a list of the model field names. If column_list was set, returns it. Otherwise calls scaffold_list_columns to generate the list from the model.
-
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.ext.admin.model.fields import ListEditableFieldList from flask.ext.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 CustomFieldList(ListEditableFieldList): widget = CustomWidget() class MyModelView(BaseModelView): def get_list_form(self): return self.scaffold_list_form(CustomFieldList)
-
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_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 after 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
(custom_fieldlist=<class 'flask_admin.model.fields.ListEditableFieldList'>, validators=None)[source]¶ Create form for the index_view using only the columns from self.column_editable_list.
Parameters: - validators – form_args dict with only validators {‘name’: {‘validators’: [required()]}}
- custom_fieldlist – A WTForm FieldList class. By default, ListEditableFieldList.
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.