### Configuring FastAPI-Admin App (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/getting_started/quickstart.md Shows how to configure the FastAPI-Admin application during the FastAPI startup event. It sets up a username/password login provider, connects to Redis, and configures visual elements like logos and template folders. ```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 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, ) ``` -------------------------------- ### Defining Dropdown Resource with Nested Models (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/getting_started/quickstart.md Demonstrates how to create a `Dropdown` resource to group other resources (like `Model` or `Link`) in the sidebar. This example groups `CategoryResource` and `ProductResource` under a "Content" dropdown menu. ```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] ``` -------------------------------- ### Install fastapi-admin from Source (Shell) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/getting_started/installation.md This command installs the fastapi-admin library directly from its Git repository on GitHub using pip. This is useful for getting the latest development version or contributing. ```shell > pip install git+https://github.com/fastapi-admin/fastapi-admin.git ``` -------------------------------- ### Mounting FastAPI-Admin App (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/getting_started/quickstart.md Demonstrates how to mount the FastAPI-Admin application instance (`admin_app`) as a sub-application at the "/admin" path within a standard FastAPI application instance (`app`). This makes the admin interface accessible at `/admin`. ```Python from fastapi_admin.app import app as admin_app from fastapi import FastAPI app = FastAPI() app.mount("/admin", admin_app) ``` -------------------------------- ### Defining Link Resource in FastAPI-Admin (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/getting_started/quickstart.md Illustrates how to create a `Link` resource, which represents a simple navigation link in the admin sidebar. It's registered with the admin application instance (`app`) and configured with a label, icon, and target 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" ``` -------------------------------- ### Defining Model Resource for Admin (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/getting_started/quickstart.md Shows how to define a `Model` resource for a database model (e.g., `Admin`). It automatically generates CRUD pages and allows customization of fields, filters, displays, and inputs, including file uploads. ```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 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", ] ``` -------------------------------- ### Install fastapi-admin from PyPI (Shell) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/getting_started/installation.md This command installs the fastapi-admin library directly from the Python Package Index (PyPI) using the pip package manager. It's the standard way to get the latest stable release. ```shell > pip install fastapi-admin ``` -------------------------------- ### Add fastapi-admin Source to requirements.txt Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/getting_started/installation.md This line can be added to a `requirements.txt` file to specify that fastapi-admin should be installed directly from its Git repository in editable mode. This is common for development or testing against the latest source. ```text -e https://github.com/fastapi-admin/fastapi-admin.git#egg=fastapi-admin ``` -------------------------------- ### Configure Database and Redis URLs (.env) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/index.md Provides example configuration for the database and Redis connection URLs in a .env file. These settings are required for running the fastapi-admin examples. ```dotenv DATABASE_URL=mysql://root:123456@127.0.0.1:3306/fastapi-admin REDIS_URL=redis://localhost:6379/0 ``` -------------------------------- ### Add fastapi-admin Source to poetry dependencies (TOML) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/getting_started/installation.md This line is added to the `[tool.poetry.dependencies]` section of a `pyproject.toml` file to specify that Poetry should install fastapi-admin directly from its Git repository. This integrates the source dependency into a Poetry-managed project. ```toml fastapi-admin = { git = 'https://github.com/fastapi-admin/fastapi-admin.git' } ``` -------------------------------- ### Add fastapi-admin-pro dependency with poetry Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/pro/installation.md Adds the fastapi-admin-pro package as a dependency in a poetry project's pyproject.toml file. The configuration specifies the Git repository URL and uses the GH_TOKEN environment variable for authentication. ```toml fastapi-admin-pro = { git = 'https://${GH_TOKEN}@github.com/fastapi-admin/fastapi-admin-pro.git'} ``` -------------------------------- ### Configuring a Model Resource with Basic Options and Filters in FastAPI-Admin (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/reference/resource.md This example shows how to configure a `Model` resource with essential properties like the menu `label`, the underlying TortoiseORM `model`, page titles, and `filters`. It includes an example of defining search and date filters for the resource's table view. ```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"), ] ``` -------------------------------- ### Install fastapi-admin-pro with pip Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/pro/installation.md Installs the fastapi-admin-pro package directly from the Git repository using pip. This method requires a GitHub personal access token (GH_TOKEN) to authenticate access to the repository. ```shell > pip install git+https://${GH_TOKEN}@github.com/fastapi-admin/fastapi-admin-pro.git ``` -------------------------------- ### Install fastapi-admin via pip (Shell) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/index.md Installs the fastapi-admin library using the pip package manager. This command downloads and installs the necessary files from PyPI. ```shell pip install fastapi-admin ``` -------------------------------- ### Add fastapi-admin-pro to requirements.txt Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/pro/installation.md Adds the fastapi-admin-pro package to a requirements.txt file, specifying the Git repository URL. When installing dependencies from this file using pip, the GH_TOKEN environment variable will be used for authentication. ```shell -e https://${GH_TOKEN}@github.com/fastapi-admin/fastapi-admin-pro.git#egg=fastapi-admin-pro ``` -------------------------------- ### Installing fastapi-admin Pro Version (Shell) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/pro/upgrade.md This command installs the fastapi-admin pro version directly from its Git repository using pip, requiring a GitHub token for authentication. ```shell pip install git+https://${GH_TOKEN}@github.com/fastapi-admin/fastapi-admin-pro.git ``` -------------------------------- ### Configure fastapi-admin on FastAPI startup Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/reference/index.md This snippet demonstrates how to initialize the fastapi-admin application (`admin_app`) within the `startup` event handler of a FastAPI application. It shows how to create a Redis connection pool and pass it, along with other configuration options like logo URL, template folders, and login providers, to the `admin_app.configure()` method. This ensures the admin application is set up asynchronously when the FastAPI app starts. ```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, ) ``` -------------------------------- ### Defining Fields for a Model Resource in FastAPI-Admin (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/reference/resource.md This example illustrates how to define the `fields` list for a `Model` resource. It shows how to include simple string field names for auto-mapping and how to use the `Field` class for custom display and input widgets, such as `displays.InputOnly` for password and `inputs.Image` for avatar. ```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 FastAPI-Admin Template Folders (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/custom/page.md Configures the FastAPI-Admin application to use a specific directory ('templates') for loading HTML templates. This setup is typically performed 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"]) ``` -------------------------------- ### Adding Toolbar Actions in FastAPI Admin Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/reference/resource.md Illustrates how to add custom actions to the toolbar located at the top right of the resource table in the FastAPI admin panel. This example adds import and export actions. ```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 ``` -------------------------------- ### Defining the Base Action Model (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/custom/action.md Defines the base Pydantic model for actions in FastAPI-Admin, specifying common attributes like icon, label, name, method, and ajax. Includes a validator to ensure `ajax` is only False when the 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") ``` -------------------------------- ### Customizing Display Widget for Datetime (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/custom/widget.md This example shows how to create a custom display widget for datetime and date objects by inheriting from `Display`. It overrides the `render` method to format the date/datetime value using the `pendulum` library before passing it to the superclass's render method, allowing for custom date/time 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, ) ``` -------------------------------- ### Custom ComputeField Implementation (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/reference/resource.md Provides an example of implementing a custom ComputeField called RestDays. It overrides the get_value method to calculate the remaining days based on a date field value. ```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 ``` -------------------------------- ### Customizing Model Column Attributes (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/reference/resource.md Shows how to add custom HTML attributes to specific columns in a Model resource's table by overriding the asynchronous column_attributes method. The example adds a CSS class to 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) ``` -------------------------------- ### Customizing Filter Widget for Search (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/custom/widget.md This example shows how to create a custom filter widget for search functionality by inheriting from the `Filter` class. The `Search` class defines a template and customizes the `__init__` method to handle different search modes ('equal', 'contains', etc.), adjusting the filter name passed to the superclass based on the selected mode. ```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) ``` -------------------------------- ### Customizing Model Row Attributes (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/reference/resource.md Explains how to add custom HTML attributes to table rows in a Model resource by overriding the asynchronous row_attributes method. The example adds a CSS class based on the object's 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) ``` -------------------------------- ### Customizing Cell Attributes in FastAPI Admin (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/reference/resource.md Demonstrates how to dynamically add HTML attributes to table cells based on the row object and column field by overriding the `cell_attributes` method. The example shows how to apply a specific CSS class to the 'id' column. ```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) ``` -------------------------------- ### Implementing a Custom ComputeField (RestDays) in FastAPI-Admin (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/reference/resource.md This example demonstrates how to create a custom `ComputeField` subclass, `RestDays`, by overriding the `get_value` method. It calculates the number of days remaining based on a date field in the object, returning 0 if the date is in the past. ```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 ``` -------------------------------- ### Adding Custom Column Attributes Based on Field in FastAPI-Admin (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/reference/resource.md This example shows how to customize the HTML attributes of table columns in a `Model` resource's list view by overriding the `column_attributes` method. It demonstrates how to conditionally add a CSS class (`w-50`) to the column corresponding to the `content` field. ```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) ``` -------------------------------- ### Defining the Base Action Class in FastAPI Admin (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/custom/action.md This Python class defines the structure and validation for a standard row action in FastAPI Admin. It includes fields for icon, label, name, HTTP method, and AJAX behavior, with a validator ensuring that AJAX is only false for GET requests. ```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") ``` -------------------------------- ### Registering a Model Resource (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/reference/resource.md Demonstrates registering a Model resource using @app.register. It shows configuring the resource with a menu label, the associated TortoiseORM model, page titles, and defining filters using built-in filter types like Search and Date. ```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"), ] ``` -------------------------------- ### Configuring fastapi-admin on FastAPI Startup (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/reference/index.md This snippet demonstrates how to configure the fastapi-admin application within a FastAPI startup event handler. It initializes a Redis connection using aioredis and calls `admin_app.configure` with parameters like logo URL, template folders, authentication providers (UsernamePasswordProvider), and the Redis instance. This configuration must happen within an asyncio loop context, typically during application startup. Requires fastapi, fastapi-admin, and aioredis. ```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, ) ``` -------------------------------- ### Configuring AdminLogProvider in FastAPI Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/reference/admin_log.md Shows how to add the AdminLogProvider to the list of providers when configuring the FastAPI Admin application during the startup event. It requires importing FastAPI, admin_app, AdminLogProvider, and a Log model. ```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)] ) ``` -------------------------------- ### Configuring Username/Password Login with FastAPI-Admin (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/reference/login.md Demonstrates how to add the UsernamePasswordProvider to the fastapi-admin configuration during application startup. This enables login using a username and password against the specified admin_model. ```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, ) ] ) ``` -------------------------------- ### Registering a Link Resource (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/reference/resource.md Demonstrates how to register a simple Link resource in FastAPI Admin using the @app.register decorator. It shows setting the menu label, icon, and URL for a navigation link. ```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" ``` -------------------------------- ### Configuring FastAPI Admin with SearchProvider (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/reference/global_search.md This snippet demonstrates how to configure the fastapi-admin application to include the SearchProvider. It imports the necessary modules, creates a FastAPI application, and configures the admin app within the startup event, adding the SearchProvider to the list of providers. ```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()] ) ``` -------------------------------- ### Configuring Global Search with SearchProvider (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/reference/global_search.md This snippet demonstrates how to add the SearchProvider to the fastapi-admin application configuration within the startup event handler. This action enables the global search feature for the admin interface. ```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()] ) ``` -------------------------------- ### Creating Text Input Widget in Python Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/custom/widget.md Demonstrates creating a text input widget by inheriting Input. Explains the use of input_type and the parameters handled in the __init__ method (help_text, default, null, placeholder, disabled). ```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, ) ``` -------------------------------- ### Configuring OAuth2 Login with FastAPI-Admin Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/reference/login.md Shows how to configure OAuth2 providers like GitHub and Google for admin login. This involves adding instances of `GitHubProvider` and `GoogleProvider` (or similar custom providers) to the `providers` list during `admin_app.configure`, providing the admin model and client credentials. ```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", ), ] ) ``` -------------------------------- ### Configuring Admin Log Provider in FastAPI Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/reference/admin_log.md This snippet demonstrates how to add the AdminLogProvider to the fastapi-admin application configuration during the FastAPI application's startup event. It shows the necessary imports and the call to `admin_app.configure` with the provider and a custom Log model. ```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)] ) ``` -------------------------------- ### Defining the AbstractLog Model Structure Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/reference/admin_log.md Provides the structure for the AbstractLog model, which serves as a base class for the user's Log model. It includes fields for the admin, content, resource, action, and creation timestamp, and specifies metadata for ordering. ```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"] ``` -------------------------------- ### Configuring FileUpload and Using in Model Field - Python Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/reference/file_upload.md This snippet demonstrates how to initialize the FileUpload class with a specified upload directory and then integrate it into a model definition for an image field, using it as the input handler. ```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), ), ] ``` -------------------------------- ### Configuring OAuth2 Login with FastAPI-Admin (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/reference/login.md Shows how to configure fastapi-admin to support OAuth2 login via providers like GitHub and Google by adding them to the providers list during startup. Requires client ID, client secret, and potentially a 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", ), ] ) ``` -------------------------------- ### Creating a Dropdown Menu in FastAPI Admin (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/reference/resource.md Shows how to group related resources under a dropdown menu in the admin interface by creating a class that inherits from `Dropdown` and listing the resources in the `resources` attribute. ```python @app.register class Content(Dropdown): label = "Content" icon = "fas fa-bars" resources = [ProductResource, CategoryResource] ``` -------------------------------- ### Configuring Username/Password Login with FastAPI-Admin Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/reference/login.md Demonstrates how to enable the built-in `UsernamePasswordProvider` for login in fastapi-admin. This requires adding the provider instance to the `providers` list during the `admin_app.configure` call, specifying the admin model. ```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, ) ] ) ``` -------------------------------- ### Registering a Link Resource in FastAPI-Admin (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/reference/resource.md This snippet shows how to define and register a `Link` resource using the `@app.register` decorator. A `Link` resource creates a menu item with a specific label, icon, and target URL within the admin interface. ```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" ``` -------------------------------- ### Implementing Search Filter Widget in Python Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/custom/widget.md Shows how to create a search filter widget by inheriting Filter. Explains the template attribute and the __init__ method which handles parameters like name, label, search_mode, placeholder, and null, adjusting the name based on the search mode. ```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) ``` -------------------------------- ### Enabling Notification Provider in FastAPI-Admin Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/reference/notification.md This snippet shows how to integrate the NotificationProvider into your FastAPI application's startup event to enable the notification center feature. ```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] ) ``` -------------------------------- ### Adding Toolbar Actions in FastAPI Admin (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/reference/resource.md Illustrates how to add custom actions, such as import and export, to the resource toolbar by overriding the `get_toolbar_actions` method and appending `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 ``` -------------------------------- ### Configuring Template Folders in FastAPI-Admin Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/custom/page.md This snippet demonstrates how to configure the template folders for `fastapi-admin` during the application startup. It shows how to pass a list of template directory paths to the `configure` method of the admin app, allowing it to find and render HTML templates. ```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"]) ``` -------------------------------- ### Configuring PermissionProvider in FastAPI App Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/reference/permission.md Configures the FastAPI application to use the PermissionProvider from fastapi_admin.providers.permission during the application startup event, integrating the defined Admin, Resource, and Permission models for permission management. ```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, Resource, Permission, ), ] ) ``` -------------------------------- ### Initialize Display Widget (under DateDisplay section) (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/reference/widget/display.md This code snippet, found under the documentation for the DateDisplay widget, shows the initialization of a `DatetimeDisplay` class. It accepts an optional `format_` string. The surrounding text indicates DateDisplay is for date values and defaults to '%Y-%m-%d', but the code shown is for `DatetimeDisplay`. ```python class DatetimeDisplay(Display): def __init__(self, format_: str = constants.DATETIME_FORMAT): ``` -------------------------------- ### Customizing Input Widget for Text (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/custom/widget.md This snippet demonstrates creating a custom input widget specifically for text input by inheriting from the `Input` class. It defines the default `input_type` as 'text' and customizes the `__init__` method to accept parameters like `help_text`, `default`, `null`, `placeholder`, and `disabled`, passing them to the superclass constructor. ```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, ) ``` -------------------------------- ### Defining Base Widget Class in Python Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/custom/widget.md Explains the base Widget class, its purpose as a parent for display, input, and filter widgets, its use of Jinja2Templates, and the render method for rendering values using a template. Mentions the context parameter in __init__. ```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) ``` -------------------------------- ### Configuring FileUpload and Using in Model Field - Python Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/reference/file_upload.md This snippet demonstrates how to initialize the basic FileUpload class by specifying the directory where files should be stored. It then shows how to integrate this configured upload instance into a model field definition, specifically using it with an inputs.Image input widget for an 'avatar' field. ```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 PermissionProvider Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/reference/permission.md Shows how to integrate the permission system into your FastAPI application by configuring the `fastapi_admin` app during startup. This involves adding the `PermissionProvider` and associating it with your custom `Admin`, `Resource`, and `Permission` models to enable permission checks. ```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, Resource, Permission, ), ] ) ``` -------------------------------- ### Defining the Base Widget Class (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/custom/widget.md This snippet defines the base `Widget` class, which provides common functionality for all widgets, including template rendering using Jinja2. The `__init__` method stores context, and the `render` method handles rendering the widget's value using a specified template, escaping newlines and other special characters for JSON output. ```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) ``` -------------------------------- ### Defining Abstract Admin Log Model Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/reference/admin_log.md This code defines the AbstractLog model, which serves as the base class for custom log models used with AdminLogProvider. It specifies the required fields like admin, content, resource, action, and created_at, along with Meta options for ordering. ```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"] ``` -------------------------------- ### Enabling NotificationProvider in FastAPI-Admin Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/reference/notification.md This snippet shows how to integrate the NotificationProvider into your FastAPI application by adding it to the list of providers when configuring the admin app. ```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] ) ``` -------------------------------- ### Creating a Dropdown Menu Resource in FastAPI Admin Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/reference/resource.md Defines a dropdown resource that groups other resources (like Model or Link resources) under a common label and icon in the FastAPI admin sidebar, allowing for nested navigation. ```python @app.register class Content(Dropdown): label = "Content" icon = "fas fa-bars" resources = [ProductResource, CategoryResource] ``` -------------------------------- ### Defining Model Fields with Field Objects (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/reference/resource.md Shows how to define fields for a Model resource, including using the Field object for custom display and input widgets like Password, Email, and Image. It also mentions using simple strings for auto-mapping based on field type. ```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", ] ``` -------------------------------- ### Broadcasting Notifications via Provider Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/reference/notification.md This code demonstrates how to send a notification directly from within your application using the broadcast method of the NotificationProvider instance. It shows the structure of the data dictionary required. ```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) ``` -------------------------------- ### Customizing Datetime Display Widget in Python Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/custom/widget.md Shows how to create a custom display widget for datetime and date objects by inheriting Display and overriding render. Explains how it formats the date/time using pendulum and calls the parent render method. Mentions the format_ parameter. ```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, ) ``` -------------------------------- ### Registering a Custom Page as a Link Resource in FastAPI-Admin Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/custom/page.md This snippet shows how to register a custom page, defined by a router, as a navigation link within the `fastapi-admin` interface. It uses the `Link` resource type to create a menu item with a specified label, icon, and URL that points to the custom page's route. ```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" ``` -------------------------------- ### Initialize DatetimeDisplay in Python Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/reference/widget/display.md Initializes the `DatetimeDisplay` class, a display widget used to format datetime values for presentation. It accepts an optional `format_` string parameter to specify the output format, defaulting to the value defined in `constants.DATETIME_FORMAT`. ```Python class DatetimeDisplay(Display): def __init__(self, format_: str = constants.DATETIME_FORMAT): ``` -------------------------------- ### ToolbarAction Class Definition (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/reference/resource.md Shows the definition of the ToolbarAction class, which inherits from Action and is used by model.get_toolbar_actions. It includes an optional class_ attribute for adding CSS classes. ```python class ToolbarAction(Action): class_: Optional[str] ``` -------------------------------- ### Initialize DatetimeDisplay Widget (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/reference/widget/display.md Initializes the DatetimeDisplay widget in FastAPI Admin. This widget is used to format and display datetime values. It accepts an optional `format_` string parameter to specify the output format, defaulting to a standard datetime format. ```python class DatetimeDisplay(Display): def __init__(self, format_: str = constants.DATETIME_FORMAT): ``` -------------------------------- ### Add Site Search Provider in FastAPI Admin Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/pro/exclusive.md Enable site-wide search functionality within the admin interface by including the SearchProvider during application configuration. ```python await admin_app.configure(providers=[SearchProvider()]) ``` -------------------------------- ### Defining FileUpload Class for Custom Uploads in Python Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/zh/docs/custom/file_upload.md This Python class provides a base structure for implementing custom file upload backends. It includes methods for initializing with upload directory, allowed extensions, max size, and prefix, saving files asynchronously, and handling the upload process with size and extension validation. ```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) ``` -------------------------------- ### Defining the ToolbarAction Class in FastAPI-Admin (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/reference/resource.md This snippet provides the definition for the `ToolbarAction` class, which is used for actions displayed in the toolbar of a model's list view. It inherits from `Action` and includes an optional `class_` attribute for styling. ```python class ToolbarAction(Action): class_: Optional[str] ``` -------------------------------- ### Configure OAuth2 Providers in FastAPI Admin Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/pro/exclusive.md Integrate OAuth2 authentication providers like GitHub and Google by adding their respective providers during the admin application configuration, including necessary client IDs, secrets, and redirect URIs. ```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", ), ] ) ``` -------------------------------- ### Uninstalling fastapi-admin Open Source (Shell) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/pro/upgrade.md This command uninstalls the existing open source version of the fastapi-admin package using pip. ```shell pip uninstall fastapi-admin ``` -------------------------------- ### Defining the Toolbar Action Model (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/custom/action.md Defines the Pydantic model for toolbar actions, inheriting from the base `Action` model and adding an optional `class_` attribute for CSS classes or similar purposes. ```python class ToolbarAction(Action): class_: Optional[str] ``` -------------------------------- ### Add Admin Log Provider in FastAPI Admin Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/pro/exclusive.md Enable logging of create, update, and delete actions performed by admin users by adding the AdminLogProvider during application configuration. ```python await admin_app.configure(providers=[AdminLogProvider(Log)]) ``` -------------------------------- ### Create Custom Page Router with Authentication (Python) Source: https://github.com/fastapi-admin/fastapi-admin.github.io/blob/main/docs/en/docs/custom/page.md Defines a FastAPI router endpoint ('/') within the admin application that renders a specific template ('dashboard.html'). It uses the 'get_current_admin' dependency to ensure the user is logged in before accessing the page. ```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}) ```