Complete guide from basic setup to production-ready admin with authentication.
Learn Monglo's core features step by step.
Get started with Monglo in just a few lines of code. This example shows automatic collection discovery and default UI setup.
Connect to MongoDB and create a Monglo engine with auto-discovery enabled:
client = AsyncIOMotorClient("mongodb://localhost:27017")
db = client.monglo_demo
app = FastAPI(title="Monglo Admin")
# Instantiate monglo engine
engine = MongloEngine(database=db, auto_discover=True)
auto_discover=True
automatically finds all MongoDB collections in your database and creates admin views for
them.
Use FastAPI's startup event to initialize Monglo and setup the UI:
@app.on_event("startup")
async def startup():
# Seed example data
await seed_database(db)
# Initialize monglo engine
await engine.initialize()
# Setup monglo UI with custom branding
setup_ui(
app,
engine=engine,
title="My Custom App", # Custom title
)
# Setup monglo router
app.include_router(create_fastapi_router(engine, prefix="/api"))
seed_database()
- Populates database with sample data (optional)engine.initialize()
- Discovers collections and detects relationshipssetup_ui()
- Adds admin UI routes at /admincreate_fastapi_router()
- Adds REST API routes at /apiHere's the full working application with all imports and shutdown handling:
from fastapi import FastAPI
from motor.motor_asyncio import AsyncIOMotorClient
from monglo import MongloEngine
from monglo.ui_helpers.fastapi import setup_ui
from monglo.adapters.fastapi import create_fastapi_router
from db import seed_database
client = AsyncIOMotorClient("mongodb://localhost:27017")
db = client.monglo_demo
app = FastAPI(title="Monglo Admin")
# Instantiate monglo engine
engine = MongloEngine(database=db, auto_discover=True)
@app.on_event("startup")
async def startup():
# Seed example data
await seed_database(db)
# Initialize monglo engine
await engine.initialize()
# Setup monglo UI with custom branding
setup_ui(
app,
engine=engine,
title="My Custom App", # Custom title
)
# Setup monglo router
app.include_router(create_fastapi_router(engine, prefix="/api"))
@app.on_event("shutdown")
async def shutdown():
client.close()
if __name__ == "__main__":
import uvicorn
uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=True)
For production apps, you'll want manual control over which collections are exposed and how they behave. Disable auto-discovery and register custom admin classes.
# MongoDB connection
client = AsyncIOMotorClient("mongodb://localhost:27017")
db = client.ecommerce_advanced
# Initialize Monglo engine
engine = MongloEngine(
database=db,
auto_discover=False # Don't auto-discover - we'll register custom admins manually
)
# Setup admin UI with branding
setup_ui(
app,
engine=engine,
title="E-Commerce Admin",
prefix="/custom_admin",
)
Order matters! Setup custom admins BEFORE calling engine.initialize():
# STARTUP & SHUTDOWN
@app.on_event("startup")
async def startup():
"""Initialize application on startup"""
print("🚀 Starting E-Commerce Admin...")
# Seed database with example data
await seed_database(db)
# Setup custom admin configurations FIRST
await setup_admin(engine)
# Then initialize monglo engine (discover relationships, etc.)
await engine.initialize()
# Setup REST API router
app.include_router(
create_fastapi_router(engine, prefix="/api"),
prefix="/api",
tags=["API"]
)
Define custom ModelAdmin
classes to control exactly how each collection appears and behaves in the admin UI.
class UserAdmin(ModelAdmin):
"""Custom admin for Users collection"""
# Display name in sidebar
display_name = "Users"
# Fields to display in list view
list_display = ["email", "full_name", "role", "is_active", "created_at"]
# Fields to search
search_fields = ["email", "username", "full_name"]
# Default sort
default_sort = [("created_at", -1)] # Newest first
# Items per page
per_page = 20
class CategoryAdmin(ModelAdmin):
"""Custom admin for Categories"""
display_name = "Categories"
list_display = ["name", "slug", "icon"]
search_fields = ["name", "slug"]
default_sort = [("name", 1)]
per_page = 50
class ProductAdmin(ModelAdmin):
"""Custom admin for Products with advanced config"""
display_name = "Products"
list_display = ["sku", "name", "price", "stock", "is_active", "is_featured"]
search_fields = ["name", "sku", "description"]
default_sort = [("created_at", -1)]
per_page = 25
Create a setup function to register all your custom admin classes:
async def setup_admin(engine: MongloEngine):
"""
Configure custom admin classes for collections
This function registers custom ModelAdmin classes that define:
- Display names and icons
- List view columns
- Search fields
- Default sorting
- Pagination settings
- Field schemas
"""
# Register custom admin classes
registry = engine.registry
# Users
registry.register("users", UserAdmin)
# Categories
registry.register("categories", CategoryAdmin)
# Products
registry.register("products", ProductAdmin)
# Orders
registry.register("orders", OrderAdmin)
# Reviews
registry.register("reviews", ReviewAdmin)
print("✅ Custom admin configurations registered")
print(f" - {len(registry._collections)} collections with custom admin")
Secure your admin panel with MongoDB-based authentication. Users are stored in your database with hashed passwords and role-based access control.
# Helper function for password verification (example)
def verify_password(plain_password: str, hashed_password: str) -> bool:
import hashlib
hashed = hashlib.sha256(plain_password.encode()).hexdigest()
return hashed == hashed_password
# Setup MongoDB-based authentication backend
auth_backend = MongoDBAuthenticationBackend(
secret_key="your-secret-key-change-in-production", # Use env variable in production
user_collection=db.users, # Your users collection
username_field="email", # Field for username/email
password_field="hashed_password", # Field for hashed password
role_field="role", # Field for user role
admin_role="admin", # Required role for admin access
password_verifier=verify_password # Your password verification function
)
# Setup admin UI with authentication
# NOTE: Must be called BEFORE @app.on_event("startup") to register middleware
setup_ui(
app,
engine,
prefix="/admin",
title="Secured Admin Panel",
brand_color="#6366f1",
auth_backend=auth_backend # Pass the auth backend!
)
setup_ui()
must be called
BEFORE the @app.on_event("startup")
event to properly register authentication middleware.
@app.on_event("startup")
async def startup():
"""Initialize application"""
print("🚀 Starting Monglo Auth Example...")
# Seed database
await seed_database(db)
# Setup custom admin configurations
await setup_admin(engine)
# Initialize Monglo engine
await engine.initialize()
/admin
You now understand Monglo's core features from basic setup to production authentication.