Django SmartBase Admin

website·Indexed 29 days ago

https://smartbase-sk.github.io/django-smartbase-admin-docs/

A powerful extension for Django projects that provides a customizable admin interface. Key features include interactive dashboards with charts and aggregate widgets, a highly customizable table (list) view with inline editing and manual reordering, global filters, built-in support for translations via django-parler, and an optional messaging feature for administrators.

Tokens
16.7K
Snippets
68
Records
88
Agent score
72%

What's inside SmartBase Admin

  1. Overview of SmartBase Admin messaging feature

    SmartBase Admin provides an optional messaging system that allows administrators to author messages (with rich-text and attachments) and deliver them to specific users. Key features include:

    • A management view for authoring and recipient selection.
    • A per-user inbox with an unread message badge.
    • Real-time notifications via a background poller that triggers toasts or modals.
    • Configurable message types and pluggable audiences (Users, Groups, All Users, or custom models).
  2. Overview of django-smartbase-admin features

    django-smartbase-admin provides an enhanced administrative interface for Django projects, featuring a modern Tailwind CSS responsive UI. Key capabilities include:

    • Interactive Dashboards: Real-time dashboards with graphs, KPIs, filters, and visual widgets.
    • Powerful List Views: Editable and sortable lists with bulk actions, saved filters, and performance optimizations using SBAdminField, annotate(), and values().
    • FakeInlines: The ability to define inline-like blocks in detail views without requiring a direct model relationship.
    • Advanced Filtering: Autocomplete filters for related fields and the ability to save and reuse custom filters.
    • Hierarchical Data: A Tree Widget for managing hierarchical data structures.
    • Customization: Role-based menu and permissions configuration, and the ability to extend list and detail views with custom actions.
  3. Customize the Django admin list view with sbadmin_list_display

    The sbadmin_list_display attribute in an SBAdmin class allows for high customization of the admin model table view. It extends the standard Django admin list view to support advanced formatting, styling, and data presentation without modifying the underlying model. Key capabilities include renaming columns, using Python formatters, adding badges/HTML, exporting to XLSX, and advanced filtering.
    @admin.register(Product, site=sb_admin_site)
    class ProductSBAdmin(SBAdmin):
        model = Product
        sbadmin_list_display = (
            "name",
            "sku",
            SBAdminField(name="price", title=_("Price")),
            SBAdminField(name="is_active", title=_("Active")),
            "manufacturer",
        )
        list_per_page = 25
  4. Manage color schemes in SmartBase Admin

    SmartBase Admin provides built-in support for light, dark, and auto (system preference) themes. User preferences are saved per-user in the database and applied by setting the data-theme attribute on the <html> element. In auto mode, the browser's prefers-color-scheme media query determines the active style.
    from django_smartbase_admin.models import ColorScheme
    
    ColorScheme.AUTO    # "auto" - Follows OS/browser preference
    ColorScheme.DARK    # "dark" - Always dark
    ColorScheme.LIGHT   # "light" - Always light
  5. Implement a 'Products from same manufacturer' fake inline

    This example demonstrates how to list other products from the same manufacturer on a Product admin page without a direct self-referencing ForeignKey. The inline is configured as read-only by overriding has_add_permission and has_change_permission and is registered via the sbadmin_fake_inlines attribute on the admin class.
    # catalog/sb_admin.py
    from django.contrib import admin
    from django.utils.safestring import mark_safe
    
    class ProductSameManufacturerInline(SBAdminFakeInlineMixin, SBAdminTableInline):
        model = Product
        fields = ["name", "price", "is_active", "created", "is_current_product"]
        readonly_fields = fields
        can_delete = False
        verbose_name = "Product from the same manufacturer - Fake inline example"
        verbose_name_plural = "Products from the same manufacturer - Fake inline example"
    
        def has_add_permission(self, request, obj=None):
            return False
    
        def has_change_permission(self, request, obj=None):
            return False
    
        def filter_fake_inline_identifier_by_parent_instance(self, inline_queryset, parent_instance):
            return inline_queryset.filter(manufacturer=parent_instance.manufacturer)
    
        @admin.display(description="Current product")
        def is_current_product(self, obj):
            if obj.pk == self.parent_instance.pk:
                return mark_safe('<svg class="w-20 h-20 text-success"><use xlink:href="#Check"></use></svg>')
            return ""
    
    @admin.register(Product, site=sb_admin_site)
    class ProductSBAdmin(SBAdmin):
        inlines = [ProductImageInline]
        sbadmin_fake_inlines = [ProductSameManufacturerInline]
  6. Format table view values using a Python formatter

    In SBAdmin, you can use a Python function to dynamically format how a value is rendered in the table view. This is achieved by passing a function to the python_formatter argument of an SBAdminField within the sbadmin_list_display tuple.

    The formatter function must accept two arguments:

    • object_id: The primary key of the object being rendered.
    • value: The actual value of the field for that object.

    If the formatter returns HTML, it must be wrapped in django.utils.safestring.mark_safe() to ensure the HTML is rendered correctly rather than escaped.

    from django.utils.safestring import mark_safe
    from django.contrib import admin
    from .models import Product
    from smartbase_admin import SBAdmin, SBAdminField
    
    # 1. Define the formatter function
    def status_formatter(object_id, value):
        if value:
            label = "✅"
        else:
            label = "❌"
        return mark_safe(f'<span>{label}</span>')
    
    # 2. Apply it to the admin class
    @admin.register(Product, site=sb_admin_site)
    class ProductSBAdmin(SBAdmin):
        model = Product
        sbadmin_list_display = (
            "name",
            "sku",
            # Use SBAdminField with the python_formatter argument
            SBAdminField(name="is_active", title="Active", python_formatter=status_formatter),
            "manufacturer",
        )
  7. Implement custom list actions in SBAdmin

    To add custom buttons or dropdown menus to the top action bar of a list view in SmartBase Admin, override the get_sbadmin_list_actions(self, request) method in your SBAdmin class. This method must return a list of SBAdminCustomAction objects. Each action can either link to a direct URL or map to a method within the admin class via the action_id parameter.
    from django_smartbase_admin.engine.actions import SBAdminCustomAction
    
    @admin.register(MyModel, site=sb_admin_site)
    class MyModelAdmin(SBAdmin):
        model = MyModel
    
        def my_custom_logic(self, request, modifier):
            # Server-side logic here
            return HttpResponse("Action executed")
    
        def get_sbadmin_list_actions(self, request):
            return [
                SBAdminCustomAction(
                    title="Execute Logic",
                    view=self,
                    action_id="my_custom_logic",
                    icon="Lightning"
                )
            ]
  8. Customize user configuration storage for color schemes

    If your project uses a non-standard user identification method (such as email-based OAuth) instead of the default user_id, you can override the get_user_config class method on SBAdminConfigurationBase. The returned object must contain a color_scheme attribute that matches one of the ColorScheme values.
    from django_smartbase_admin.engine.configuration import SBAdminConfigurationBase
    from django_smartbase_admin.models import ColorScheme
    
    class SBAdminConfiguration(SBAdminConfigurationBase):
    
        @classmethod
        def get_user_config(cls, request):
            """Override to use email-based identification instead of user_id."""
            from myapp.models import MyUserConfig
    
            email = getattr(request.user, "email", None)
            if not email:
                return MyUserConfig(email="anonymous", color_scheme=ColorScheme.AUTO.value)
            
            config, _ = MyUserConfig.objects.get_or_create(
                email=email,
                defaults={
                    "color_scheme": request.request_data.configuration.default_color_scheme,
                },
            )
            return config
  9. Enable messaging in SmartBase Admin

    To enable the messaging feature, you must install the required dependencies, add the messaging app to your Django settings, run migrations, and attach an SBAdminMessagingConfig to your SBAdminRoleConfiguration.

    Prerequisites:

    • ckeditor and ckeditor_uploader must be installed as message content uses RichTextField.
    # settings.py
    INSTALLED_APPS = [
        "django_smartbase_admin",
        "django_smartbase_admin.messaging",
        "ckeditor",
        "ckeditor_uploader",
    ]
    python manage.py migrate
    # config/sbadmin_config.py
    from django_smartbase_admin.engine.configuration import SBAdminRoleConfiguration
    from django_smartbase_admin.messaging.config import SBAdminMessagingConfig
    from django_smartbase_admin.messaging.services import SBAdminMessagingService
    from django_smartbase_admin.engine.menu_item import SBAdminMenuItem
    
    config = SBAdminRoleConfiguration(
        # ... other config
        messaging_config=SBAdminMessagingConfig(),  # Enables messaging with defaults
        menu_items=[
            # Inbox with unread badge
            SBAdminMenuItem(
                view_id="sb_admin_messaging_messagerecipient",
                label="My messages",
                icon="Mail",
                badge=SBAdminMessagingService.get_unread_count,
            ),
            # Authoring view (gated by Django model permissions)
            SBAdminMenuItem(view_id="sb_admin_messaging_message", label="Sent"),
        ],
    )
  10. Initialize SmartBase Admin registration with sb_admin.py

    To register models with the SmartBase admin and define their UI appearance, create a file named sb_admin.py within your Django app directory (e.g., catalog/sb_admin.py). This file serves as the central configuration for how your models are presented in the SmartBase admin panel.
  11. Install and register Smartbase Admin in Django

    Install the django-smartbase-admin package via pip and add it along with its required dependencies (easy_thumbnails, widget_tweaks, ckeditor, and ckeditor_uploader) to the INSTALLED_APPS list in your Django settings.py file.
    pip install django-smartbase-admin
    # settings.py
    INSTALLED_APPS = [
        # other apps
        "django_smartbase_admin",
        "easy_thumbnails",
        "widget_tweaks",
        "ckeditor",
        "ckeditor_uploader",
    ]