### Integrate with LightStar (Python) Source: https://docs.brilliance-admin.com/how-to-start.txt Provides an example of integrating the admin panel with a LightStar application by mounting it to a specific route. ```python from lightstar import LightStar, Mount from your_project.admin import admin_app app = LightStar( routes=[ Mount('/admin', admin_app), ], ) ``` -------------------------------- ### Integrate with Starlette (Python) Source: https://docs.brilliance-admin.com/how-to-start.txt Demonstrates mounting the admin application to a Starlette application. This is useful for building ASGI applications with Starlette. ```python from starlette.applications import Starlette from starlette.routing import Mount from your_project.admin import admin_app app = Starlette( routes=[ Mount('/admin', admin_app), ], ) ``` -------------------------------- ### Integrate with Django ASGI (Python) Source: https://docs.brilliance-admin.com/how-to-start.txt Shows how to integrate the brilliance-admin panel with a Django project using an ASGI application. This example handles requests to the '/admin' path separately from the main Django app. ```python import os from django.core.asgi import get_asgi_application from your_project.admin import admin_app os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_project.settings') django_app = get_asgi_application() async def application(scope, receive, send): if scope['type'] == 'http' and scope.get('path', '').startswith('/admin'): await admin_app(scope, receive, send) return await django_app(scope, receive, send) ``` -------------------------------- ### Install brilliance-admin Package Source: https://docs.brilliance-admin.com/how-to-start.txt Installs the brilliance-admin package using pip. This is the first step to get started with the admin panel. ```shell pip install brilliance-admin ``` -------------------------------- ### Integrate with FastAPI (Python) Source: https://docs.brilliance-admin.com/how-to-start.txt Shows how to mount the generated admin application to a FastAPI application. This allows the admin panel to be accessible at a specific URL path. ```python from fastapi import FastAPI from your_project.admin import admin_app app = FastAPI() app.mount('/admin', admin_app) ``` -------------------------------- ### Define AdminSchema Instance (Python) Source: https://docs.brilliance-admin.com/how-to-start.txt Demonstrates how to create an instance of `AdminSchema` for configuring the admin panel. This includes defining models, authentication, and groups. It requires the `brilliance_admin.schema` module. ```python from brilliance_admin import schema # SQLAlchemy example class UserAdmin(sqlalchemy.SQLAlchemyAdmin): model = User admin_schema = schema.AdminSchema( title='Admin Panel', auth=YourAdminAuthentication(), groups=[ schema.Group(slug='example', categories=[UserAdmin()]) ], ) admin_app = admin_schema.generate_app() ``` -------------------------------- ### Full Brilliance Admin Example with Schema and Admin Configuration Source: https://docs.brilliance-admin.com/integrations/sqlalchemy/table_schema.txt A comprehensive example showcasing the integration of a custom SQLAlchemyFieldsSchema with display fields and the SQLAlchemyAdmin configuration. It includes search fields, ordering fields, and table filters with specific field types. ```python from brilliance_admin import schema, sqlalchemy from brilliance_admin.translations import TranslateText as _ from myapp.models import User from myapp.database import db class UserSchema(sqlalchemy.SQLAlchemyFieldsSchema): model = User @schema.function_field(label=_('full_name')) async def get_full_name(self, record, user, **kwargs): return f"{record.first_name} {record.last_name}" list_display = ['id', 'username', 'email', 'get_full_name', 'is_active'] class UserAdmin(sqlalchemy.SQLAlchemyAdmin): model = User db_async_session = db.async_session slug = 'users' title = _('users') icon = 'mdi-account-details' search_fields = ['username', 'email'] ordering_fields = ['id', 'created_at'] table_schema = UserSchema() table_filters = sqlalchemy.SQLAlchemyFieldsSchema( model=User, created_at=schema.DateTimeField(range=True), is_active=schema.BooleanField(), ) ``` -------------------------------- ### Define Fields Schema as an Instance Source: https://docs.brilliance-admin.com/fields_schema/fields_schema.txt This example shows how to create a FieldsSchema instance by passing fields directly to the constructor. This is useful for simpler schemas, such as those used in action forms or filters. ```python from brilliance_admin import schema form_schema = schema.FieldsSchema( new_password=schema.StringField(label='New password', min_length=6), is_active=schema.BooleanField(label='Active'), ) ``` -------------------------------- ### Specify Fields Order in Schema Source: https://docs.brilliance-admin.com/fields_schema/fields_schema.txt This example shows how to explicitly define the order and selection of fields within a FieldsSchema by setting the `fields` attribute. If omitted, fields are auto-populated from class attributes. ```python from brilliance_admin.schema import FieldsSchema class TerminalSchema(FieldsSchema): fields = ['title', 'description', 'status', 'merchant_id', 'currency_id'] ``` -------------------------------- ### Generate FastAPI App with Options (Python) Source: https://docs.brilliance-admin.com/admin-schema/main.txt This code example shows how to generate the FastAPI application from an existing `AdminSchema` instance, with optional arguments to enable debug mode and include API documentation interfaces like Swagger UI. ```python admin_app = admin_schema.generate_app( debug=True, include_docs=True, ) ``` -------------------------------- ### Implement get_list to return paginated data (Python) Source: https://docs.brilliance-admin.com/admin-schema/tables.txt Provides an example implementation of the `get_list` method within a `CategoryTable` subclass. It demonstrates how to process `ListData` (containing pagination, search, filters, and ordering) and return a `TableListResult` with the fetched rows and total count. ```python from brilliance_admin.schema.table.table_models import ListData, TableListResult async def get_list(self, list_data: ListData, user, language_context, admin_schema) -> TableListResult: # your data fetching logic rows = [ {'id': 1, 'username': 'admin', 'email': 'admin@example.com'}, {'id': 2, 'username': 'user', 'email': 'user@example.com'}, ] return TableListResult(rows=rows, total=len(rows)) ``` -------------------------------- ### SQLAlchemy JWT Admin Authentication Setup (Python) Source: https://docs.brilliance-admin.com/integrations/sqlalchemy/authentication.txt Sets up SQLAlchemyJWTAdminAuthentication with provided credentials and a password validator. Requires PyJWT library. Takes JWT secret, async session factory, user model, and a password validator function as input. ```python from brilliance_admin import schema, sqlalchemy from app.your_models import User, UserDAO # Your way to verify password async def password_validator(user: User, password: str) -> bool: return await UserDAO.verify_password(plain_password=password, hashed_password=user.password) auth = sqlalchemy.SQLAlchemyJWTAdminAuthentication( secret='YOUR_JWT_SECRET', db_async_session=auth_db.async_session, user_model=User, password_validator=password_validator, ) admin_schema = schema.AdminSchema( ... auth=auth, ) ``` -------------------------------- ### Fake Admin Authentication Implementation in Python Source: https://docs.brilliance-admin.com/authentication.txt Provides a fake implementation of Brilliance Admin's authentication system. It defines 'login' to validate 'admin' credentials and 'authenticate' to return a user object. This example demonstrates how to extend the `AdminAuthentication` class and handle `AuthData` and `AuthResult`. ```python from brilliance_admin.auth import AdminAuthentication, AuthData, AuthResult, UserABC, UserResult class FakeAdminAuthentication(AdminAuthentication): async def login(self, data: AuthData) -> AuthResult: if data.username != 'admin' or data.password != 'admin': raise AdminAPIException(APIError(code='user_not_found'), status_code=401) return AuthResult(token='test', user=UserResult(username='test_admin')) async def authenticate(self, headers: dict) -> UserABC: return UserABC(username='test_admin') ``` -------------------------------- ### Synchronous Password Validator Example (Python) Source: https://docs.brilliance-admin.com/integrations/sqlalchemy/authentication.txt Demonstrates using a synchronous lambda function as a password validator. This is an alternative to an async function for password verification. It takes user and password as input and returns a boolean. ```python password_validator=lambda user, pwd: verify_password(pwd, user.hashed_password) ``` -------------------------------- ### Create a Table Action with a Form Schema in Python Source: https://docs.brilliance-admin.com/admin-schema/table_actions.txt This Python example illustrates how to create a table action that requires user input before execution. The `@admin_action` decorator is used with the `form_schema` parameter to define a `FieldsSchema` for collecting data, such as a new password. ```python @admin_action( title='Change password', form_schema=schema.FieldsSchema( new_password=schema.StringField(label='New password', min_length=6), ), ) async def change_password(self, action_data: ActionData): new_password = action_data.form_data['new_password'] for pk in action_data.pks: await update_user_password(pk, new_password) return ActionResult('Password changed') ``` -------------------------------- ### Exclude Fields from Schema with exclude_fields Source: https://docs.brilliance-admin.com/fields_schema/fields_schema.txt This example demonstrates how to exclude specific fields from a FieldsSchema by listing their slugs in the `exclude_fields` attribute. Excluded fields will not be included even if present in the `fields` list. ```python from brilliance_admin.schema import FieldsSchema class TerminalSchema(FieldsSchema): exclude_fields = ['internal_code', 'legacy_field'] ``` -------------------------------- ### ChoiceField with Enum Source: https://docs.brilliance-admin.com/fields_schema/table_fields.txt Defines a ChoiceField using an Enum class for predefined options. The Enum must have 'value', 'label', and optionally 'tag_color' properties. This example shows how to create a StatusEnum and use it to configure a ChoiceField. ```python from enum import Enum class StatusEnum(Enum): ACTIVE = 'active' BLOCKED = 'blocked' @property def label(self): return self.value.capitalize() @property def tag_color(self): return {'active': 'green', 'blocked': 'red'}.get(self.value) status = schema.ChoiceField(label='Status', choices=StatusEnum) ``` -------------------------------- ### Create a Table Action Without Row Selection in Python Source: https://docs.brilliance-admin.com/admin-schema/table_actions.txt This Python example demonstrates how to create a table action that can be executed without selecting any rows. By setting `allow_empty_selection=True` in the `@admin_action` decorator, actions like 'Generate report' or 'Create new' can be triggered, utilizing table filters if available. ```python @admin_action( title='Generate report', allow_empty_selection=True, ) async def generate_report(self, action_data: ActionData): # action_data.pks will be empty # action_data.filters contains current table filters report = await build_report(action_data.filters) return ActionResult(persistent_message='Report generated') ``` -------------------------------- ### FunctionField for Computed Values Source: https://docs.brilliance-admin.com/fields_schema/table_fields.txt Demonstrates how to use FunctionField to create computed, read-only fields. The value is generated by an async function. This example shows a 'full_name' field computed from 'first_name' and 'last_name'. ```python from brilliance_admin import schema from brilliance_admin.translations import TranslateText as _ class UsersSchema(schema.FieldsSchema): id = schema.IntegerField(label='ID') username = schema.StringField(label='Username') @schema.function_field(label='Full Name') async def full_name(self, record, user, **kwargs): return f"{record['first_name']} {record['last_name']}" list_display = ['id', 'username', 'full_name'] ``` -------------------------------- ### generate_app() Method Source: https://docs.brilliance-admin.com/admin-schema/main.txt Generates a FastAPI ASGI application from the AdminSchema configuration. ```APIDOC ## generate_app() Method ### Description Generates a FastAPI ASGI application. This application can be mounted to your backend at any desired path. ### Method `generate_app()` ### Parameters - **debug** (boolean) - Optional - Enable debug mode. - **default_cors** (boolean) - Optional - Add CORS middleware (enabled by default). - **include_docs** (boolean) - Optional - Enable Swagger UI at `/docs`. - **include_scalar** (boolean) - Optional - Enable Scalar documentation. - **include_redoc** (boolean) - Optional - Enable ReDoc documentation. ### Usage Example ```python admin_app = admin_schema.generate_app( debug=True, include_docs=True, ) ``` ::: tip All string parameters (`title`, `description`, `login_greetings_message`) support `TranslateText` for i18n. ::: ``` -------------------------------- ### Implement UsersTable by subclassing CategoryTable (Python) Source: https://docs.brilliance-admin.com/admin-schema/tables.txt Demonstrates subclassing `CategoryTable` to create a custom table for users. It includes configuration for search, ordering, and schema definition, along with a placeholder for the `get_list` method. ```python from brilliance_admin import schema from brilliance_admin.schema.table.category_table import CategoryTable from brilliance_admin.schema.table.table_models import ListData, TableListResult class UsersTable(schema.CategoryTable): slug = 'users' title = 'Users' icon = 'mdi-account-group' pk_name = 'id' search_enabled = True search_help = 'Search by name or email' ordering_fields = ['id', 'created_at'] default_ordering = '-created_at' table_schema = UsersSchema() table_filters = UsersFiltersSchema() async def get_list(self, list_data: ListData, user, language_context, admin_schema) -> TableListResult: # fetch and return your data here ... ``` -------------------------------- ### Configure Custom Static Files Prefix in Python Source: https://docs.brilliance-admin.com/customization/main.txt This Python code snippet demonstrates how to configure Brilliance Admin to use custom static files by specifying a `static_prefix`. This is useful when hosting frontend assets on a CDN or a custom location. It requires an `AdminSchema` object and potentially authentication and category configurations. ```python admin_schema = schema.AdminSchema( title='My Admin', auth=auth, categories=[...], static_prefix='https://cdn.example.com/admin-static/', ) ``` -------------------------------- ### Define Custom Themes for Brilliance Admin (Python) Source: https://docs.brilliance-admin.com/customization/colors.txt Shows how to define custom themes for Brilliance Admin by creating a list of theme objects. Each theme object includes a name, a dark mode flag, and a dictionary of color overrides. ```python custom_themes = [ { "name": "pinkLight", "dark": False, "colors": { "light2": "#FBF5F7", "light3": "#E8D0D8", "secondary": "#C4A0AE", "darken1": "#A88392", "primary": "#D46B8A", "darken3": "#6B4458", "darken4": "#4A2E3D", "accent": "#D4A9B8", "error": "#C26161", "info": "#7BA4C9", "success": "#7BAF7F", "warning": "#C9A84E", }, }, { "name": "pinkDark", "dark": True, "colors": { "surface": "#160D12", "on-surface": "#F0E0E8", "light2": "#2E1825", "light3": "#E8A0B8", "secondary": "#5C3350", "darken1": "#D4789A", "primary": "#D46B8A", "on-primary": "#FFFFFF", "darken3": "#421E35", "darken4": "#0E0609", "accent": "#D4A9B8", "error": "#C26161", "info": "#7BA4C9", "success": "#7BAF7F", "warning": "#C9A84E", }, }, ] admin_schema = schema.AdminSchema( title='My Admin', auth=auth, categories=[...], default_theme='pinkDark', custom_themes=custom_themes, ) ``` -------------------------------- ### Create a SmallGraph Component Source: https://docs.brilliance-admin.com/admin-schema/dashboard.txt The `SmallGraph` component is a compact card featuring a sparkline. It displays a title, a main value, a change percentage, and a dictionary of points representing the sparkline data. ```python from brilliance_admin.schema.dashboard.category_dashboard import SmallGraph balance = SmallGraph( title='Wallet balance', value='950 150 558 RUB', change=15, points={'01.05': 5, '05.05': 35, '10.05': 45, '15.05': 30}, ) ``` -------------------------------- ### SQLAlchemy Admin Configuration - Python Source: https://docs.brilliance-admin.com/integrations/sqlalchemy/table_schema.txt Configures a SQLAlchemyAdmin class for the User model, setting up search fields, ordering, and table schema. It requires the SQLAlchemy model and an async session factory. ```python from brilliance_admin import schema, sqlalchemy from brilliance_admin.translations import TranslateText as _ from myapp.models import User from myapp.database import db class UserAdmin(sqlalchemy.SQLAlchemyAdmin): model = User db_async_session = db.async_session slug = 'users' title = _('users') icon = 'mdi-account-details' search_fields = ['username', 'email'] ordering_fields = ['id', 'created_at'] default_ordering = '-id' table_schema = sqlalchemy.SQLAlchemyFieldsSchema(model=User) table_filters = sqlalchemy.SQLAlchemyFieldsSchema( model=User, created_at=schema.DateTimeField(range=True), ) ``` -------------------------------- ### Control Table Column Display with list_display Source: https://docs.brilliance-admin.com/fields_schema/fields_schema.txt This code demonstrates how to use the `list_display` attribute to specify which fields appear as table columns and in what order. This setting is primarily relevant for `table_schema` in `CategoryTable`. ```python from brilliance_admin import schema class UserSchema(schema.FieldsSchema): id = schema.IntegerField(label='ID') username = schema.StringField(label='Username') email = schema.StringField(label='Email') internal_note = schema.StringField(label='Note') # only these fields will appear in the table, in this order list_display = ['id', 'username', 'email'] ``` -------------------------------- ### Implement CRUD operations for CategoryTable (Python) Source: https://docs.brilliance-admin.com/admin-schema/tables.txt Illustrates how to implement optional asynchronous methods (`retrieve`, `create`, `update`) within a `CategoryTable` subclass to enable CRUD functionalities. The `pk_name` must be set for the retrieve operation to be enabled. ```python class CustomTable(schema.CategoryTable): ... async def retrieve(self, pk, user, language_context, admin_schema) -> schema.RetrieveResult: # fetch record by pk return schema.RetrieveResult(data={'id': pk, 'username': 'admin'}) async def create(self, data, user, language_context, admin_schema) -> schema.CreateResult: # create record from data dict return schema.CreateResult(pk=1) async def update(self, pk, data, user, language_context, admin_schema) -> schema.UpdateResult: # update record by pk with data dict return schema.UpdateResult(pk=pk) ``` -------------------------------- ### Create a Custom Dashboard with CategoryDashboard Source: https://docs.brilliance-admin.com/admin-schema/dashboard.txt Implement a custom dashboard by subclassing `CategoryDashboard` and overriding the `get_data` method. This method should return a `DashboardContainer` object that defines the layout and components of your dashboard. Essential attributes like `slug`, `title`, and `icon` must be defined. ```python from brilliance_admin import schema from brilliance_admin.schema.dashboard.category_dashboard import ( DashboardContainer, DashboardData) class MyDashboard(schema.CategoryDashboard): slug = 'dashboard' title = 'Dashboard' icon = 'mdi-chart-bar-stacked' async def get_data(self, data: DashboardData, user) -> DashboardContainer: # build and return your layout here ... ``` -------------------------------- ### Define Admin Panel Schema and Generate App (Python) Source: https://docs.brilliance-admin.com/admin-schema/main.txt This snippet demonstrates how to define the main configuration for the Brilliance Admin Panel using `AdminSchema` and then generate a FastAPI application from this schema. It includes setting the panel title, authentication, categories, and language management. ```python from brilliance_admin import schema admin_schema = schema.AdminSchema( title='My Admin Panel', auth=your_auth, categories=[ YourDashboard(), YourTableCategory(), ], language_manager=schema.LanguageManager( languages={'en': 'English', 'ru': 'Russian'}, locales_dir='locales', ), ) admin_app = admin_schema.generate_app() ``` -------------------------------- ### String Interpolation with TranslateText (Python) Source: https://docs.brilliance-admin.com/translations.txt Insert dynamic values into translated strings using the `%` operator with a dictionary. This method looks up a key in the translation file and substitutes placeholders (e.g., `{name}`) with provided values. Ensure the dictionary keys match the placeholders in the translation string. ```python message = _('greeting') % {'name': 'John'} ``` -------------------------------- ### Configuring Ordering Fields and Default Order Source: https://docs.brilliance-admin.com/integrations/sqlalchemy/table_schema.txt Shows how to define sortable columns in the table header using `ordering_fields` and set a default sorting order (ascending or descending) with `default_ordering`. Descending order is indicated by a leading hyphen. ```python class UserAdmin(sqlalchemy.SQLAlchemyAdmin): model = User db_async_session = db.async_session ordering_fields = ['id', 'username', 'created_at'] default_ordering = '-created_at' ``` -------------------------------- ### Define Category Links in Python Source: https://docs.brilliance-admin.com/admin-schema/category_link.txt Demonstrates how to define internal and external links using the CategoryLink schema in Python. These links are used to populate the sidebar navigation. Absolute URLs open in new tabs, while relative paths navigate within the application. ```python from brilliance_admin import schema class Documentation(schema.CategoryLink): slug = 'docs' title = 'Documentation' icon = 'mdi-book-open-variant' link = 'https://docs.example.com' class GitHubRepo(schema.CategoryLink): slug = 'github' title = 'GitHub' icon = 'mdi-github' link = 'https://github.com/example/repo' ``` -------------------------------- ### Set Default Theme in AdminSchema (Python) Source: https://docs.brilliance-admin.com/customization/colors.txt Demonstrates how to set a default theme for the Brilliance Admin interface using the `AdminSchema` class. This involves passing a theme name string to the `default_theme` parameter. ```python admin_schema = schema.AdminSchema( title='My Admin', auth=auth, categories=[...], default_theme='deepPurpleDark', ) ``` -------------------------------- ### Custom Filter Logic with apply_filter Source: https://docs.brilliance-admin.com/integrations/sqlalchemy/table_schema.txt Demonstrates how to implement custom filtering logic for string fields using the `apply_filter` method. This allows for advanced filtering conditions like case-insensitive matching. ```python class ILikeStringField(schema.StringField): async def apply_filter(self, stmt, value, model, column): return stmt.where(column.ilike(f'%{value}%')) ``` -------------------------------- ### Create a PeriodGraph Component Source: https://docs.brilliance-admin.com/admin-schema/dashboard.txt The `PeriodGraph` component displays a bar chart with a summary value, change percentage, and optional subcards. It requires data for the main value, change, and lists for horizontal and vertical axis labels, along with corresponding values for the bars. ```python from brilliance_admin.schema.dashboard.category_dashboard import ( PeriodGraph, Subcard) period = PeriodGraph( title='Operations for period', value='150 558,01 RUB', change=160, subcards=[ Subcard(title='PayIn', value='24 051 RUB', color='#4CAF50'), Subcard(title='PayOut', value='124 051 RUB', color='#1976D2'), ], horizontal=['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], vertical=['1 400', '1 050', '700', '350', '0'], values=[ [25, 35], [35, 45], [8, 40], [85, 45], [40, 35], ], ) ``` -------------------------------- ### Auto-generate Schema from SQLAlchemy Model Source: https://docs.brilliance-admin.com/integrations/sqlalchemy/fields_schema.txt Demonstrates how to automatically generate a schema from a SQLAlchemy model using SQLAlchemyFieldsSchema. This is useful for creating table schemas or filters in SQLAlchemyAdmin. ```python from my_app import sqlalchemy from my_app.models import User table_schema = sqlalchemy.SQLAlchemyFieldsSchema(model=User) ``` -------------------------------- ### Implement a Table Action with Confirmation in Python Source: https://docs.brilliance-admin.com/admin-schema/table_actions.txt This Python snippet shows how to add a confirmation dialog before executing a table action. The `confirmation_text` parameter in the `@admin_action` decorator prompts the user for confirmation, which is useful for potentially destructive operations like deletion. ```python @admin_action( title='Delete', confirmation_text='Are you sure you want to delete selected items?', base_color='red-lighten-2', variant='outlined', ) async def delete(self, action_data: ActionData): for pk in action_data.pks: await delete_item(pk) return ActionResult('Deleted successfully') ``` -------------------------------- ### AdminSchema Configuration Source: https://docs.brilliance-admin.com/admin-schema/main.txt Defines the main configuration object for the Brilliance Admin Panel, including title, authentication, and categories. ```APIDOC ## AdminSchema Configuration ### Description This schema is the main configuration object that describes the entire admin panel, including its title, authentication, and categories (tables, dashboards, links, etc.). ### Parameters #### Main Config - **categories** (list) - Required - List of root categories (tables, dashboards, links) displayed in the sidebar. - **auth** (object) - Required - Authentication provider configuration. - **language_manager** (object) - Optional - i18n configuration for translations. #### Info - **title** (string) - Admin panel title, shown in the navbar and browser tab. - **description** (string) - Panel description. - **login_greetings_message** (string) - Message displayed on the login page. #### Customization - **favicon_image** (string) - URL to the favicon. - **logo_image** (string) - URL to the logo image in the navbar. - **navbar_density** (string) - Sidebar density: `'default'`, `'comfortable'` or `'compact'`. - **default_theme** (string) - Default color theme name. - **custom_themes** (list) - List of custom color theme objects. #### Urls - **main_page** (string) - Redirect path after login and when clicking the logo (e.g., `'/group/category'`). - **backend_prefix** (string) - Custom backend URL prefix (auto-detected if not set). - **static_prefix** (string) - Custom static files URL prefix (auto-detected if not set). ### Usage Example ```python from brilliance_admin import schema admin_schema = schema.AdminSchema( title='My Admin Panel', auth=your_auth_provider, # Replace with your actual auth provider categories=[ # Your Dashboard(), # YourTableCategory(), ], language_manager=schema.LanguageManager( languages={'en': 'English', 'ru': 'Russian'}, locales_dir='locales', ), ) ``` ``` -------------------------------- ### Create a ChartData Component using ChartJS Source: https://docs.brilliance-admin.com/admin-schema/dashboard.txt The `ChartData` component allows embedding any ChartJS compatible chart. You provide the chart type, data, and options directly in the ChartJS format. You can also specify the height and width of the chart. ```python from brilliance_admin.schema.dashboard.category_dashboard import ChartData chart = ChartData( type='line', height=300, data={ 'labels': ['Jan', 'Feb', 'Mar', 'Apr'], 'datasets': [{ 'label': 'Revenue', 'data': [65, 59, 80, 81], 'borderColor': '#3b82f6', }], }, options={ 'responsive': True, 'plugins': {'legend': {'position': 'top'}}, }, ) ``` -------------------------------- ### Return Feedback from Table Actions in Python Source: https://docs.brilliance-admin.com/admin-schema/table_actions.txt This Python code shows different ways to return feedback to the user after a table action is executed using `ActionResult`. It covers short form text messages, persistent messages, and custom `ActionMessage` objects with specified types and positions. ```python # Short form — text converts to ActionMessage automatically return ActionResult('Operation completed') # With persistent message (stays on screen, does not auto-hide) return ActionResult(persistent_message='Report generated successfully') # Full form with ActionMessage for custom type and position from brilliance_admin.schema.table.admin_action import ActionMessage return ActionResult( message=ActionMessage( text='Done', type='success', # 'success', 'error', 'warning', 'info' position='top-center', ), ) ``` -------------------------------- ### Mark Strings for Translation with TranslateText (Python) Source: https://docs.brilliance-admin.com/translations.txt Use the `TranslateText` class, aliased as `_`, to mark strings for translation. The actual translation is performed at render time based on the user's current language. This function does not require external dependencies beyond the `brilliance_admin` library. ```python from brilliance_admin.translations import TranslateText as _ title = _('dashboard.title') ``` -------------------------------- ### Define Fields Schema as a Class Source: https://docs.brilliance-admin.com/fields_schema/fields_schema.txt This snippet demonstrates how to define a FieldsSchema by subclassing and declaring fields as class attributes. It's suitable for complex schemas where fields are reused across different contexts. ```python from brilliance_admin import schema class PaymentSchema(schema.FieldsSchema): id = schema.IntegerField(label='ID', read_only=True) amount = schema.IntegerField() list_display = [ 'id', 'amount', ] ``` -------------------------------- ### Configure LanguageManager for Translations (Python) Source: https://docs.brilliance-admin.com/translations.txt The `LanguageManager` class loads translation files and resolves text for the current language. It requires a dictionary of supported languages and the directory where locale files are stored. This manager is typically configured within the `AdminSchema`. ```python from brilliance_admin.translations import LanguageManager import schema language_manager = LanguageManager( languages={'en': 'English', 'ru': 'Russian'}, locales_dir='path/to/your/locales', ) admin_schema = schema.AdminSchema( ... language_manager=language_manager, ) ``` -------------------------------- ### Define SQLAlchemy Model with Field Metadata Source: https://docs.brilliance-admin.com/integrations/sqlalchemy/fields_schema.txt Shows how to define a SQLAlchemy model with custom metadata for fields using the 'info' dictionary. This metadata, such as 'label', 'help_text', and 'choices', is used by SQLAlchemyFieldsSchema to configure the generated form fields. ```python import sqlalchemy as sa from enum import Enum class RoleEnum(Enum): ADMIN = "admin" USER = "user" class User(Base): __tablename__ = 'users' id = sa.Column(sa.Integer, primary_key=True) username = sa.Column(sa.String(100), info={'label': 'Username'}) role = sa.Column(sa.String(20), info={ 'label': 'Role', 'choices': RoleEnum, }) ``` -------------------------------- ### Arrange Dashboard Components with DashboardContainer Source: https://docs.brilliance-admin.com/admin-schema/dashboard.txt Use `DashboardContainer` to structure the layout of your dashboard components in a responsive grid. Containers can be nested to create complex layouts, and properties like `cols`, `md`, `lg`, and `sm` control column widths across different screen sizes. ```python DashboardContainer( components=[ DashboardContainer( cols=12, md=6, components=[chart_1], ), DashboardContainer( cols=12, md=6, components=[chart_2], ), ], ) ``` -------------------------------- ### Translation File Structure (YAML) Source: https://docs.brilliance-admin.com/translations.txt Translation files are structured as YAML files, with one file per language, placed in a specified `locales_dir`. Keys in the code (dot-separated) correspond to nested structures within the YAML files. This format allows for easy management and readability of translations. ```yaml dashboard: title: 'Dashboard' greeting: 'Hello, %(name)s!' ``` ```yaml dashboard: title: 'Панель управления' greeting: 'Привет, %(name)s!' ``` -------------------------------- ### Overriding Create Operation in SQLAlchemy Admin - Python Source: https://docs.brilliance-admin.com/integrations/sqlalchemy/table_schema.txt Shows how to override the 'create' method in a SQLAlchemyAdmin class to add custom logic before the default creation process. The custom logic modifies the data before calling the superclass's create method. ```python from brilliance_admin import schema, sqlalchemy from myapp.models import User from myapp.database import db class UserAdmin(sqlalchemy.SQLAlchemyAdmin): model = User db_async_session = db.async_session async def create(self, data, user, language_context, admin_schema) -> schema.CreateResult: # custom logic before create data['created_by'] = user.username return await super().create(data, user, language_context, admin_schema) ``` -------------------------------- ### FunctionField with Specific Type Rendering Source: https://docs.brilliance-admin.com/fields_schema/table_fields.txt Shows how to specify the rendering type for a FunctionField. By passing a field class like BooleanField to the 'type' parameter, the computed value will be rendered accordingly (e.g., as a checkbox icon). ```python @schema.function_field(label=_('is_verified'), type=schema.BooleanField) async def get_is_verified(self, record, user, **kwargs): return record['amount'] > 0 ``` -------------------------------- ### Define UsersSchema for table columns and filters (Python) Source: https://docs.brilliance-admin.com/admin-schema/tables.txt Shows how to define a `FieldsSchema` for the `UsersTable`. This schema specifies the fields, their types (e.g., IntegerField, StringField, DateTimeField), and labels for columns, filters, and forms. ```python from brilliance_admin import schema from brilliance_admin.translations import TranslateText as _ class UsersSchema(schema.FieldsSchema): id = schema.IntegerField(label='ID') username = schema.StringField(label=_('username')) email = schema.StringField(label=_('email')) is_active = schema.BooleanField(label=_('is_active')) created_at = schema.DateTimeField(label=_('created_at')) _fields = ['id', 'username', 'email', 'is_active', 'created_at'] ``` -------------------------------- ### Define a Basic Table Action in Python Source: https://docs.brilliance-admin.com/admin-schema/table_actions.txt This Python code snippet demonstrates how to define a basic table action using the `@admin_action` decorator. It registers an asynchronous method `deactivate` on a `CategoryTable` subclass to perform an operation on selected user primary keys. ```python from brilliance_admin.schema.table.admin_action import admin_action, ActionData, ActionResult class UsersTable(schema.CategoryTable): ... @admin_action( title='Deactivate', description='Deactivate selected users', confirmation_text='Are you sure?', ) async def deactivate(self, action_data: ActionData): for pk in action_data.pks: await deactivate_user(pk) return ActionResult('Users deactivated') ``` -------------------------------- ### Customizing Queryset in SQLAlchemy Admin - Python Source: https://docs.brilliance-admin.com/integrations/sqlalchemy/table_schema.txt Illustrates how to override the 'get_queryset' method in SQLAlchemyAdmin to modify the base SQLAlchemy select statement. This allows for custom joins, filters, or eager loading options, such as filtering for active users. ```python from brilliance_admin import sqlalchemy from myapp.models import User from myapp.database import db class UserAdmin(sqlalchemy.SQLAlchemyAdmin): model = User db_async_session = db.async_session def get_queryset(self): stmt = super().get_queryset() # only show active users return stmt.where(User.is_active == True) ``` -------------------------------- ### Raise Exception for User Error Message (Python) Source: https://docs.brilliance-admin.com/admin-schema/table_actions.txt This snippet demonstrates how to raise a generic `Exception` within an admin action. The exception's message is displayed as an error notification to the user. It requires the `admin_action` decorator and `ActionData` for context. The action returns an `ActionResult` upon successful completion. ```python @admin_action(title='Approve') async def approve(self, action_data: ActionData): if not action_data.pks: raise Exception('No items selected') await approve_items(action_data.pks) return ActionResult('Approved') ``` -------------------------------- ### Force Read-Only Fields with readonly_fields Source: https://docs.brilliance-admin.com/fields_schema/fields_schema.txt This snippet shows how to enforce specific fields as read-only during schema initialization by providing a list of field names to the `readonly_fields` attribute. ```python from brilliance_admin.schema import FieldsSchema table_schema = FieldsSchema(readonly_fields=['amount', 'endpoint']) ``` -------------------------------- ### Custom Autocomplete Logic in Python Source: https://docs.brilliance-admin.com/autocomplete.txt Implement custom search logic for autocomplete by overriding the `autocomplete` method in a `CategoryTable` subclass. This method takes `AutocompleteData` as input and should return an `AutocompleteResult` containing a list of `Record` objects. The `Record` object represents a single autocomplete suggestion with a `key` and a `title`. ```python from brilliance_admin import schema from brilliance_admin.schema.table.table_models import AutocompleteData, AutocompleteResult, Record class MyTable(schema.CategoryTable): ... async def autocomplete(self, data: AutocompleteData, user, admin_schema) -> AutocompleteResult: # your custom search logic results = [ Record(key=1, title='Option 1'), Record(key=2, title='Option 2'), ] return AutocompleteResult(results=results) ```