flask_admin.contrib.mongoengine

MongoEngine model backend implementation.

class ModelView(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]

MongoEngine model scaffolding.

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

Collection of the column filters.

Can contain either field names or instances of flask_admin.contrib.mongoengine.filters.BaseMongoEngineFilter 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.mongoengine.filters import BooleanEqualFilter

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

or:

from flask_admin.contrib.mongoengine.filters import BaseMongoEngineFilter

class FilterLastNameBrown(BaseMongoEngineFilter):
    def apply(self, query, value):
        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(
            column=User.last_name, name='Last Name',
            options=(('1', 'Yes'), ('0', 'No'))
        )
    ]
column_type_formatters = {<type 'NoneType'>: <function empty_formatter>, <type 'bool'>: <function bool_formatter>, <type 'dict'>: <function dict_formatter>, <class 'mongoengine.fields.GridFSProxy'>: <function grid_formatter>, <class 'mongoengine.base.datastructures.BaseList'>: <function list_formatter>, <type 'list'>: <function list_formatter>, <enum 'Enum'>: <function enum_formatter>, <class 'mongoengine.fields.ImageGridFsProxy'>: <function grid_image_formatter>}

Customized type formatters for MongoEngine backend

filter_converter = <flask_admin.contrib.mongoengine.filters.FilterConverter object>

Field to filter converter.

Override this attribute to use a non-default converter.

model_form_converter = <class 'flask_admin.contrib.mongoengine.form.CustomModelConverter'>

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

Custom class should be derived from the flask_admin.contrib.mongoengine.form.CustomModelConverter.

For example:

class MyModelConverter(AdminModelConverter):
    pass


class MyAdminView(ModelView):
    model_form_converter = MyModelConverter
allowed_search_types = (<class 'mongoengine.fields.StringField'>, <class 'mongoengine.fields.URLField'>, <class 'mongoengine.fields.EmailField'>)

List of allowed search field types.

form_subdocuments = None

Subdocument configuration options.

This field accepts dictionary, where key is field name and value is either dictionary or instance of the flask_admin.contrib.mongoengine.EmbeddedForm.

Consider following example:

class Comment(db.EmbeddedDocument):
    name = db.StringField(max_length=20, required=True)
    value = db.StringField(max_length=20)

class Post(db.Document):
    text = db.StringField(max_length=30)
    data = db.EmbeddedDocumentField(Comment)

class MyAdmin(ModelView):
    form_subdocuments = {
        'data': {
            'form_columns': ('name',)
        }
    }

In this example, Post model has child Comment subdocument. When generating form for Comment embedded document, Flask-Admin will only create name field.

It is also possible to use class-based embedded document configuration:

class CommentEmbed(EmbeddedForm):
    form_columns = ('name',)

class MyAdmin(ModelView):
    form_subdocuments = {
        'data': CommentEmbed()
    }

Arbitrary depth nesting is supported:

class SomeEmbed(EmbeddedForm):
    form_excluded_columns = ('test',)

class CommentEmbed(EmbeddedForm):
    form_columns = ('name',)
    form_subdocuments = {
        'inner': SomeEmbed()
    }

class MyAdmin(ModelView):
    form_subdocuments = {
        'data': CommentEmbed()
    }

There’s also support for forms embedded into ListField. All you have to do is to create nested rule with None as a name. Even though it is slightly confusing, but that’s how Flask-MongoEngine creates form fields embedded into ListField:

class Comment(db.EmbeddedDocument):
    name = db.StringField(max_length=20, required=True)
    value = db.StringField(max_length=20)

class Post(db.Document):
    text = db.StringField(max_length=30)
    data = db.ListField(db.EmbeddedDocumentField(Comment))

class MyAdmin(ModelView):
    form_subdocuments = {
        'data': {
            'form_subdocuments': {
                None: {
                    'form_columns': ('name',)
                }
            }

        }
    }
action_form(obj=None)

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.

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

Edits a single column of a record in list view.

allowed_search_types = (<class 'mongoengine.fields.StringField'>, <class 'mongoengine.fields.URLField'>, <class 'mongoengine.fields.EmailField'>)

List of allowed search field types.

create_blueprint(admin)

Create Flask blueprint.

create_form(obj=None)

Instantiate model creation form and return it.

Override to implement custom behavior.

create_model(form)[source]

Create model helper

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

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 helper

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

Delete model view. Only POST method is allowed.

details_view(*args, **kwargs)

Details model view

edit_form(obj=None)

Instantiate model editing form and return it.

Override to implement custom behavior.

edit_view(*args, **kwargs)

Edit model view

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)

Returns a list of tuples with the model field name and formatted field name.

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 if only_columns is not set.
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_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_list(page, sort_column, sort_desc, search, filters, execute=True, page_size=None)[source]

Get list of objects from MongoEngine

Parameters:
  • page – Page number
  • sort_column – Sort column
  • sort_desc – Sort descending
  • search – Search criteria
  • filters – List of applied filters
  • execute – Run query immediately or not
  • 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 instance by its ID

Parameters:id – Model ID
get_pk_value(model)[source]

Return the primary key value from the model instance

Parameters:model – Model instance
get_query()[source]

Returns the QuerySet for this view. By default, it returns all the objects for the current model.

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

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)

Postprocess (add joins, etc) for a filter.

Parameters:filter – Filter object to postprocess
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

init_actions()

Initialize list of actions for the current administrative view.

Init search

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_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)[source]

Validate if the provided filter is a valid MongoEngine filter

Parameters:filter – Filter object
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.

model_form_converter

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

Custom class should be derived from the flask_admin.contrib.mongoengine.form.CustomModelConverter.

For example:

class MyModelConverter(AdminModelConverter):
    pass


class MyAdminView(ModelView):
    model_form_converter = MyModelConverter

alias of CustomModelConverter

object_id_converter

Mongodb _id value conversion function. Default is bson.ObjectId. Use this if you are using String, Binary and etc.

For example:

class MyModelView(BaseModelView):
    object_id_converter = int

or:

class MyModelView(BaseModelView):
    object_id_converter = str

alias of ObjectId

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.

render(template, **kwargs)

Render template

Parameters:
  • template – Template path to render
  • kwargs – Template arguments
scaffold_filters(name)[source]

Return filter object(s) for the field

Parameters:name – Either field name or field instance
scaffold_form()[source]

Create form from the model.

scaffold_list_columns()[source]

Scaffold list columns

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_sortable_columns()[source]

Return a dictionary of sortable columns (name, field)

update_model(form, model)[source]

Update model helper

Parameters:
  • form – Form instance
  • model – Model instance to update
validate_form(form)

Validate the form on submit.

Parameters:form – Form to validate