API Reference

Package exports

AdminSite, ModelAdmin, FieldWidget, site, display, and action are re-exported from submodules for convenience; their API is documented in the sections below.

FastAPI Mongo Admin — Django-inspired admin for MongoDB.

fastapi_mongo_admin.mount_admin_app(app, get_database, *, admin_site=None, router_prefix='/admin', mode='async', auth_dependency=None, permission_dependency=None, api_write_methods=False)[source]

Mount the admin UI, JSON API, and static files on a FastAPI application.

Parameters:
  • app (FastAPI) – FastAPI application to extend.

  • get_database (Callable[[...], AsyncIOMotorDatabase | Database | Awaitable[AsyncIOMotorDatabase]]) – Callable returning a Motor database, PyMongo database, or awaitable that resolves to one.

  • admin_site (AdminSite | None) – Admin site registry. Defaults to the global site singleton.

  • router_prefix (str) – URL prefix for admin routes (default /admin).

  • mode (Literal['async', 'sync']) – MongoDB access mode — async (Motor) or sync (PyMongo).

  • auth_dependency (Callable[[...], Any] | None) – Optional FastAPI dependency injected on admin routes.

  • permission_dependency (Callable[[...], Any] | None) – Optional dependency checked before the admin index.

  • api_write_methods (bool) – When True, register POST, PUT, PATCH, and DELETE JSON API routes and include them in OpenAPI (/docs). When False (default), only GET list/detail routes are registered and documented.

Returns:

None. Mutates app by including the admin router and static mount.

Return type:

None

fastapi_mongo_admin.create_admin_router(admin_site, get_database, *, prefix='/admin', mode='async', auth_dependency=None, permission_dependency=None, static_url='/admin/static', api_write_methods=False)[source]

Create the admin UI and JSON API router.

Parameters:
  • admin_site (AdminSite) – Registered models and global admin configuration.

  • get_database (Callable[[...], Any]) – Callable returning the MongoDB database (sync or async).

  • prefix (str) – URL prefix for all admin routes (default /admin).

  • mode (Literal['async', 'sync']) – MongoDB access mode — async or sync.

  • auth_dependency (Callable[[...], Any] | None) – Optional FastAPI dependency for authentication.

  • permission_dependency (Callable[[...], Any] | None) – Optional dependency checked on the admin index.

  • static_url (str) – URL path prefix for packaged admin static files.

  • api_write_methods (bool) – When True, expose POST, PUT, PATCH, and DELETE JSON API endpoints in the router and OpenAPI schema. When False (default), only GET endpoints are registered.

Returns:

APIRouter with HTML admin views and /api JSON routes included.

Return type:

APIRouter

fastapi_mongo_admin.serialize_document(doc)[source]

Convert a MongoDB document to a JSON-serializable dict.

Parameters:

doc (dict[str, Any]) – Raw MongoDB document.

Returns:

Serialized document with id alias for _id.

Return type:

dict[str, Any]

Admin registry

AdminSite registry.

class fastapi_mongo_admin.admin.site.AdminSite(name='admin', template_dirs=None)[source]

Registry for models and custom admin views.

Parameters:
  • name (str)

  • template_dirs (list[Path] | None)

site_header: str = 'FastAPI Mongo Admin'
site_title: str = 'Admin'
index_title: str = 'Site administration'
register(model_or_iterable, admin_class=None, **options)[source]

Register one or more Pydantic models with optional admin class.

Parameters:
  • model_or_iterable (Type[BaseModel] | Iterable[Type[BaseModel]]) – A single model class or iterable of models.

  • admin_class (type[ModelAdmin] | None) – Optional ModelAdmin subclass; defaults to ModelAdmin.

  • **options (Any) – ModelAdmin options applied before registration (e.g. collection_name, list_display).

Returns:

None.

Raises:

ValueError – When collection_name is missing or already registered.

Return type:

None

register_view(name, path, endpoint, *, permission=None)[source]

Register a custom admin page.

Parameters:
  • name (str) – View label for internal reference.

  • path (str) – URL path relative to the admin prefix (must start with /).

  • endpoint (Callable[[...], Any]) – FastAPI-compatible view callable.

  • permission (Callable[[Request, Any], bool] | None) – Optional permission check (request, user) -> bool.

Returns:

None.

Return type:

None

