flask_admin.contrib.sqla

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.

column_searchable_list: T_COLUMN_LIST | None

Collection of the searchable columns.

Example:

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

or:

from flask_admin.contrib.sqla.filters import BooleanEqualFilter

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

or:

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")
        else:
            return query.filter(self.column != "Brown")

    def operation(self):
        return 'is Brown'

class MyModelView(BaseModelView):
    column_filters = [
        FilterLastNameBrown(
            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):
    pass


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):
        pass
    
    class Model2(Base):
        # ...
        model1 = relation(Model1, backref='models')
    
    class MyModel1View(Base):
        inline_models = (Model2,)
        column_labels = {'models': 'Hello'}
    

By default used ManyToMany relationship for inline models. You may configure inline model for OneToOne relationship. To achieve this, you need to install special inline_converter for your model:

from flask_admin.contrib.sqla.form import                 InlineOneToOneModelConverter

class MyInlineModelForm(InlineFormAdmin):
    form_columns = ('title', 'date')
    inline_converter = InlineOneToOneModelConverter

class MyModelView(ModelView):
    inline_models = (MyInlineModelForm(MyInlineModel),)
form_choices: Dict[str, List[Tuple[str, str]]] | None = None

Map choices to form fields

Example:

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.

Example:

class MyModelView(BaseModelView):
    form_optional_types = (Boolean, Unicode)
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’]

action_form(obj=None)

Instantiate model action form and return it.

Override to implement custom behavior.

action_view()

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.

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)

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

Edits a single column of a record in list view.

build_new_instance()[source]

Build new instance of a model. Useful to override the Flask-Admin behavior when the model has a custom __init__ method.

can_create = True

Is model creation allowed

can_delete = True

Is model deletion allowed

can_edit = True

Is model editing allowed

can_export = False

Is model list export allowed

can_set_page_size = False

Allows to select page size via dropdown list

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_choices = None

Map choices to columns in list view

Example:

class MyModelView(BaseModelView):
    column_choices = {
        'my_column': [
            ('db_value', 'display_value'),
        ]
    }
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)

If you want to sort by more than one column, you can pass a list of tuples:

class MyModelView(BaseModelView):
    column_default_sort = [('name', True), ('last_name', True)]
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_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_display_all_relations

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

column_display_pk

Controls if the primary key should be displayed in the list view.

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_exclude_list: T_COLUMN_LIST | None

Collection of excluded list column names.

For example:

class MyModelView(BaseModelView):
    column_exclude_list = ('last_name', 'email')
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

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_formatters_detail = None

Dictionary of list view column formatters to be used for the detail view.

Defaults to column_formatters when set to None.

Functions the same way as column_formatters except that macros are not supported.

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_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_list: T_COLUMN_LIST | None

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_sortable_list: T_COLUMN_LIST | None

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

You can also specify multiple fields to be used while sorting:

class MyModelView(BaseModelView):
    column_sortable_list = (
        'name', ('user', ('user.first_name', 'user.last_name')))

When using SQLAlchemy models, model attributes can be used instead of strings:

class MyModelView(BaseModelView):
    column_sortable_list = ('name', ('user', User.username))
column_type_formatters: T_FORMATTERS | None = {<class 'NoneType'>: <function empty_formatter>, <class 'bool'>: <function bool_formatter>, <class 'list'>: <function list_formatter>, <class 'dict'>: <function dict_formatter>, <enum 'Enum'>: <function enum_formatter>, <class 'sqlalchemy.orm.collections.InstrumentedList'>: <function list_formatter>, <class 'sqlalchemy.ext.associationproxy._AssociationList'>: <function list_formatter>, <class 'sqlalchemy_utils.types.choice.Choice'>: <function choice_formatter>, <class 'arrow.arrow.Arrow'>: <function arrow_formatter>}

Dictionary of value type formatters to be used in the list view.

By default, three types are formatted:

  1. None will be displayed as an empty string

  2. bool will be displayed as a checkmark if it is True

  3. 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_type_formatters_detail = None

Dictionary of value type formatters to be used in the detail view.

By default, two types are formatted:

  1. None will be displayed as an empty string

  2. list will be joined using ‘, ‘

Functions the same way as column_type_formatters.

column_type_formatters_export = None

Dictionary of value type formatters to be used in the export.

By default, two types are formatted:

  1. None will be displayed as an empty string

  2. list will be joined using ‘, ‘

