By default, all fields are rendered as text in the list view. To customize this, you must use a JavaScript function to render the column within the Datatables instance.
- Provide a JS file: Override the
custom_render_js method in your Admin class to return the URL of your custom JavaScript file. - Implement the render function: In your JS file, add your rendering logic to the
render object. The fieldOptions argument contains your field's attributes (serialized via asdict). - Set the key: In your
BaseField subclass, set the render_function_key to match the key used in your JavaScript object.
from starlette_admin.contrib.sqla import Admin as BaseAdmin
from starlette_admin import BaseField
from dataclasses import dataclass
from typing import Optional
from starlette.requests import Request
# 1. Override Admin to provide the JS file
class Admin(BaseAdmin):
def custom_render_js(self, request: Request) -> Optional[str]:
return request.url_for("statics", path="js/custom_render.js")
# 2. Define the field with the matching key
@dataclass
class CustomField(BaseField):
render_function_key: str = "mycustomkey"
admin = Admin(engine)
admin.add_view(...)
Object.assign(render, {
mycustomkey: function render(data, type, full, meta, fieldOptions) {
// Your custom rendering logic here
},
});