get_model_admin(collection_name)[source]

Return the ModelAdmin registered for a collection.

Parameters:

collection_name (str) – MongoDB collection name.

Returns:

ModelAdmin instance or None when not registered.

Return type:

ModelAdmin | None

get_registered_collections()[source]

Return registered collection names.

Returns:

List of collection name strings.

Return type:

list[str]

get_registered_models()[source]

Return a copy of the full model registry.

Returns:

Mapping of collection name to ModelAdmin instance.

Return type:

dict[str, ModelAdmin]

get_csrf_token(request)[source]

Return the CSRF token from the session when available.

Parameters:

request (Request) – Current HTTP request.

Returns:

CSRF token string, or empty string when sessions are disabled.

Return type:

str

ModelAdmin base class with Django-admin-style hooks.

class fastapi_mongo_admin.admin.model.ModelAdmin(model=None)[source]

Configuration and hooks for a registered Pydantic model.

Subclass to customize changelist columns, filters, forms, permissions, and document lifecycle behavior.

Parameters:

model (Type[BaseModel] | None)

collection_name: str | None = None
list_display: list[str] | None = None
list_editable: list[str] | None = None
list_filter: list[str | type[ListFilter]] | None = None
search_fields: list[str] | None = None
list_per_page: int = 25
list_max_show_all: int = 200
ordering: list[str] | None = None
date_hierarchy: str | None = None
fieldsets: list[tuple[str | None, dict[str, list[str]]]] | None = None
readonly_fields: list[str] | None = None
field_mapping: dict[str, str] | None = None
actions: list[str] | None = None
choices: dict[str, list[tuple[Any, str]]] | None = None
formfield_overrides: dict[str, FieldWidget | dict[str, Any]] | None = None
date_format: str | None = None
datetime_format: str | None = None
change_list_template: str = 'admin/change_list.html'
change_form_template: str = 'admin/change_form.html'
delete_confirmation_template: str = 'admin/delete_confirmation.html'
delete_selected_confirmation_template: str = 'admin/delete_selected_confirmation.html'
model: Type[BaseModel] | None = None
get_model_name()[source]

Return the human-readable model name.

Returns:

Model class name, or collection_name when no model is set.

Return type:

str

get_model_name_plural()[source]

Return the plural human-readable model name.

Returns:

Pluralized model label for result counts and bulk messages.

Return type:

str

get_list_display(request=None)[source]

Return changelist column field names.

Parameters:

request (Request | None) – Current HTTP request (unused by default).

Returns:

Column names from list_display, model fields, or ["_id"].

Return type:

list[str]

Return changelist columns that link to the change form.

Parameters:

request (Request | None) – Current HTTP request (unused by default).

Returns:

Clickable column names; defaults to the first list display column.

Return type:

list[str]

get_search_fields()[source]

Return searchable model field names.

Returns:

Field names from search_fields, or an empty list.

Return type:

list[str]

get_ordering()[source]

Return default changelist ordering.

Returns:

Ordering list; prefix fields with - for descending. Defaults to ["-_id"].

Return type:

list[str]

get_sortable_field(column_name)[source]

Return the database field used to sort a changelist column.

Parameters:

column_name (str) – list_display column or @display method name.

Returns:

Sortable model field name, or None when the column is not sortable.

Return type:

str | None

get_readonly_fields(request=None, obj=None)[source]

Return readonly form field names.

Parameters:
  • request (Request | None) – Current HTTP request.

  • obj (dict[str, Any] | None) – Existing document on change forms.

Returns:

Readonly field names from readonly_fields.

Return type:

list[str]

get_formfield_overrides(request=None, obj=None)[source]

Return per-field widget overrides for the change form.

Parameters:
  • request (Request | None) – Current HTTP request.

  • obj (dict[str, Any] | None) – Existing document on change forms.

Returns:

Mapping of field name to FieldWidget instances.

Return type:

dict[str, FieldWidget]

formfield_for_field(field, request=None, obj=None)[source]

Customize a single form field after defaults and overrides.

Parameters:
  • field (AdminField) – AdminField metadata to customize.

  • request (Request | None) – Current HTTP request.

  • obj (dict[str, Any] | None) – Existing document on change forms.

Returns:

Modified AdminField (default implementation returns unchanged).

Return type:

AdminField

get_fieldsets(request=None, obj=None)[source]

