SQLAlchemy model backend implementation.

class ModelView(model, session, name=None, category=None, endpoint=None, url=None, static_folder=None, menu_class_name=None, menu_icon_type=None, menu_icon_value=None)[source]

SQLAlchemy model view

Usage sample:

admin = Admin()
admin.add_view(ModelView(User, db.session))

Class inherits configuration options from BaseModelView and they’re not displayed here.

Enable automatic detection of displayed foreign keys in this view and perform automatic joined loading for related models to improve query performance.

Please note that detection is not recursive: if __unicode__ method of related model uses another model to generate string representation, it will still make separate database call.

List of parameters for SQLAlchemy subqueryload. Overrides column_auto_select_related property.

For example:

class PostAdmin(ModelView):
    column_select_related_list = ('user', 'city')

You can also use properties:

class PostAdmin(ModelView):
    column_select_related_list = (Post.user, Post.city)

Please refer to the subqueryload on list of possible values.


Collection of the searchable columns.


class MyModelView(ModelView):
    column_searchable_list = ('name', 'email')

You can also pass columns:

class MyModelView(ModelView):
    column_searchable_list = (User.name, User.email)

The following search rules apply:

  • If you enter ZZZ in the UI search field, it will generate ILIKE '%ZZZ%' statement against searchable columns.
  • If you enter multiple words, each word will be searched separately, but only rows that contain all words will be displayed. For example, searching for abc def will find all rows that contain abc and def in one or more columns.
  • If you prefix your search term with ^, it will find all rows that start with ^. So, if you entered ^ZZZ then ILIKE 'ZZZ%' will be used.
  • If you prefix your search term with =, it will perform an exact match. For example, if you entered =ZZZ, the statement ILIKE 'ZZZ' will be used.
column_filters = None

Collection of the column filters.

Can contain either field names or instances of flask_admin.contrib.sqla.filters.BaseSQLAFilter classes.

Filters will be grouped by name when displayed in the drop-down.

For example:

class MyModelView(BaseModelView):
    column_filters = ('user', 'email')


from flask_admin.contrib.sqla.filters import BooleanEqualFilter

class MyModelView(BaseModelView):
    column_filters = (BooleanEqualFilter(column=User.name, name='Name'),)


from flask_admin.contrib.sqla.filters import BaseSQLAFilter

class FilterLastNameBrown(BaseSQLAFilter):
    def apply(self, query, value, alias=None):
        if value == '1':
            return query.filter(self.column == "Brown")
            return query.filter(self.column != "Brown")

    def operation(self):
        return 'is Brown'