Functions the same way as column_type_formatters.

create_blueprint(admin)

Create Flask blueprint.

create_form(obj=None)

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

Parameters:

form – Form instance

create_template = 'admin/model/create.html'

Default create template

create_view()

Create model view

delete_form()

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.

Parameters:

model – Model to delete

delete_view()

Delete model view. Only POST method is allowed.

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

details_view()

Details model view

edit_form(obj=None)

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

edit_template = 'admin/model/edit.html'

Default edit template

edit_view()

Edit model view

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://tablib.readthedocs.io/en/stable/formats.html for supported types.

form: Type[Form] | None = 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_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'),
            'placeholder': 'Please select',
            'page_size': 10,
            'minimum_input_length': 0,
        }
    }

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_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_base_class

alias of BaseForm

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

form_excluded_columns

Collection of excluded form field names.

For example:

class MyModelView(BaseModelView):
    form_excluded_columns = ('last_name', 'email')
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_overrides = None

Dictionary of form column overrides.

Example:

class MyModelView(BaseModelView):
    form_overrides = dict(name=wtf.FileField)
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')
    ]
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
)
get_action_form()

Create form class for a model action.

Override to implement customized behavior.

get_actions_list()

Return a list and a dictionary of allowed actions.

get_column_name(field)

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.

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.

get_count_query()[source]

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.

get_create_form()

Create form class for model creation view.

Override to implement customized behavior.

get_delete_form()

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

Parameters:
  • contextjinja2.runtime.Context

  • model – Model instance

  • name – Field name

get_details_columns()

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

Create form class for model editing view.

Override to implement customized behavior.

get_export_columns()

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_name(export_type='csv')
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.

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

Parameters:
  • index – Filter index in _filters array

  • flt – Filter instance

get_filters()

Return a list of filter objects.

If your model backend implementation does not support filters, override this method and return None.

get_form()

Get form class.

If self.form is set, will return it and will call self.scaffold_form otherwise.

Override to implement customized behavior.

get_invalid_value_msg(value, filter)

Returns message, which should be printed in case of failed validation. :param value: Invalid value :param filter: Filter :return: string

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

Return records from the database.

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

get_list_columns()

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

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

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

Parameters:
  • contextjinja2.runtime.Context

  • model – Model instance

  • name – Field name

get_one(id)[source]

Return a single model by its id.

Example:

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

get_pk_value(model)[source]

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

get_query()[source]

Return a query for the model type.

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

Example:

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.

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.

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.

Parameters:
  • endpoint – Flask endpoint name

  • kwargs – Arguments for url_for

handle_action(return_view=None)

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.

handle_filter(filter)[source]

Postprocess (add joins, etc) for a filter.

Parameters:

filter – Filter object to postprocess

ignore_hidden = True

Ignore field that starts with “_”

Example:

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

List view

init_actions()

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.

is_accessible()

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.

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_editable(name)

Verify if column is editable.

Parameters:

name – Column name.

is_sortable(name)

Verify if column is sortable.

Not case-sensitive.

Parameters:

name – Column name.

is_valid_filter(filter)

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.

is_visible()

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.

list_form(obj=None)

Instantiate model editing form for list view and return it.

Override to implement custom behavior.

list_template = 'admin/model/list.html'

Default list view template

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)

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)

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)

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.

page_size = 20

Default page size for pagination.

page_size_options: tuple = (20, 50, 100)

Sets the page size options available, if can_set_page_size is True

render(template, **kwargs)

Render template

Parameters:
  • template – Template path to render

  • kwargs – Template arguments

scaffold_auto_joins()[source]

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

scaffold_filters(name)[source]

Return list of enabled filters

scaffold_form()[source]

Create form from the model.

scaffold_inline_form_models(form_class)[source]

Contribute inline models to the form

Parameters:

form_class – Form class

scaffold_list_columns()[source]

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.

Parameters:
  • widget – WTForms widget class. Defaults to XEditableWidget.

  • validatorsform_args dict with only validators {‘name’: {‘validators’: [required()]}}

scaffold_pk()[source]

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

scaffold_sortable_columns()[source]

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

search_placeholder()[source]

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: “Name, Last Name”

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.

update_model(form, model)[source]

Update model from form.

Parameters:
  • form – Form instance

  • model – Model instance

validate_form(form)

Validate the form on submit.

Parameters:

form – Form to validate