Return grouped fieldsets for the change form.

Parameters:
  • request (Request | None) – Current HTTP request.

  • obj (dict[str, Any] | None) – Existing document on change forms.

Returns:

List of (title, {"fields": [...]}) tuples.

Return type:

list[tuple[str | None, dict[str, list[str]]]]

get_list_filters(request=None, params=None)[source]

Instantiate sidebar list filters from configuration.

Parameters:
  • request (Request | None) – Current HTTP request.

  • params (dict[str, str] | None) – Active query parameters.

Returns:

Initialized ListFilter instances.

Return type:

list[ListFilter]

get_actions()[source]

Return enabled bulk actions for the changelist.

Returns:

List of (name, method, label) tuples. delete_selected is always included first.

Return type:

list[tuple[str, Any, str]]

get_queryset(request, base_query)[source]

Customize the base MongoDB query for changelist operations.

Parameters:
  • request (Request | None) – Current HTTP request.

  • base_query (dict[str, Any]) – Starting query dict (usually empty).

Returns:

Modified base query merged with filters and search.

Return type:

dict[str, Any]

async save_model(request, obj, form_data, is_new)[source]

Hook called before persisting a document.

Parameters:
  • request (Request | None) – Current HTTP request.

  • obj (dict[str, Any]) – Existing document dict (empty on create).

  • form_data (dict[str, Any]) – Validated form data to persist.

  • is_new (bool) – Whether this is a new document.

Returns:

Data dict to write to MongoDB.

Return type:

dict[str, Any]

async delete_model(request, obj)[source]

Hook called before deleting a document.

Parameters:
  • request (Request | None) – Current HTTP request.

  • obj (dict[str, Any]) – Document dict about to be deleted.

Returns:

None.

Return type:

None

has_view_permission(request, user=None, obj=None)[source]

Return whether the user can view the changelist and detail pages.

Parameters:
  • request (Request | None) – Current HTTP request.

  • user (Any) – Authenticated user from auth_dependency.

  • obj (dict[str, Any] | None) – Optional document for object-level checks.

Returns:

True by default.

Return type:

bool

has_add_permission(request, user=None)[source]

Return whether the user can add documents.

Parameters:
  • request (Request | None) – Current HTTP request.

  • user (Any) – Authenticated user from auth_dependency.

Returns:

True by default.

Return type:

bool

has_change_permission(request, user=None, obj=None)[source]

Return whether the user can change documents.

Parameters:
  • request (Request | None) – Current HTTP request.

  • user (Any) – Authenticated user from auth_dependency.

  • obj (dict[str, Any] | None) – Optional document for object-level checks.

Returns:

True by default.

Return type:

bool

has_delete_permission(request, user=None, obj=None)[source]

Return whether the user can delete documents.

Parameters:
  • request (Request | None) – Current HTTP request.

  • user (Any) – Authenticated user from auth_dependency.

  • obj (dict[str, Any] | None) – Optional document for object-level checks.

Returns:

True by default.

Return type:

bool

get_urls()[source]

Return extra (path, handler) pairs under the model URL prefix.

Returns:

List of relative path/handler pairs for custom model views.

Return type:

list[tuple[str, Any]]

get_date_format()[source]

Return the strftime-style format for date display.

Returns:

Custom format string, or None for the default 8 Apr 2026.

Return type:

str | None

get_datetime_format()[source]

Return the strftime-style format for datetime display.

Returns:

Custom format string, or None for the default 8 Apr 2026, 7:32pm.

Return type:

str | None

format_date_value(value)[source]

Format a date value for changelist and readonly display.

Parameters:

value (Any) – Raw date value.

Returns:

Formatted date string.

Return type:

str

format_datetime_value(value)[source]

Format a datetime value for changelist and readonly display.

Parameters:

value (Any) – Raw datetime value.

Returns:

Formatted datetime string.

Return type:

str

boolean_display_cell(field_name, obj, *, true_label, false_label)[source]

Return colored-label metadata for a boolean changelist cell.

Parameters:
  • field_name (str) – Model field name.

  • obj (dict[str, Any]) – Row document dict.

  • true_label (str) – Localized label for True.

  • false_label (str) – Localized label for False.

Returns:

Dict with boolean and label keys, or None when not boolean.

Return type:

dict[str, Any] | None