class MyModelView(BaseModelView):
    column_filters = [
            User.last_name, 'Last Name', options=(('1', 'Yes'), ('0', 'No'))
filter_converter = <flask_admin.contrib.sqla.filters.FilterConverter object>

Field to filter converter.

Override this attribute to use non-default converter.

model_form_converter = <class 'flask_admin.contrib.sqla.form.AdminModelConverter'>

Model form conversion class. Use this to implement custom field conversion logic.

For example:

class MyModelConverter(AdminModelConverter):

class MyAdminView(ModelView):
    model_form_converter = MyModelConverter
inline_model_form_converter = <class 'flask_admin.contrib.sqla.form.InlineModelConverter'>

Inline model conversion class. If you need some kind of post-processing for inline forms, you can customize behavior by doing something like this:

class MyInlineModelConverter(InlineModelConverter):
    def post_process(self, form_class, info):
        form_class.value = wtf.StringField('value')
        return form_class

class MyAdminView(ModelView):
    inline_model_form_converter = MyInlineModelConverter
fast_mass_delete = False

If set to False and user deletes more than one model using built in action, all models will be read from the database and then deleted one by one giving SQLAlchemy a chance to manually cleanup any dependencies (many-to-many relationships, etc).

If set to True, will run a DELETE statement which is somewhat faster, but may leave corrupted data if you forget to configure DELETE CASCADE for your model.

inline_models = None

Inline related-model editing for models with parent-child relations.

Accepts enumerable with one of the following possible values:

  1. Child model class:

    class MyModelView(ModelView):
        inline_models = (Post,)
  2. Child model class and additional options:

    class MyModelView(ModelView):
        inline_models = [(Post, dict(form_columns=['title']))]
  3. Django-like InlineFormAdmin class instance:

    from flask_admin.model.form import InlineFormAdmin
    class MyInlineModelForm(InlineFormAdmin):
        form_columns = ('title', 'date')
    class MyModelView(ModelView):
        inline_models = (MyInlineModelForm(MyInlineModel),)

You can customize the generated field name by:

  1. Using the form_name property as a key to the options dictionary:

    class MyModelView(ModelView):
        inline_models = ((Post, dict(form_label='Hello')))
  2. Using forward relation name and column_labels property:

    class Model1(Base):
    class Model2(Base):
        # ...
        model1 = relation(Model1, backref='models')
    class MyModel1View(Base):
        inline_models = (Model2,)
        column_labels = {'models': 'Hello'}
form_choices = None

Map choices to form fields


class MyModelView(BaseModelView):
    form_choices = {'my_form_field': [
        ('db_value', 'display_value'),
form_optional_types = (<class 'sqlalchemy.sql.sqltypes.Boolean'>,)

List of field types that should be optional if column is not nullable.


class MyModelView(BaseModelView):
    form_optional_types = (Boolean, Unicode)

Instantiate model action form and return it.

Override to implement custom behavior.

action_view(*args, **kwargs)

Mass-model action view.

after_model_change(form, model, is_created)

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.

  • 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

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
ajax_update(*args, **kwargs)

Edits a single column of a record in list view.


Controls if list view should display all relations, not only many-to-one.


Create Flask blueprint.


Instantiate model creation form and return it.

Override to implement custom behavior.


Create model from form.

Parameters:form – Form instance
create_view(*args, **kwargs)

Create model view


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.

Parameters:model – Model to delete
delete_view(*args, **kwargs)

Delete model view. Only POST method is allowed.

details_view(*args, **kwargs)

Details model view


Instantiate model editing form and return it.

Override to implement custom behavior.

edit_view(*args, **kwargs)

Edit model view


alias of flask_admin.form.BaseForm


Create form class for a model action.

Override to implement customized behavior.


Return a list and a dictionary of allowed actions.


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.

Overridden to handle special columns like InstrumentedAttribute.

  • 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.

Return a the count query for the model type

A query(self.model).count() approach produces an excessive subquery, so query(func.count('*')) should be used instead.

See commit #45a2723 for details.


Create form class for model creation view.

Override to implement customized behavior.


Create form class for model delete view.

Override to implement customized behavior.

get_detail_value(context, model, name)

Returns the value to be displayed in the detail view

  • contextjinja2.runtime.Context
  • model – Model instance
  • name – Field name

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.


Create form class for model editing view.

Override to implement customized behavior.


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.

Returns:The exported csv file name.
get_export_value(model, name)

Returns the value to be displayed in export. Allows export to use different (non HTML) formatters.

  • model – Model instance
  • name – Field name
get_filter_arg(index, flt)

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.

  • index – Filter index in _filters array
  • flt – Filter instance

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.

get_list(page, sort_column, sort_desc, search, filters, execute=True, page_size=None)[source]

Return records from the database.

  • page – Page number
  • sort_column – Sort column name
  • sort_desc – Descending or ascending sort
  • search – Search query
  • execute – Execute query immediately? Default is True
  • filters – List of filter tuples
  • 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.

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 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)

Return list of row action objects, each is instance of BaseListRowAction

get_list_value(context, model, name)

Returns the value to be displayed in the list view

  • contextjinja2.runtime.Context
  • model – Model instance
  • name – Field name

Return a single model by its id.


def get_one(self, id):
    query = self.get_query()
    return query.filter(self.model.id == id).one()

Also see get_query for how to filter the list view.

Parameters:id – Model id

Return the primary key value from a model object. If there are multiple primary keys, they’re encoded into string representation.


Return a query for the model type.

This method can be used to set a “persistent filter” on an index_view.


class MyView(ModelView):
    def get_query(self):
        return super(MyView, self).get_query().filter(User.username == current_user.username)

If you override this method, don’t forget to also override get_count_query, for displaying the correct item count in the list view, and get_one, which is used when retrieving records for the edit view.

get_save_return_url(model, is_created=False)

Return url where user is redirected after successful form save.

  • 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)

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.

get_url(endpoint, **kwargs)

Generate URL for the endpoint. If you want to customize URL generation logic (persist some query string argument, for example), this is right place to do it.

  • endpoint – Flask endpoint name
  • kwargs – Arguments for url_for

Handle action request.

Parameters:return_view – Name of the view to return to after the request. If not provided, will return user to the return url in the form or the list view.

Postprocess (add joins, etc) for a filter.

Parameters:filter – Filter object to postprocess
ignore_hidden = True

Ignore field that starts with “_”


class MyModelView(BaseModelView):
    ignore_hidden = False
inaccessible_callback(name, **kwargs)

Handle the response to inaccessible views.

By default, it throw HTTP 403 error. Override this method to customize the behaviour.

index_view(*args, **kwargs)

List view


Initialize list of actions for the current administrative view.

Initialize search. Returns True if search is supported for this view.

For SQLAlchemy, this will initialize internal fields: list of column objects used for filtering, etc.


Override this method to add permission checks.

Flask-Admin does not make any assumptions about the authentication system used in your application, so it is up to you to implement it.

By default, it will allow access for everyone.


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 editable.

Parameters:name – Column name.

Verify if column is sortable.

Not case-sensitive.

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.

Override this method if you want dynamically hide or show administrative views from Flask-Admin menu structure

By default, item is visible in menu.

Please note that item should be both visible and accessible to be displayed in menu.


Instantiate model editing form for list view and return it.

Override to implement custom behavior.

on_form_prefill(form, id)

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.

  • form – Form instance
  • id – id of the object that is going to be edited
on_model_change(form, model, is_created)

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.

  • 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

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.

render(template, **kwargs)

Render template

  • template – Template path to render
  • kwargs – Template arguments

Return a list of joined tables by going through the displayed columns.


Return list of enabled filters


Create form from the model.


Contribute inline models to the form

Parameters:form_class – Form class

Return a list of columns from the model.

scaffold_list_form(widget=None, validators=None)[source]

Create form for the index_view using only the columns from self.column_editable_list.

  • widget – WTForms widget class. Defaults to XEditableWidget.
  • validatorsform_args dict with only validators {‘name’: {‘validators’: [required()]}}

Return the primary key name(s) from a model If model has single primary key, will return a string and tuple otherwise


Return a dictionary of sortable columns. Key is column name, value is sort column/field.


Return search placeholder.

For example, if set column_labels and column_searchable_list:

class MyModelView(BaseModelView):
column_labels = dict(name=’Name’, last_name=’Last Name’) column_searchable_list = (‘name’, ‘last_name’)

placeholder is: “Search: Name, Last Name”

update_model(form, model)[source]

Update model from form.

  • form – Form instance
  • model – Model instance

Validate the form on submit.

Parameters:form – Form to validate