Skip to content

ModelView

sqladmin.models.ModelView

Bases: BaseView

Base class for defining admnistrative behaviour for the model.

Usage
from sqladmin import ModelView

from mymodels import User # SQLAlchemy model

class UserAdmin(ModelView, model=User):
    can_create = True

name_plural: str = '' class-attribute

Plural name of ModelView. Default value is Model class name + s.

column_labels: Dict[MODEL_ATTR, str] = {} class-attribute

A mapping of column labels, used to map column names to new names. Dictionary keys can be string names or SQLAlchemy columns with string values.

Example
class UserAdmin(ModelView, model=User):
    column_labels = {User.mail: "Email"}

can_create: bool = True class-attribute

Permission for creating new Models. Default value is set to True.

can_edit: bool = True class-attribute

Permission for editing Models. Default value is set to True.

can_delete: bool = True class-attribute

Permission for deleting Models. Default value is set to True.

can_view_details: bool = True class-attribute

Permission for viewing full details of Models. Default value is set to True.

column_list: Union[str, Sequence[MODEL_ATTR]] = [] class-attribute

List of columns to display in List page. Columns can either be string names or SQLAlchemy columns.

Note

By default only Model primary key is displayed.

Example
class UserAdmin(ModelView, model=User):
    column_list = [User.id, User.name]

column_exclude_list: Sequence[MODEL_ATTR] = [] class-attribute

List of columns to exclude in List page. Columns can either be string names or SQLAlchemy columns.

Example
class UserAdmin(ModelView, model=User):
    column_exclude_list = [User.id, User.name]

column_formatters: Dict[MODEL_ATTR, Callable[[type, Column], Any]] = {} class-attribute

Dictionary of list view column formatters. Columns can either be string names or SQLAlchemy columns.

Example
class UserAdmin(ModelView, model=User):
    column_formatters = {User.name: lambda m, a: m.name[:10]}

The format function has the prototype:

Formatter
def formatter(model, attribute):
    # `model` is model instance
    # `attribute` is a Union[ColumnProperty, RelationshipProperty]
    pass

column_formatters_detail: Dict[MODEL_ATTR, Callable[[type, Column], Any]] = {} class-attribute

Dictionary of details view column formatters. Columns can either be string names or SQLAlchemy columns.

Example
class UserAdmin(ModelView, model=User):
    column_formatters_detail = {User.name: lambda m, a: m.name[:10]}

The format function has the prototype:

Formatter
def formatter(model, attribute):
    # `model` is model instance
    # `attribute` is a Union[ColumnProperty, RelationshipProperty]
    pass

page_size: int = 10 class-attribute

Default number of items to display in List page pagination. Default value is set to 10.

Example
class UserAdmin(ModelView, model=User):
    page_size = 25

page_size_options: Sequence[int] = [10, 25, 50, 100] class-attribute

Pagination choices displayed in List page. Default value is set to [10, 25, 50, 100].

Example
class UserAdmin(ModelView, model=User):
    page_size_options = [50, 100]

column_details_list: Union[str, Sequence[MODEL_ATTR]] = [] class-attribute

List of columns to display in Detail page. Columns can either be string names or SQLAlchemy columns.

Note

By default all columns of Model are displayed.

Example
class UserAdmin(ModelView, model=User):
    column_details_list = [User.id, User.name, User.mail]

column_details_exclude_list: Sequence[MODEL_ATTR] = [] class-attribute

List of columns to exclude from displaying in Detail page. Columns can either be string names or SQLAlchemy columns.

Example
class UserAdmin(ModelView, model=User):
    column_details_exclude_list = [User.mail]

list_template: str = 'list.html' class-attribute

List view template. Default is list.html.

create_template: str = 'create.html' class-attribute

Create view template. Default is create.html.

details_template: str = 'details.html' class-attribute

Details view template. Default is details.html.

edit_template: str = 'edit.html' class-attribute

Edit view template. Default is edit.html.

column_searchable_list: Sequence[MODEL_ATTR] = [] class-attribute

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 UserAdmin(ModelView, model=User):
    column_searchable_list = [User.name]

column_sortable_list: Sequence[MODEL_ATTR] = [] class-attribute

Collection of the sortable columns for the list view.

Example
class UserAdmin(ModelView, model=User):
    column_sortable_list = [User.name]

column_default_sort: Union[MODEL_ATTR, Tuple[MODEL_ATTR, bool], list] = [] class-attribute

Default sort column if no sorting is applied.

Example
class UserAdmin(ModelView, model=User):
    column_default_sort = "email"

You can use tuple to control ascending descending order. In following example, items will be sorted in descending order:

Example
class UserAdmin(ModelView, model=User):
    column_default_sort = ("email", True)

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

Example
class UserAdmin(ModelView, model=User):
    column_default_sort = [("email", True), ("name", False)]

can_export: bool = True class-attribute

Permission for exporting lists of Models. Default value is set to True.

column_export_list: List[MODEL_ATTR] = [] class-attribute

List of columns to include when exporting. Columns can either be string names or SQLAlchemy columns.

Example
class UserAdmin(ModelView, model=User):
    column_export_list = [User.id, User.name]