format_display_value(field_name, value)[source]

Apply date/datetime display formatting when applicable.

Parameters:
  • field_name (str) – Model field name.

  • value (Any) – Raw field value.

Returns:

Formatted value for display.

Return type:

Any

display_value(request, obj, field_name)[source]

Resolve a changelist cell value including @display methods.

Parameters:
  • request (Request | None) – Current HTTP request.

  • obj (dict[str, Any]) – Row document dict.

  • field_name (str) – Column field name.

Returns:

Display value for the cell.

Return type:

Any

object_repr(request, obj)[source]

Return a human-readable label for flash messages and confirmations.

Parameters:
  • request (Request | None) – Current HTTP request.

  • obj (dict[str, Any]) – Document dict.

Returns:

Best-effort human-readable object label.

Return type:

str

Decorators

Decorators for ModelAdmin display columns and actions.

fastapi_mongo_admin.admin.decorators.display(description=None, ordering=None)[source]

Mark a ModelAdmin method as a changelist display column.

Parameters:
  • description (str | None) – Column heading shown in the changelist.

  • ordering (str | None) – Model field name used when sorting by this column.

Returns:

Decorator that sets admin_display, short_description, and admin_order_field on the wrapped function.

Return type:

Callable[[F], F]

fastapi_mongo_admin.admin.decorators.action(description, permissions=None)[source]

Mark a ModelAdmin method as a bulk admin action.

Parameters:
  • description (str) – Action label shown in the changelist actions dropdown.

  • permissions (list[str] | None) – Optional list of required permission names.

Returns:

Decorator that sets admin_action, short_description, and allowed_permissions on the wrapped function.

Return type:

Callable[[F], F]

Actions

Admin action helpers.

async fastapi_mongo_admin.admin.actions.run_delete_selected(model_admin, request, repo, docs, doc_ids)[source]

Delete selected documents after calling delete_model hooks.

Parameters:
  • model_admin (Any) – ModelAdmin instance with lifecycle hooks.

  • request (Any) – Current HTTP request.

  • repo (Any) – Collection repository for bulk delete.

  • docs (list[dict[str, Any]]) – Selected document dicts.

  • doc_ids (list[str]) – Selected document id strings.

Returns:

Number of documents deleted from the database.

Return type:

int

fastapi_mongo_admin.admin.actions.get_model_actions(model_admin)[source]

Collect @action-decorated methods from a ModelAdmin instance.

Parameters:

model_admin (Any) – ModelAdmin instance to inspect.

Returns:

List of (name, method, short_description) tuples.

Return type:

list[tuple[str, Callable[[…], Any], str]]

List filters

Base list filter classes.

class fastapi_mongo_admin.admin.filters.base.ListFilter(request, params, model_admin, field_name)[source]

Base class for changelist sidebar filters.

Parameters:
title: str = ''
parameter_name: str = ''
lookups()[source]

Return filter choice values and labels.

Returns:

List of (value, label) tuples excluding the “All” option.

Return type:

list[tuple[str, str]]

queryset(value)[source]

Return a MongoDB filter fragment for the selected value.

Parameters:

value (str) – Selected filter value from the query string.

Returns:

MongoDB filter dict, or empty dict when no filter applies.

Return type:

dict[str, Any]

choices()[source]

Return sidebar choices including an “All” option.

Returns:

List of choice dicts with value, label, and selected keys.

Return type:

list[dict[str, str]]

db_field()[source]

Map the model field name to the database field name.

Returns:

Database field name after applying field_mapping.

Return type:

str

Choice list filter.

class fastapi_mongo_admin.admin.filters.choice.ChoiceListFilter(request, params, model_admin, field_name)[source]

Filter by discrete choice values.

Parameters:
title: str = ''
lookups()[source]

Return choices from ModelAdmin config or field metadata.

Returns:

List of (value, label) tuples.

Return type:

list[tuple[str, str]]

queryset(value)[source]

Return an exact-match filter for the selected choice.

Parameters:

value (str) – Selected choice value.

Returns:

MongoDB filter dict keyed by the database field.

Return type:

dict[str, Any]

Boolean list filter.

class fastapi_mongo_admin.admin.filters.boolean.BooleanFieldListFilter(request, params, model_admin, field_name)[source]

Filter boolean fields with Yes/No choices.

