### Install via pip Source: https://fastapi-admin.github.io/pro/installation Use this command to install the package directly from the private GitHub repository. ```bash > pip install git+https://${GH_TOKEN}@github.com/fastapi-admin/fastapi-admin-pro.git ``` -------------------------------- ### Install FastAPI Admin Source: https://fastapi-admin.github.io Use pip to install the package in your environment. ```bash > pip install fastapi-admin ``` -------------------------------- ### Install FastAPI-Admin Pro Version Source: https://fastapi-admin.github.io/pro/upgrade Install the pro version using pip with a GitHub token for private repository access. Ensure you have the GH_TOKEN environment variable set. ```bash pip install git+https://${GH_TOKEN}@github.com/fastapi-admin/fastapi-admin-pro.git ``` -------------------------------- ### Install FastAPI-Admin from Source (pip) Source: https://fastapi-admin.github.io/getting_started/installation Install the latest development version of FastAPI-Admin directly from its GitHub repository using pip. ```bash > pip install git+https://github.com/fastapi-admin/fastapi-admin.git ``` -------------------------------- ### Add FastAPI-Admin to requirements.txt Source: https://fastapi-admin.github.io/getting_started/installation Include this line in your requirements.txt file to specify the installation of FastAPI-Admin from its GitHub repository. ```text -e https://github.com/fastapi-admin/fastapi-admin.git#egg=fastapi-admin ``` -------------------------------- ### Configure SearchProvider in FastAPI Admin Source: https://fastapi-admin.github.io/reference/global_search Add `SearchProvider` to `admin_app.configure` to enable site search. This setup is typically done during the application's startup event. ```python from fastapi import FastAPI from fastapi_admin.app import app as admin_app from fastapi_admin.providers.search import SearchProvider app = FastAPI() @app.on_event("startup") async def startup(): await admin_app.configure( providers=[SearchProvider()] ) ``` -------------------------------- ### Configure PermissionProvider in FastAPI App Source: https://fastapi-admin.github.io/reference/permission Integrates the PermissionProvider into your FastAPI application during startup. This setup is essential for enabling permission control across your admin interface. ```python from fastapi import FastAPI from fastapi_admin.app import app as admin_app from fastapi_admin.providers.permission import PermissionProvider app = FastAPI() @app.on_event("startup") async def startup(): await admin_app.configure( providers=[ PermissionProvider( Admin, # Assuming Admin is your custom Admin model Resource, Permission, ), ] ) ``` -------------------------------- ### Uninstall FastAPI-Admin Open Source Source: https://fastapi-admin.github.io/pro/upgrade Use this command to remove the open-source version before installing the pro version. ```bash pip uninstall fastapi-admin ``` -------------------------------- ### Mount FastAPI-Admin App Source: https://fastapi-admin.github.io/getting_started/quickstart Mount the admin app from FastAPI-Admin as a sub-application of your FastAPI app. Ensure FastAPI-Admin is installed. ```python from fastapi_admin.app import app as admin_app from fastapi import FastAPI app = FastAPI() app.mount("/admin", admin_app) ``` -------------------------------- ### Register a Dropdown Resource with Nested Models Source: https://fastapi-admin.github.io/getting_started/quickstart Define a 'Dropdown' resource to group multiple resources (Links or Models) under a single menu item. This example nests 'ProductResource' and 'CategoryResource' under 'Content'. ```python from examples import enums from examples.models import Category, Product from fastapi_admin.app import app from fastapi_admin.resources import Dropdown, Field, Model from fastapi_admin.widgets import displays, filters @app.register class Content(Dropdown): class CategoryResource(Model): label = "Category" model = Category fields = ["id", "name", "slug", "created_at"] class ProductResource(Model): label = "Product" model = Product filters = [ filters.Enum(enum=enums.ProductType, name="type", label="ProductType"), filters.Datetime(name="created_at", label="CreatedAt"), ] fields = [ "id", "name", "view_num", "sort", "is_reviewed", "type", Field(name="image", label="Image", display=displays.Image(width="40")), "body", "created_at", ] label = "Content" icon = "fas fa-bars" resources = [ProductResource, CategoryResource] ``` -------------------------------- ### Define Base Action Model Source: https://fastapi-admin.github.io/custom/action Use this model to define a base action with properties like icon, label, name, method, and ajax. The `ajax_validate` method ensures that `ajax` can only be `False` when the HTTP method is `GET`. ```python class Action(BaseModel): icon: str label: str name: str method: enums.Method = enums.Method.POST ajax: bool = True @validator("ajax") def ajax_validate(cls, v: bool, values: dict, **kwargs): if not v and values["method"] != enums.Method.GET: raise ValueError("ajax is False only available when method is Method.GET") ``` -------------------------------- ### Configure Template Folders Source: https://fastapi-admin.github.io/custom/page Set up the template directory during the application startup event. ```python from fastapi import FastAPI from fastapi_admin.app import app as admin_app app = FastAPI() @app.on_event("startup") async def startup(): await admin_app.configure(template_folders=["templates"]) ``` -------------------------------- ### Configure Environment Variables Source: https://fastapi-admin.github.io Define database and Redis connection strings in a .env file. ```text DATABASE_URL=mysql://root:123456@127.0.0.1:3306/fastapi-admin REDIS_URL=redis://localhost:6379/0 ``` -------------------------------- ### ALiYunOSS Configuration (Pro) Source: https://fastapi-admin.github.io/reference/file_upload Configuration for ALiYunOSS cloud storage integration. ```APIDOC ## ALiYunOSS (💗 Pro only) `fastapi_admin.file_upload.ALiYunOSS` See https://help.aliyun.com/product/31815.html ### Parameters * `access_key` (string) - Required - Access key of aliyun. * `access_key_secret` (string) - Required - Access ket secret of aliyun. * `bucket` (string) - Required - Bucket name of aliyun oss. * `endpoint` (string) - Required - Endpoint of aliyun oss. ``` -------------------------------- ### Configure FastAPI Admin on Startup Source: https://fastapi-admin.github.io/reference Configure the predefined `admin_app` from `fastapi-admin` on the startup event of your FastAPI application. This ensures the admin app is properly initialized within the asyncio loop. Requires `aioredis` for Redis integration and a model for admin authentication. ```python import aioredis from fastapi import FastAPI from fastapi_admin.app import app as admin_app from fastapi_admin.providers.login import UsernamePasswordProvider from examples.models import Admin app = FastAPI() @app.on_event("startup") async def startup(): redis = await aioredis.create_redis_pool(address='redis://localhost') await admin_app.configure( logo_url="https://preview.tabler.io/static/logo-white.svg", template_folders=["templates"], providers=[ UsernamePasswordProvider( login_logo_url="https://preview.tabler.io/static/logo.svg", admin_model=Admin ) ], redis=redis, ) ``` -------------------------------- ### Configure Admin App Settings Source: https://fastapi-admin.github.io/getting_started/quickstart Configure the admin app settings on FastAPI's startup event. This includes setting up a login provider, logo, template folders, and a Redis connection. ```python from fastapi_admin.app import app as admin_app from fastapi_admin.providers.login import UsernamePasswordProvider from examples.models import Admin import aioredis from fastapi import FastAPI import os login_provider = UsernamePasswordProvider( admin_model=Admin, enable_captcha=True, login_logo_url="https://preview.tabler.io/static/logo.svg" ) app = FastAPI() @app.on_event("startup") async def startup(): redis = await aioredis.create_redis_pool("redis://localhost", encoding="utf8") admin_app.configure( logo_url="https://preview.tabler.io/static/logo-white.svg", template_folders=[os.path.join(BASE_DIR, "templates")], providers=[login_provider], redis=redis, ) ``` -------------------------------- ### Enable Site Search Source: https://fastapi-admin.github.io/pro/exclusive Add `SearchProvider` to `admin_app.configure(...)` to enable site-wide search functionality. ```python await admin_app.configure(providers=[SearchProvider()]) ``` -------------------------------- ### Enable Admin Logging Source: https://fastapi-admin.github.io/pro/exclusive Include `AdminLogProvider` in `admin_app.configure(...)` to log all create, update, and delete actions performed within the admin interface. ```python await admin_app.configure(providers=[AdminLogProvider(Log)]) ``` -------------------------------- ### Create a Dropdown menu Source: https://fastapi-admin.github.io/reference/resource Define a Dropdown class to group multiple resources under a single label and icon. ```python @app.register class Content(Dropdown): label = "Content" icon = "fas fa-bars" resources = [ProductResource, CategoryResource] ``` -------------------------------- ### Configure AdminLogProvider in FastAPI Source: https://fastapi-admin.github.io/reference/admin_log Register the AdminLogProvider within the startup event of the FastAPI application. ```python from fastapi import FastAPI from fastapi_admin.app import app as admin_app from fastapi_admin.providers.admin_log import AdminLogProvider from examples.models import Log app = FastAPI() @app.on_event("startup") async def startup(): await admin_app.configure( providers=[AdminLogProvider(Log)] ) ``` -------------------------------- ### Configure OAuth2 Providers Source: https://fastapi-admin.github.io/reference/login Integrates GitHub or Google OAuth2 authentication by providing client credentials and the required redirect URI. ```python from fastapi import FastAPI from fastapi_admin.app import app as admin_app from examples.providers import GitHubProvider, GoogleProvider, LoginProvider from examples.models import Admin app = FastAPI() @app.on_event("startup") async def startup(): await admin_app.configure( providers=[ GitHubProvider(Admin, settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET), GoogleProvider( Admin, settings.GOOGLE_CLIENT_ID, settings.GOOGLE_CLIENT_SECRET, redirect_uri="https://fastapi-admin-pro.long2ice.io/admin/oauth2/google_oauth2_provider", ), ] ) ``` -------------------------------- ### Configure Notification Provider Source: https://fastapi-admin.github.io/reference/notification Add the NotificationProvider to your FastAPI application's startup event to enable the notification center. Ensure FastAPI-Admin is configured with this provider. ```python from fastapi import FastAPI from fastapi_admin.app import app as admin_app from fastapi_admin.providers.notification import NotificationProvider app = FastAPI() provider = NotificationProvider() @app.on_event("startup") async def startup(): await admin_app.configure( providers=[provider] ) ``` -------------------------------- ### Add dependency to requirements.txt Source: https://fastapi-admin.github.io/pro/installation Add this line to your requirements.txt file to include the package as an editable dependency. ```text -e https://${GH_TOKEN}@github.com/fastapi-admin/fastapi-admin-pro.git#egg=fastapi-admin-pro ``` -------------------------------- ### Configure UsernamePasswordProvider Source: https://fastapi-admin.github.io/reference/login Enables standard username and password authentication by adding the provider to the admin application configuration. ```python from fastapi import FastAPI from fastapi_admin.app import app as admin_app from fastapi_admin.providers.login import UsernamePasswordProvider from examples.models import Admin app = FastAPI() @app.on_event("startup") async def startup(): await admin_app.configure( providers=[ LoginProvider( login_logo_url="https://preview.tabler.io/static/logo.svg", admin_model=Admin, ) ] ) ``` -------------------------------- ### Define a Model Resource with Basic Configuration Source: https://fastapi-admin.github.io/reference/resource Register a Model resource, setting its label, associated TortoiseORM model, page titles, and defining search and date filters. ```python @app.register class AdminResource(Model): label = "Admin" model = Admin page_pre_title = "admin list" page_title = "Admin Model" filters = [ filters.Search( name="username", label="Name", search_mode="contains", placeholder="Search for username", ), filters.Date(name="created_at", label="CreatedAt"), ] ``` -------------------------------- ### Enable Notifications Source: https://fastapi-admin.github.io/pro/exclusive Add `NotificationProvider` to `admin_app.configure(...)` to enable real-time notifications implemented via WebSockets. ```python await admin_app.configure(providers=[NotificationProvider()]) ``` -------------------------------- ### AwsS3 Configuration (Pro) Source: https://fastapi-admin.github.io/reference/file_upload Configuration for AWS S3 cloud storage integration. ```APIDOC ## AwsS3 (💗 Pro only) `fastapi_admin.file_upload.AwsS3` See https://aws.amazon.com/s3 ### Parameters * `access_key` (string) - Required - Access key of aws. * `access_key_secret` (string) - Required - Access ket secret of aws. * `bucket` (string) - Required - Bucket name of aws. * `region_name` (string) - Required - Regin name of aws. ``` -------------------------------- ### Display Widgets Overview Source: https://fastapi-admin.github.io/reference/widget/display This section provides an overview of the different display widgets available in FastAPI Admin. ```APIDOC ## Display Widgets FastAPI Admin provides several display widgets to customize how data is rendered in tables and edit pages. ### Default Display - **Description**: The default display widget, which renders the value without any modifications. ### DatetimeDisplay - **Description**: Displays a datetime value formatted according to a specified format string. Defaults to `%Y-%m-%d %H:%M:%S`. - **Usage**: `class DatetimeDisplay(Display)` - **Constructor**: `__init__(self, format_: str = constants.DATETIME_FORMAT)` ### DateDisplay - **Description**: Displays a date value formatted according to a specified format string. Defaults to `%Y-%m-%d`. - **Usage**: `class DateDisplay(Display)` - **Constructor**: `__init__(self, format_: str = constants.DATE_FORMAT)` ### InputOnly - **Description**: A special display widget that does not render in the table content but is only displayed on the edit page. ### Boolean - **Description**: Displays a value in a boolean format. ### Image - **Description**: Displays a value as an image. ### Json - **Description**: Displays a value with JSON highlighting for better readability. ``` -------------------------------- ### Register a Link Resource Source: https://fastapi-admin.github.io/reference/resource Register a Link resource using the @app.register decorator. This creates a menu item with a label, icon, and URL. ```python from fastapi_admin.app import app from fastapi_admin.resources import Link @app.register class Home(Link): label = "Home" icon = "fas fa-home" url = "/admin" ``` -------------------------------- ### Define Model Fields with Custom Inputs and Displays Source: https://fastapi-admin.github.io/reference/resource Configure fields for a Model resource, specifying names, labels, custom display widgets, and input types like passwords and images. Use 'str' for auto-mapping or 'Field' for custom configurations. ```python @app.register class AdminResource(Model): fields = [ "id", "username", Field( name="password", label="Password", display=displays.InputOnly(), input_=inputs.Password(), ), Field(name="email", label="Email", input_=inputs.Email()), Field( name="avatar", label="Avatar", display=displays.Image(width="40"), input_=inputs.Image(null=True, upload=upload), ), "created_at", ] ``` -------------------------------- ### Configure FileUpload for Image Input Source: https://fastapi-admin.github.io/reference/file_upload Use FileUpload to specify the directory for uploads when configuring an Image input field. Ensure the uploads_dir is correctly set up. ```python upload = FileUpload(uploads_dir=os.path.join(BASE_DIR, "static", "uploads")) @app.register class AdminResource(Model): fields = [ Field( name="avatar", label="Avatar", display=displays.Image(width="40"), input_=inputs.Image(null=True, upload=upload), ), ] ``` -------------------------------- ### Configure OAuth2 Providers Source: https://fastapi-admin.github.io/pro/exclusive Configure built-in OAuth2 providers like GitHub and Google by passing the relevant `Admin` model, client IDs, and secrets to their respective providers. ```python await admin_app.configure( providers=[ GitHubProvider(Admin, settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET), GoogleProvider( Admin, settings.GOOGLE_CLIENT_ID, settings.GOOGLE_CLIENT_SECRET, redirect_uri="https://fastapi-admin-pro.long2ice.io/admin/oauth2/google_oauth2_provider", ), ] ) ``` -------------------------------- ### Initialize DatetimeDisplay Widget Source: https://fastapi-admin.github.io/reference/widget/display Initializes the DatetimeDisplay widget, which displays a value using a specified format. The default format is defined by constants.DATETIME_FORMAT. ```python class DatetimeDisplay(Display): def __init__(self, format_: str = constants.DATETIME_FORMAT): ``` -------------------------------- ### Register a Link Resource Source: https://fastapi-admin.github.io/getting_started/quickstart Register a 'Link' resource to display a menu item in the sidebar that points to a custom or external page. Requires importing 'Link' from fastapi_admin.resources. ```python from fastapi_admin.app import app from fastapi_admin.resources import Link @app.register class Home(Link): label = "Home" icon = "fas fa-home" url = "/admin" ``` -------------------------------- ### Implement Custom File Upload Backend Source: https://fastapi-admin.github.io/custom/file_upload Inherit from the FileUpload class and override the upload method to define custom storage logic. Ensure the method accepts an UploadFile object and returns the accessible file URL. ```python class FileUpload: def __init__( self, uploads_dir: str, allow_extensions: Optional[List[str]] = None, max_size: int = 1024 ** 3, filename_generator: Optional[Callable] = None, prefix: str = "/static/uploads", ): self.max_size = max_size self.allow_extensions = allow_extensions self.uploads_dir = uploads_dir self.filename_generator = filename_generator self.prefix = prefix async def save_file(self, filename: str, content: bytes): file = os.path.join(self.uploads_dir, filename) async with aiofiles.open(file, "wb") as f: await f.write(content) return os.path.join(self.prefix, filename) async def upload(self, file: UploadFile): if self.filename_generator: filename = self.filename_generator(file) else: filename = file.filename content = await file.read() file_size = len(content) if file_size > self.max_size: raise FileMaxSizeLimit(f"File size {file_size} exceeds max size {self.max_size}") if self.allow_extensions: for ext in self.allow_extensions: if filename.endswith(ext): raise FileExtNotAllowed( f"File ext {ext} is not allowed of {self.allow_extensions}" ) return await self.save_file(filename, content) ``` -------------------------------- ### Limit Failed Login Attempts Source: https://fastapi-admin.github.io/pro/exclusive Add `LoginPasswordMaxTryMiddleware` to restrict login attempts from IPs that repeatedly fail authentication. Configure `max_times` and `after_seconds` for the lockout period. ```python admin_app.add_middleware(BaseHTTPMiddleware, dispatch=LoginPasswordMaxTryMiddleware(max_times=3, after_seconds=360)) ``` -------------------------------- ### Enable Maintenance Mode Source: https://fastapi-admin.github.io/pro/exclusive Set `maintenance=True` during `admin_app.configure(...)` to put the site into maintenance mode. ```python await admin_app.configure(maintenance=True) ``` -------------------------------- ### FileUpload Configuration Source: https://fastapi-admin.github.io/reference/file_upload Configuration for the local FileUpload component, used in file input widgets. ```APIDOC ## FileUpload `fastapi_admin.file_upload.FileUpload` is used in `file` input widget. ### Parameters * `uploads_dir` (string) - Required - File upload directory. * `allow_extensions` (list) - Optional - Alow extensions list, default allow all extensions. * `max_size` (integer) - Optional - Max size allow of file upload. * `filename_generator` (Callable) - Optional - Filename generator `Callable`, which param type passed is `starlette.datastructures.UploadFile`. ### Request Example ```python import os from fastapi_admin.file_upload import FileUpload from fastapi_admin.resources import Field, displays, inputs BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__name__))) upload = FileUpload(uploads_dir=os.path.join(BASE_DIR, "static", "uploads")) # Assuming 'app' is your FastAPI instance and 'AdminResource' is defined elsewhere # @app.register # class AdminResource(Model): # fields = [ # Field( # name="avatar", # label="Avatar", # display=displays.Image(width="40"), # input_=inputs.Image(null=True, upload=upload), # ), # ] ``` ``` -------------------------------- ### Add FastAPI-Admin to Poetry dependencies Source: https://fastapi-admin.github.io/getting_started/installation Specify FastAPI-Admin as a dependency in your pyproject.toml file using Poetry, pointing to the GitHub repository for the latest code. ```toml fastapi-admin = { git = 'https://github.com/fastapi-admin/fastapi-admin.git' } ``` -------------------------------- ### Define Toolbar Action Model Source: https://fastapi-admin.github.io/custom/action Extend the base `Action` model to create a `ToolbarAction`. This model includes an optional `class_` attribute, likely for CSS styling or specific UI element identification. ```python class ToolbarAction(Action): class_: Optional[str] ``` -------------------------------- ### Define AbstractLog Model Source: https://fastapi-admin.github.io/reference/admin_log The log model must inherit from AbstractLog to store administrative action details. ```python class AbstractLog(Model): admin = fields.ForeignKeyField("models.Admin") content = fields.JSONField() resource = fields.CharField(max_length=50) action = fields.CharEnumField(enums.Action, default=enums.Action.create) created_at = fields.DatetimeField(auto_now_add=True) class Meta: abstract = True ordering = ["-id"] ``` -------------------------------- ### Configure Google Recaptcha V2 Source: https://fastapi-admin.github.io/pro/exclusive Integrate Google Recaptcha V2 by providing `site_key` and `secret` to the `GoogleRecaptcha` provider within the login configuration. ```python class GoogleRecaptcha(BaseModel): cdn_url: str = "https://www.google.com/recaptcha/api.js" verify_url: str = "https://www.google.com/recaptcha/api/siteverify" site_key: str secret: str ``` ```python from fastapi_admin.providers.login import GoogleRecaptcha await admin_app.configure( providers=[ LoginProvider( google_recaptcha=GoogleRecaptcha( site_key=settings.GOOGLE_RECAPTCHA_SITE_KEY, secret=settings.GOOGLE_RECAPTCHA_SECRET, ), ), ] ) ``` -------------------------------- ### Define Custom Page Router Source: https://fastapi-admin.github.io/custom/page Create a route to render a template, optionally requiring admin authentication via the get_current_admin dependency. ```python from fastapi_admin.app import app as admin_app from fastapi_admin.template import templates from starlette.requests import Request from fastapi import Depends from fastapi_admin.depends import get_current_admin @admin_app.get("/", dependencies=[Depends(get_current_admin)]) async def home(request: Request): return templates.TemplateResponse("dashboard.html", context={"request": request}) ``` -------------------------------- ### Configure LoginPasswordMaxTryMiddleware Source: https://fastapi-admin.github.io/reference/middleware Adds the LoginPasswordMaxTryMiddleware to the FastAPI-Admin application to limit failed login attempts from a single IP. ```python from starlette.middleware.base import BaseHTTPMiddleware from fastapi_admin import middlewares from fastapi_admin.app import app as admin_app admin_app.add_middleware(BaseHTTPMiddleware, dispatch=middlewares.LoginPasswordMaxTryMiddleware(max_times=3, after_seconds=3600)) ``` -------------------------------- ### Define Custom Resource, Permission, and Role Models Source: https://fastapi-admin.github.io/reference/permission Inherit from FastAPI Admin's abstract models to define custom Resource, Permission, and Role classes. This is a required step for integrating custom permission logic. ```python from fastapi_admin.models import ( AbstractPermission, AbstractResource, AbstractRole, ) class Resource(AbstractResource): pass class Permission(AbstractPermission): pass class Role(AbstractRole): pass ``` -------------------------------- ### Add dependency to Poetry Source: https://fastapi-admin.github.io/pro/installation Include this line in the [tool.poetry.dependencies] section of your pyproject.toml file. ```toml fastapi-admin-pro = { git = 'https://${GH_TOKEN}@github.com/fastapi-admin/fastapi-admin-pro.git'} ``` -------------------------------- ### Register Custom Page as Link Resource Source: https://fastapi-admin.github.io/custom/page Add the custom page to the admin interface by registering a Link resource class. ```python from fastapi_admin.app import app as admin_app from fastapi_admin.resources import Link @admin_app.register class Dashboard(Link): label = "Dashboard" icon = "fas fa-home" url = "/admin" ``` -------------------------------- ### Configure Datetime Filter Source: https://fastapi-admin.github.io/reference/widget/filter Adds a datetime-based filter to a model resource. ```python @app.register class AdminResource(Model): filters = [ filters.Datetime(name="created_at", label="CreatedAt"), ] ``` -------------------------------- ### Configure Date Filter Source: https://fastapi-admin.github.io/reference/widget/filter Adds a date-based filter to a model resource. ```python @app.register class AdminResource(Model): filters = [ filters.Date(name="created_at", label="CreatedAt"), ] ``` -------------------------------- ### Hide Default Actions in a Model Resource Source: https://fastapi-admin.github.io/reference/resource Override 'get_actions' and 'get_bulk_actions' to return empty lists and hide default delete and edit actions for a Model resource. ```python @app.register class AdminResource(Model): async def get_actions(self, request: Request) -> List[Action]: return [] async def get_bulk_actions(self, request: Request) -> List[Action]: return [] ``` -------------------------------- ### Enable Login Captcha Source: https://fastapi-admin.github.io/pro/exclusive Set `enable_captcha=True` in the `UsernamePasswordProvider` to enable CAPTCHA on the admin login page. ```python login_provider = UsernamePasswordProvider(user_model=User, enable_captcha=True) ``` -------------------------------- ### Customize toolbar actions in ModelResource Source: https://fastapi-admin.github.io/reference/resource Override get_toolbar_actions to append custom actions to the table toolbar. Requires returning a list of ToolbarAction objects. ```python @app.register class CategoryResource(Model): async def get_toolbar_actions(self, request: Request) -> List[ToolbarAction]: actions = await super().get_toolbar_actions(request) actions.append(import_export_provider.import_action) actions.append(import_export_provider.export_action) return actions ``` -------------------------------- ### Define a Model Resource with Fields and Filters Source: https://fastapi-admin.github.io/getting_started/quickstart Define a 'Model' resource to create a CRUD interface for a TortoiseORM model. Customize fields, display options, input types, and add filters for searching and date range selection. ```python from examples.models import Admin from fastapi_admin.app import app from fastapi_admin.file_upload import FileUpload from fastapi_admin.resources import Field, Model from fastapi_admin.widgets import displays, filters, inputs import os upload = FileUpload(uploads=os.path.join(BASE_DIR, "static", "uploads")) @app.register class AdminResource(Model): label = "Admin" model = Admin icon = "fas fa-user" page_pre_title = "admin list" page_title = "admin model" filters = [ filters.Search( name="username", label="Name", search_mode="contains", placeholder="Search for username" ), filters.Date(name="created_at", label="CreatedAt"), ] fields = [ "id", "username", Field( name="password", label="Password", display=displays.InputOnly(), input_=inputs.Password(), ), Field(name="email", label="Email", input_=inputs.Email()), Field( name="avatar", label="Avatar", display=displays.Image(width="40"), input_=inputs.Image(null=True, upload=upload), ), "created_at", ] ``` -------------------------------- ### Custom Datetime Display Widget Source: https://fastapi-admin.github.io/custom/widget Extends the Display widget to format datetime or date objects. Requires the 'pendulum' library for formatting. ```python class DatetimeDisplay(Display): def __init__(self, format_: str = constants.DATETIME_FORMAT): super().__init__() self.format_ = format_ async def render(self, request: Request, value: datetime): if isinstance(value, datetime): return await super(DatetimeDisplay, self).render( request, pendulum.instance(value).format(self.format_) if value else None ) elif isinstance(value, date): return await super(DatetimeDisplay, self).render( request, pendulum.date(value.year, value.month, value.day).format(self.format_) if value else None, ) ``` -------------------------------- ### Base Widget Class Source: https://fastapi-admin.github.io/custom/widget The base class for all widgets, handling context and template rendering. Subclasses should define a 'template' attribute. ```python class Widget: templates: Jinja2Templates = t template: str = "" def __init__(self, **context): """ All context will pass to template render if template is not empty. :param context: """ self.context = context async def render(self, request: Request, value: Any): if value is None: value = "" if not self.template: return value return self.templates.get_template(self.template).render(value=value, **self.context) ``` -------------------------------- ### Configure Enum Filter Source: https://fastapi-admin.github.io/reference/widget/filter Creates a filter based on an Enum class for selecting values. ```python class ProductResource(Model): filters = [ filters.Enum(enum=enums.ProductType, name="type", label="ProductType"), ] ``` -------------------------------- ### HTML Text Input Widget Source: https://fastapi-admin.github.io/custom/widget A basic Input widget for HTML text fields. It inherits from Input and sets the input_type to 'text'. ```python class Text(Input): input_type: Optional[str] = "text" def __init__( self, help_text: Optional[str] = None, default: Any = None, null: bool = False, placeholder: str = "", disabled: bool = False, ): super().__init__( null=null, default=default, input_type=self.input_type, placeholder=placeholder, disabled=disabled, help_text=help_text, ) ``` -------------------------------- ### Define Built-in Permissions Source: https://fastapi-admin.github.io/reference/permission Defines the enumeration for permission types: create, delete, update, and read. These are used to control access to resources. ```python class Permission(str, Enum): create = "create" delete = "delete" update = "update" read = "read" ``` -------------------------------- ### Create a Custom ComputeField Source: https://fastapi-admin.github.io/reference/resource Define a virtual field by subclassing 'Field' and overriding the 'get_value' method to compute and return a value based on the object's data. ```python class ComputeField(Field): async def get_value(self, request: Request, obj: dict): return obj.get(self.name) ``` -------------------------------- ### Configure Search Filter Source: https://fastapi-admin.github.io/reference/widget/filter Defines a search filter on a model field with specified search modes. ```python @app.register class AdminResource(Model): filters = [ filters.Search( name="username", label="Name", search_mode="contains", placeholder="Search for username", ), ] ``` -------------------------------- ### Add Exception Handlers for HTTP Errors Source: https://fastapi-admin.github.io/reference/errors Use `add_exception_handler` to register handlers for specific HTTP error codes. This allows `fastapi-admin` to display custom error pages for 403, 404, and 500 errors. ```python from fastapi_admin.exceptions import forbidden_error_exception, not_found_error_exception, server_error_exception from starlette.status import HTTP_403_FORBIDDEN, HTTP_404_NOT_FOUND, HTTP_500_INTERNAL_SERVER_ERROR admin_app.add_exception_handler(HTTP_500_INTERNAL_SERVER_ERROR, server_error_exception) admin_app.add_exception_handler(HTTP_404_NOT_FOUND, not_found_error_exception) admin_app.add_exception_handler(HTTP_403_FORBIDDEN, forbidden_error_exception) ``` -------------------------------- ### Search Filter Widget Source: https://fastapi-admin.github.io/custom/widget A Filter widget for implementing search functionality. It supports various search modes and customizes the template. ```python class Search(Filter): template = "widgets/filters/search.html" def __init__( self, name: str, label: str, search_mode: str = "equal", placeholder: str = "", null: bool = True, ): """ Search for keyword :param name: :param label: :param search_mode: equal,contains,icontains,startswith,istartswith,endswith,iendswith,iexact,search """ if search_mode == "equal": super().__init__(name, label, placeholder, null) else: super().__init__(name + "__" + search_mode, label, placeholder) self.context.update(search_mode=search_mode) ``` -------------------------------- ### Implement Computed Field Logic Source: https://fastapi-admin.github.io/reference/resource Extend 'ComputeField' to implement specific computation logic, such as calculating remaining days until a date. ```python class RestDays(ComputeField): async def get_value(self, request: Request, obj: dict): days = (obj.get(self.name) - date.today()).days return days if days >= 0 else 0 ``` -------------------------------- ### Send Broadcast Notification Source: https://fastapi-admin.github.io/reference/notification Use the broadcast method on the NotificationProvider instance to send notifications to all connected WebSocket clients. The data payload should include title, content, image, and an optional link. ```python data = { "title": "test", "content": "//avatars.githubusercontent.com/u/13377178?v=4", "image": "https://avatars.githubusercontent.com/u/13377178?v=4", "link": "https://fastapi-admin.github.io" } await provider.broadcast(data) ``` -------------------------------- ### Send Notification via HTTP API Source: https://fastapi-admin.github.io/reference/notification Send notifications externally by making a POST request to the admin notification endpoint. This is useful for triggering notifications from outside the application context. ```python import requests requests.post('http://localhost:8000/admin/notification', json=data) ``` -------------------------------- ### Customize Row Attributes Based on Object Status Source: https://fastapi-admin.github.io/reference/resource Override the 'row_attributes' method to dynamically add CSS classes to table rows based on object properties, such as setting a green background for active status. ```python @app.register class ConfigResource(Model): async def row_attributes(self, request: Request, obj: dict) -> dict: if obj.get("status") == enums.Status.on: return {"class": "bg-green text-white"} return await super().row_attributes(request, obj) ``` -------------------------------- ### Customize Column Attributes Based on Field Name Source: https://fastapi-admin.github.io/reference/resource Override the 'column_attributes' method to apply specific CSS classes to columns based on the field name, like setting a width for the 'content' column. ```python @app.register class LogResource(Model): async def column_attributes(self, request: Request, field: Field) -> dict: if field.name == "content": return {"class": "w-50"} return await super().column_attributes(request, field) ``` -------------------------------- ### Customize Cell Attributes Based on Field and Object Source: https://fastapi-admin.github.io/reference/resource Override the 'cell_attributes' method to conditionally apply CSS classes to individual cells based on both the column field and the row object's data, such as styling the 'id' cell. ```python @app.register class AdminResource(Model): async def cell_attributes(self, request: Request, obj: dict, field: Field) -> dict: if field.name == "id": return {"class": "bg-danger text-white"} return await super().cell_attributes(request, obj, field) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.