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)
Is model creation allowed
Is model editing allowed
Is model deletion allowed
Default list view template
Default edit template
Default create template
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')
Collection of excluded list column names.
For example:
class MyModelView(BaseModelView):
column_exclude_list = ('last_name', 'email')
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')
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'
)
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
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 is True
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
Controls if the primary key should be displayed in the list view.
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))
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')
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)
Map choices to columns in list view
Example:
class MyModelView(BaseModelView):
column_choices = {
'my_column': [
('db_value', 'display_value'),
]
}
Collection of the column filters.
Can contain either field names or instances of BaseFilter classes.
Example:
class MyModelView(BaseModelView):
column_filters = ('user', 'email')
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
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
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')
Collection of excluded form field names.
For example:
class MyModelView(BaseModelView):
form_excluded_columns = ('last_name', 'email')
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()])
)
Dictionary of form column overrides.
Example:
class MyModelView(BaseModelView):
form_overrides = dict(name=wtf.FileField)
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
)
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.
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.
Customized rules for the create form. Override form_rules if present.
Customized rules for the edit form. Override form_rules if present.
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’]
Default page size for pagination.
Mass-model action view.
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: |
|
---|
Instantiate model creation form and return it.
Override to implement custom behavior.
Create model from the form.
Returns True if operation succeeded.
Must be implemented in the child class.
Parameters: | form – Form instance |
---|
Create model view
Delete model.
Returns True if operation succeeded.
Must be implemented in the child class.
Parameters: | model – Model instance |
---|
Delete model view. Only POST method is allowed.
Instantiate model editing form and return it.
Override to implement custom behavior.
Edit model view
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')
]
Return a human-readable column name.
Parameters: | field – Model field name. |
---|
Create form class for model creation view.
Override to implement customized behavior.
Create form class for model editing view.
Override to implement customized behavior.
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: |
|
---|
Return a list of filter objects.
If your model backend implementation does not support filters, override this method and return None.
Get form class.
If self.form is set, will return it and will call self.scaffold_form otherwise.
Override to implement customized behavior.
Return a paginated and sorted list of models from the data source.
Must be implemented in the child class.
Parameters: |
|
---|
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.
Returns the value to be displayed in the list view
Parameters: |
|
---|
Return one model by its id.
Must be implemented in the child class.
Parameters: | id – Model id |
---|
Return PK value from a model object.
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.
Postprocess (add joins, etc) for a filter.
Parameters: | filter – Filter object to postprocess |
---|
List view
Initialize search. If data provider does not support search, init_search will return False.
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.
Verify if column is sortable.
Parameters: | name – Column name. |
---|
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. |
---|
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.
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: |
|
---|
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: |
|
---|
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.
Generate filter object for the given name
Parameters: | name – Name of the field |
---|
Create form.BaseForm inherited class from the model. Must be implemented in the child class.
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']
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.
Update model from the form.
Returns True if operation succeeded.
Must be implemented in the child class.
Parameters: |
|
---|
Validate the form on submit.
Parameters: | form – Form to validate |
---|