Parameters:
title: str = ''
lookups()[source]

Return Yes/No filter choices.

Returns:

List of (value, label) tuples.

Return type:

list[tuple[str, str]]

queryset(value)[source]

Return a boolean equality filter.

Parameters:

value (str) – Selected filter value (1/0 or truthy strings).

Returns:

MongoDB filter dict keyed by the database field.

Return type:

dict[str, Any]

Date list filter and date hierarchy.

class fastapi_mongo_admin.admin.filters.date.DateFieldListFilter(request, params, model_admin, field_name)[source]

Filter documents by common date ranges.

Parameters:
title: str = ''
lookups()[source]

Return preset date range choices.

Returns:

List of (value, label) tuples.

Return type:

list[tuple[str, str]]

queryset(value)[source]

Return a date range filter for the selected preset.

Parameters:

value (str) – Preset key (today, past_7_days, etc.).

Returns:

MongoDB range filter dict keyed by the database field.

Return type:

dict[str, Any]

fastapi_mongo_admin.admin.filters.date.build_date_hierarchy_query(field, year, month, day)[source]

Build a date hierarchy drill-down query.

Parameters:
  • field (str) – Database date/datetime field name.

  • year (str | None) – Selected year string.

  • month (str | None) – Selected month string.

  • day (str | None) – Selected day string.

Returns:

MongoDB range filter for the selected hierarchy level.

Return type:

dict[str, Any]

Related field list filter for ObjectId references.

class fastapi_mongo_admin.admin.filters.related.RelatedFieldListFilter(request, params, model_admin, field_name)[source]

Filter by related document ObjectId.

Parameters:
related_collection: str = ''
related_field: str = '_id'
display_field: str = 'name'
lookups()[source]

Return related-document lookup choices.

Returns:

Empty list by default; subclasses may populate dynamically.

Return type:

list[tuple[str, str]]

queryset(value)[source]

Return an ObjectId reference filter.

Parameters:

value (str) – Related document id string.

Returns:

MongoDB filter dict keyed by the database field.

Return type:

dict[str, Any]

Field widgets

Widget type constants and per-field override configuration.

fastapi_mongo_admin.admin.fields.widgets.is_primitive_list(annotation)[source]

Return whether an annotation is a list of primitive scalar values.

Parameters:

annotation (Any)

Return type:

bool

fastapi_mongo_admin.admin.fields.widgets.widget_for_type(field_type, *, has_choices=False, annotation=None)[source]

Map an inferred field type to an HTML widget name.

Parameters:
  • field_type (str) – Inferred admin field type.

  • has_choices (bool) – Whether the field has discrete choices.

  • annotation (Any) – Original field annotation for list element detection.

Returns:

Widget name string.

Return type:

str

fastapi_mongo_admin.admin.fields.widgets.step_for_type(field_type)[source]

Return the HTML step attribute for numeric field types.

Parameters:

field_type (str) – Inferred admin field type.

Returns:

Step string for numeric widgets, or None.

Return type:

str | None

class fastapi_mongo_admin.admin.fields.widgets.FieldWidget(widget=None, attrs=<factory>)[source]

Override default widget and HTML attributes for a model field.

Parameters:
widget: str | None = None

Widget name override.

attrs: dict[str, Any]

Extra HTML attributes merged onto the rendered control.

classmethod from_mapping(data)[source]

Build from a FieldWidget instance or shorthand dict.

Parameters:

data (FieldWidget | dict[str, Any]) – FieldWidget or dict with optional widget key plus HTML attribute overrides.

Returns:

Normalized FieldWidget instance.

Return type:

FieldWidget

fastapi_mongo_admin.admin.fields.widgets.apply_field_widget_override(admin_field, override)[source]

Apply a widget override onto an AdminField.

Parameters:
  • admin_field (Any) – AdminField instance to mutate.

  • override (FieldWidget | dict[str, Any]) – FieldWidget or shorthand dict.

Returns:

None.

Return type:

None

Mount helpers

Mount helpers for FastAPI applications.

fastapi_mongo_admin.utils.get_static_directory()[source]

Return the packaged static assets directory.

Returns:

Path to the fastapi_mongo_admin/static package directory.

Return type:

Path

fastapi_mongo_admin.utils.mount_admin_app(app, get_database, *, admin_site=None, router_prefix='/admin', mode='async', auth_dependency=None, permission_dependency=None, api_write_methods=False)[source]