column_export_exclude_list: List[MODEL_ATTR] = [] class-attribute

List of columns to exclude when exporting. Columns can either be string names or SQLAlchemy columns.

Example
class UserAdmin(ModelView, model=User):
    column_export_exclude_list = [User.id, User.name]

export_types: List[str] = ['csv'] class-attribute

A list of available export filetypes. Currently only csv is supported.

export_max_rows: int = 0 class-attribute

Maximum number of rows allowed for export. Unlimited by default.

form: Optional[Type[Form]] = None class-attribute

Form class. Override if you want to use custom form for your model. Will completely disable form scaffolding functionality.

Example
class MyForm(Form):
    name = StringField('Name')

class MyModelView(ModelView, model=User):
    form = MyForm

form_args: Dict[str, Dict[str, Any]] = {} class-attribute

Dictionary of form field arguments. Refer to WTForms documentation for list of possible options.

Example
from wtforms.validators import DataRequired

class MyModelView(ModelView, model=User):
    form_args = dict(
        name=dict(label="User Name", validators=[DataRequired()])
    )

form_columns: Sequence[MODEL_ATTR] = [] class-attribute

List of columns to include in the form. Columns can either be string names or SQLAlchemy columns.

Note

By default all columns of Model are included in the form.

Example
class UserAdmin(ModelView, model=User):
    form_columns = [User.name, User.mail]

form_excluded_columns: Sequence[MODEL_ATTR] = [] class-attribute

List of columns to exclude from the form. Columns can either be string names or SQLAlchemy columns.

Example
class UserAdmin(ModelView, model=User):
    form_excluded_columns = [User.id]

form_overrides: Dict[str, Type[Field]] = {} class-attribute

Dictionary of form column overrides.

Example
class UserAdmin(ModelView, model=User):
    form_overrides = dict(name=wtf.FileField)

form_widget_args: Dict[str, Dict[str, Any]] = {} class-attribute

Dictionary of form widget rendering arguments. Use this to customize how widget is rendered without using custom template.

Example
class UserAdmin(ModelView, model=User):
    form_widget_args = {
        "email": {
            "readonly": True,
        },
    }

form_include_pk: bool = False class-attribute

Control if form should include primary key columns or not.

Example
class UserAdmin(ModelView, model=User):
    form_include_pk = True

form_ajax_refs: Dict[str, dict] = {} class-attribute

Use Ajax for foreign key model loading. Should contain dictionary, where key is field name and value is a dictionary which configures Ajax lookups.

Example
class UserAdmin(ModelAdmin, model=User):
    form_ajax_refs = {
        'address': {
            'fields': ('street', 'zip_code'),
            'order_by': ('id',),
        }
    }

form_converter: Type[ModelConverterBase] = ModelConverter class-attribute

Custom form converter class. Useful if you want to add custom form conversion in addition to the defaults.

Example
class PhoneNumberConverter(ModelConverter):
    pass

class UserAdmin(ModelAdmin, model=User):
    form_converter = PhoneNumberConverter

column_type_formatters: Dict[Type, Callable] = BASE_FORMATTERS class-attribute

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

By default, two types are formatted:

- None will be displayed as an empty string
- bool will be displayed as a checkmark if it is True otherwise as an X.

If you don’t like the default behavior and don’t want any type formatters applied, just override this property with an empty dictionary:

Example
class UserAdmin(ModelView, model=User):
    column_type_formatters = dict()

save_as: bool = False class-attribute

Set save_as to enable a “save as new” feature on admin change forms.

Normally, objects have three save options: `Save, Save and continue editing and Save and add another.

If save_as is True, Save and add another will be replaced by a Save as new button that creates a new object (with a new ID) rather than updating the existing object.

By default, save_as is set to False.

save_as_continue: bool = True class-attribute

When save_as=True, the default redirect after saving the new object is to the edit view for that object. If you set save_as_continue=False, the redirect will be to the list view.

By default, save_as_continue is set to True.

search_placeholder()

Return search placeholder text.

Example
class UserAdmin(ModelView, model=User):
    column_labels = dict(name="Name", email="Email")
    column_searchable_list = [User.name, User.email]

# placeholder is: "Name, Email"

list_query(request)

The SQLAlchemy select expression used for the list page which can be customized. By default it will select all objects without any filters.

count_query(request)

The SQLAlchemy select expression used for the count query which can be customized. By default it will select all objects without any filters.

search_query(stmt, term)

Specify the search query given the SQLAlchemy statement and term to search for. It can be used for doing more complex queries like JSON objects. For example:

return stmt.filter(MyModel.name == term)

sort_query(stmt, request)

A method that is called every time the fields are sorted and that can be customized. By default, sorting takes place by default fields.

The 'sortBy' and 'sort' query parameters are available in this request context.

on_model_change(data, model, is_created, request) async

Perform some actions before a model is created or updated. By default does nothing.

after_model_change(data, model, is_created, request) async

Perform some actions after a model was created or updated and committed to the database. By default does nothing.

on_model_delete(model, request) async

Perform some actions before a model is deleted. By default does nothing.

after_model_delete(model, request) async

Perform some actions after a model is deleted. By default do nothing.