Mount the admin UI, JSON API, and static files on a FastAPI application.

Parameters:
  • app (FastAPI) – FastAPI application to extend.

  • get_database (Callable[[...], AsyncIOMotorDatabase | Database | Awaitable[AsyncIOMotorDatabase]]) – Callable returning a Motor database, PyMongo database, or awaitable that resolves to one.

  • admin_site (AdminSite | None) – Admin site registry. Defaults to the global site singleton.

  • router_prefix (str) – URL prefix for admin routes (default /admin).

  • mode (Literal['async', 'sync']) – MongoDB access mode — async (Motor) or sync (PyMongo).

  • auth_dependency (Callable[[...], Any] | None) – Optional FastAPI dependency injected on admin routes.

  • permission_dependency (Callable[[...], Any] | None) – Optional dependency checked before the admin index.

  • api_write_methods (bool) – When True, register POST, PUT, PATCH, and DELETE JSON API routes and include them in OpenAPI (/docs). When False (default), only GET list/detail routes are registered and documented.

Returns:

None. Mutates app by including the admin router and static mount.

Return type:

None

Router

Admin view routes.

fastapi_mongo_admin.views.router.create_admin_router(admin_site, get_database, *, prefix='/admin', mode='async', auth_dependency=None, permission_dependency=None, static_url='/admin/static', api_write_methods=False)[source]

Create the admin UI and JSON API router.

Parameters:
  • admin_site (AdminSite) – Registered models and global admin configuration.

  • get_database (Callable[[...], Any]) – Callable returning the MongoDB database (sync or async).

  • prefix (str) – URL prefix for all admin routes (default /admin).

  • mode (Literal['async', 'sync']) – MongoDB access mode — async or sync.

  • auth_dependency (Callable[[...], Any] | None) – Optional FastAPI dependency for authentication.

  • permission_dependency (Callable[[...], Any] | None) – Optional dependency checked on the admin index.

  • static_url (str) – URL path prefix for packaged admin static files.

  • api_write_methods (bool) – When True, expose POST, PUT, PATCH, and DELETE JSON API endpoints in the router and OpenAPI schema. When False (default), only GET endpoints are registered.

Returns:

APIRouter with HTML admin views and /api JSON routes included.

Return type:

APIRouter

Repository

Collection repository for CRUD operations.

fastapi_mongo_admin.services.repository.related_object_label(doc)[source]

Return a human-readable label for a related document.

Parameters:

doc (dict[str, Any]) – Related MongoDB document.

Returns:

Best-effort display label for select widgets and changelists.

Return type:

str

class fastapi_mongo_admin.services.repository.CollectionRepository(backend, model_admin)[source]

Repository wrapping sync or async MongoDB backends for one collection.

Parameters:
async list_documents(*, page=1, search='', filter_params=None, date_hierarchy_params=None, show_all=False, request=None)[source]

List documents with pagination, search, and filters.

Parameters:
  • page (int) – Page number (1-based).

  • search (str) – Changelist search string.

  • filter_params (dict[str, str] | None) – Active list-filter query parameters.

  • date_hierarchy_params (dict[str, str] | None) – Optional date hierarchy drill-down params.

  • show_all (bool) – When True, use list_max_show_all as page size.

  • request (Any) – Current request passed to queryset hooks.

Returns:

Dict with results, total, page, per_page, and num_pages keys.

Return type:

dict[str, Any]

async get_document(doc_id)[source]

Fetch a single serialized document by id.

Parameters:

doc_id (str) – Document id string.

Returns:

Serialized document dict with an id field.

Raises:

DocumentNotFoundError – When no document matches the id.

Return type:

dict[str, Any]

async create_document(form_data, request=None)[source]

Create a document from form or JSON data.

Parameters:
  • form_data (dict[str, Any]) – Raw field values to validate and persist.

  • request (Any) – Current request passed to hooks.

Returns:

New document id string.

Return type:

str

async update_document(doc_id, form_data, request=None)[source]

Update a document from form or JSON data.

Parameters:
  • doc_id (str) – Document id string.

  • form_data (dict[str, Any]) – Raw field values to validate and persist.

  • request (Any) – Current request passed to hooks.

Returns:

True when the backend reports a successful update.

Return type:

bool

async delete_document(doc_id, request=None)[source]

Delete a document by id.

Parameters:
  • doc_id (str) – Document id string.

  • request (Any) – Current request passed to delete_model hook.

Returns:

True when the backend reports a successful delete.

Return type:

bool

async delete_many(doc_ids)[source]

Bulk delete documents by id.

Parameters:

doc_ids (list[str]) – Document id strings.

Returns:

Number of deleted documents.

Return type:

int

Fetch the current value label for list_select_related form fields.

Parameters:

obj (dict[str, Any] | None) – Existing document on change forms.

Returns:

Mapping of field name to (value, label) for the selected reference.

Return type:

dict[str, tuple[str, str]]

Search related documents for a searchable form dropdown.

Parameters:
  • field_name (str) – Model field configured in list_select_related.

  • query (str) – User search string.

  • min_chars (int) – Minimum query length before searching.

  • limit (int) – Maximum number of matches to return.

Returns:

List of (value, label) tuples sorted by label.

Return type:

list[tuple[str, str]]

Register a backend for list_select_related lookups.

Parameters:
  • collection (str) – Related collection name.

  • backend (AsyncMotorBackend | SyncPyMongoBackend) – Backend for that collection.

Returns:

None.

Return type:

None

Formatting

Display formatting for date and datetime values.

fastapi_mongo_admin.formatting.parse_datetime(value)[source]

Parse a datetime from BSON, ISO string, or date.

Parameters:

value (Any) – Input value to parse.

Returns:

Parsed datetime, or None when parsing fails.

Return type:

datetime | None

fastapi_mongo_admin.formatting.parse_date(value)[source]

Parse a date from BSON, ISO string, or datetime.

Parameters:

value (Any) – Input value to parse.

Returns:

Parsed date, or None when parsing fails.

Return type:

date | None

fastapi_mongo_admin.formatting.format_date_display(value, fmt=None)[source]

Format a value for date display in lists and readonly fields.

Parameters:
  • value (Any) – Raw field value.

  • fmt (str | None) – Optional custom format string.

Returns:

Formatted date string, or "" for empty values.

Return type:

str

fastapi_mongo_admin.formatting.format_datetime_display(value, fmt=None)[source]

Format a value for datetime display in lists and readonly fields.

Parameters:
  • value (Any) – Raw field value.

  • fmt (str | None) – Optional custom format string.

Returns:

Formatted datetime string, or "" for empty values.

Return type:

str

Schema utilities

Pydantic schema inference for admin forms and lists.

fastapi_mongo_admin.schemas.inference.serialize_document(doc)[source]

Convert a MongoDB document to a JSON-serializable dict.

Parameters:

doc (dict[str, Any]) – Raw MongoDB document.

Returns:

Serialized document with id alias for _id.

Return type:

dict[str, Any]

fastapi_mongo_admin.schemas.inference.prepare_for_mongodb(value)[source]

Recursively convert Python values to BSON-encodable types.

Parameters:

value (Any) – Python value from a validated model.

Returns:

BSON-safe value for insertion/update.

Return type:

Any

fastapi_mongo_admin.schemas.inference.format_field_value(field)[source]

Format a field value for HTML form controls.

Parameters:

field (AdminField) – AdminField with value and widget metadata.

Returns:

Value formatted for the field’s widget type.

Return type:

Any

fastapi_mongo_admin.schemas.inference.infer_admin_fields(model, *, readonly_fields=None, choices=None, field_overrides=None)[source]

Build an AdminField list from a Pydantic model.

Parameters:
Returns:

List of AdminField metadata objects.

Return type:

list[AdminField]

fastapi_mongo_admin.schemas.inference.prepare_form_fields(model, *, obj=None, readonly_fields=None, choices=None, field_overrides=None, display_formatter=None)[source]

Build admin fields with values formatted for HTML widgets.

Parameters:
  • model (Type[BaseModel] | None) – Pydantic model class.

  • obj (dict[str, Any] | None) – Existing document for edit forms.

  • readonly_fields (list[str] | None) – Field names rendered read-only.

  • choices (dict[str, list[tuple[Any, str]]] | None) – Per-field select choices.

  • field_overrides (dict[str, FieldWidget | dict[str, Any]] | None) – Per-field widget overrides.

  • display_formatter (Any | None) – Optional object with format_display_value.

Returns:

List of AdminField objects with value populated.

Return type:

list[AdminField]

fastapi_mongo_admin.schemas.inference.infer_schema_dict(model)[source]

Return schema metadata dict for API responses.

Parameters:

model (Type[BaseModel]) – Pydantic model class.

Returns:

Dict with model name and per-field metadata.

Return type:

dict[str, Any]

Form parsing and Pydantic validation.

fastapi_mongo_admin.schemas.forms.parse_form_to_model(model, form_data, *, existing=None, readonly_fields=None)[source]

Validate and normalize form or JSON data through a Pydantic model.

Parameters:
  • model (Type[BaseModel] | None) – Pydantic model class, or None to pass data through unchanged.

  • form_data (dict[str, Any]) – Raw submitted field values.

  • existing (dict[str, Any] | None) – Existing document for partial updates.

  • readonly_fields (list[str] | None) – Field names preserved from existing when omitted.

Returns:

Validated document dict from model.model_dump().

Raises:

AdminValidationError – When Pydantic validation fails.

Return type:

dict[str, Any]

Field mapping

Field mapping between Pydantic model and MongoDB.

fastapi_mongo_admin.services.mapping.translate_to_db(data, mapping)[source]

Translate model field keys to database keys.

Parameters:
  • data (dict[str, Any]) – Document keyed by model field names.

  • mapping (dict[str, str] | None) – Optional model_field -> db_field mapping.

Returns:

Document keyed by database field names.

Return type:

dict[str, Any]

fastapi_mongo_admin.services.mapping.translate_from_db(doc, mapping)[source]

Translate database keys to model field keys.

Parameters:
  • doc (dict[str, Any]) – Document keyed by database field names.

  • mapping (dict[str, str] | None) – Optional model_field -> db_field mapping.

Returns:

Document keyed by model field names.

Return type:

dict[str, Any]

fastapi_mongo_admin.services.mapping.translate_query(query, mapping)[source]

Translate query keys including MongoDB operators.

Parameters:
  • query (dict[str, Any]) – MongoDB filter document keyed by model field names.

  • mapping (dict[str, str] | None) – Optional model_field -> db_field mapping.

Returns:

Filter document keyed by database field names.

Return type:

dict[str, Any]

Exceptions

Admin HTTP exceptions.

exception fastapi_mongo_admin.exceptions.AdminException(status_code, detail, error_code=None, details=None)[source]

Base exception for admin operations.

Parameters:
error_code

Optional machine-readable error code.

details

Optional extra error context.

exception fastapi_mongo_admin.exceptions.DocumentNotFoundError(document_id, collection_name)[source]

Raised when a document is not found in a collection.

Parameters:
  • document_id (str)

  • collection_name (str)

exception fastapi_mongo_admin.exceptions.CollectionNotFoundError(collection_name)[source]

Raised when a collection is not registered or missing.

Parameters:

collection_name (str)

exception fastapi_mongo_admin.exceptions.InvalidQueryError(detail, query=None)[source]

Raised when a changelist or API query is invalid.

Parameters:
  • detail (str)

  • query (str | None)

exception fastapi_mongo_admin.exceptions.ValidationError(detail, field=None, value=None)[source]

Raised when Pydantic or form validation fails.

Parameters:
  • detail (str)

  • field (str | None)

  • value (Any)

exception fastapi_mongo_admin.exceptions.PermissionDeniedError(resource, action)[source]

Raised when a user lacks permission for an admin action.

Parameters:

Internationalization

Translation helper for admin UI.

class fastapi_mongo_admin.i18n.translator.Translator(language, messages, fallback)[source]

Lookup translated strings with optional format placeholders.

Parameters:
gettext(key, **kwargs)[source]

Return a translated string for a message key.

Parameters:
  • key (str) – Message key.

  • **kwargs (Any) – Optional str.format placeholders.

Returns:

Translated string, or the key itself when missing.

Return type:

str

ngettext(singular_key, plural_key, count, **kwargs)[source]

Return singular or plural translation based on count.

Parameters:
  • singular_key (str) – Message key when count == 1.

  • plural_key (str) – Message key for all other counts.

  • count (int) – Value used to pick the form.

  • **kwargs (Any) – Optional str.format placeholders.

Returns:

Translated string for the chosen form.

Return type:

str