django-unfold Documentation

repository·main·Indexed 25 days ago

https://github.com/unfoldadmin/django-unfold

A modern Django Admin skin and enhancement library built on top of django.contrib.admin. It provides a professional, Tailwind CSS-based interface featuring sidebar navigation, dark mode, a command palette, and advanced form enhancements like inline tabs and conditional fields. The library includes specialized ModelAdmin tools for implementing changelist row actions, changeform actions, and submitline actions, as well as integrations for packages such as django-guardian, django-import-export, and django-celery-beat.

Tokens
53.7K
Snippets
144
Records
244
Agent score
86%

What's inside django-unfold

  1. Overview of Unfold features

    main

    Unfold enhances the standard django.contrib.admin with a modern Tailwind CSS-based interface. Key features include:

    • Navigation & UI: Sidebar navigation with icons, dark mode support, command palette for quick searching, and custom dashboard tools.
    • Form Enhancements: Inline tabs, fieldset tabs, conditional fields (show/hide based on other values), and sortable inlines via drag-and-drop.
    • Advanced Filtering & Widgets: Custom dropdowns, autocomplete, numeric, datetime, and text field filters; support for ArrayField and Trix WYSIWYG editor.
    • Performance & UX: Infinite pagination for large datasets, paginated inlines, and compressed changeform modes.
    • Customization: Theming options for colors, backgrounds, and border radius; support for custom favicons and environment labels.
  2. Use Unfold inline classes for enhanced styling

    main

    Unfold provides its own versions of Django's inline classes to ensure visual consistency with the Unfold admin theme. While standard Django StackedInline and TabularInline will work, they will not match the Unfold design aesthetic. To achieve the full Unfold look and feel, use unfold.admin.StackedInline and unfold.admin.TabularInline instead of the standard Django imports.

    To implement inlines:

    1. Import StackedInline or TabularInline from unfold.admin.
    2. Define your inline class by inheriting from the Unfold class and specifying the model.
    3. Add the inline classes to the inlines list of your ModelAdmin.
    from django.contrib import admin
    from django.contrib.auth.models import User
    from unfold.admin import StackedInline, TabularInline
    
    
    class MyStackedInline(StackedInline):
        model = User
    
    
    class MyTabularInline(TabularInline):
        model = User
    
    
    @admin.register(User)
    class UserAdmin(ModelAdmin):
        inlines = [MyStackedInline, MyTabularInline]
  3. Use ArrayWidget for ArrayField in Django Admin

    main

    You can globally apply ArrayWidget to all ArrayField instances in a ModelAdmin using the formfield_overrides attribute. By default, the widget renders as standard text inputs. If choices are provided to the widget, it automatically switches to a dropdown list interface.

    from django.contrib import admin
    from django.contrib.postgres.fields import ArrayField
    from unfold.admin import ModelAdmin
    from unfold.contrib.forms.widgets import ArrayWidget
    
    @admin.register(MyModel)
    class CustomAdminClass(ModelAdmin):
        formfield_overrides = {
            ArrayField: {
                "widget": ArrayWidget,
            }
        }
  4. Use InfinitePaginator for large datasets

    main

    To optimize performance when handling tables with millions of records, use the InfinitePaginator. This paginator avoids expensive database COUNT operations by removing the upper limit on page numbers and simplifying navigation to only "Previous" and "Next" links.

    When implementing InfinitePaginator, you must also set show_full_result_count = False in your ModelAdmin to prevent Django from attempting to calculate the total record count, which would negate the performance benefits.

    from unfold.admin import ModelAdmin
    from unfold.paginator import InfinitePaginator
    
    
    class YourAdmin(ModelAdmin):
        paginator = InfinitePaginator
        show_full_result_count = False
  5. Create custom Django admin actions with Unfold

    main

    Unfold actions are derived from standard Django actions but enhanced with Unfold's @action decorator. You can define actions within a ModelAdmin class and register them in the actions_list attribute. The @action decorator allows you to add a description and an icon.

    from django.contrib import admin
    from django.db.models import QuerySet
    from django.http import HttpRequest
    from unfold.admin import ModelAdmin
    from unfold.decorators import action
    
    @admin.register(User)
    class UserAdmin(ModelAdmin):
        actions_list = ["custom_action"]
    
        @action(description="Custom action", icon="person")
        def custom_action(self, request: HttpRequest, queryset: QuerySet):
            pass
  6. Load custom styles and scripts in Django Unfold

    main

    You can inject custom CSS and JavaScript files across all pages of the Django Unfold admin interface by configuring the STYLES and SCRIPTS keys within the UNFOLD dictionary in your settings.py.

    Both keys accept a list containing either strings or lambda functions. It is recommended to use lambda functions with Django's static() template tag to ensure correct path resolution.

    Deployment Note: Always run python manage.py collectstatic during your production deployment process to ensure your custom static files are correctly gathered and served.

    # settings.py
    
    from django.templatetags.static import static
    
    UNFOLD = {
        "STYLES": [
            lambda request: static("css/styles.css"),
        ],
        "SCRIPTS": [
            lambda request: static("js/scripts.js"),
        ],
    }
  7. Customizing styles in Unfold 0.57+ using Tailwind 4.x

    main

    For Unfold version 0.57 and above, you can use Tailwind 4.x to add custom styles. Tailwind 4 uses a CSS-first configuration approach where settings are managed directly in your CSS file rather than a separate JavaScript config file.

    1. Install dependencies: Install tailwindcss and @tailwindcss/cli via npm.
    2. Configure CSS: Create a styles.css file and import Tailwind using @import 'tailwindcss';.
    3. Compile: Use the @tailwindcss/cli to compile your input CSS into a static file.
    4. Register in Django: Add the compiled file path to the UNFOLD["STYLES"] setting in your settings.py using a lambda function that calls static().
    npm i tailwindcss @tailwindcss/cli
    /* styles.css */
    @import 'tailwindcss';
    npx @tailwindcss/cli -i styles.css -o your_project/static/css/styles.css --minify
    # settings.py
    from django.templatetags.static import static
    
    UNFOLD = {
        "STYLES": [
            lambda request: static("css/styles.css"),
        ],
    }
  8. Enable multi-language support in Django Unfold

    main

    To enable multi-language support in the Django Unfold admin interface, you must configure your Django settings to handle internationalization and locale middleware.

    1. Add django.middleware.locale.LocaleMiddleware to your MIDDLEWARE setting.
    2. Set USE_I18N = True.
    3. Define your default LANGUAGE_CODE.
    4. Define the available languages in the LANGUAGES setting.
    # settings.py
    
    MIDDLEWARE = [
        "django.middleware.locale.LocaleMiddleware",
    ]
    
    LANGUAGE_CODE = "en"
    
    USE_I18N = True
    
    LANGUAGES = (
        ("de", _("German")),
        ("en", _("English")),
    )
  9. Implement expandable rows using Sections

    main

    Unfold allows you to add expandable rows to Django admin changelists using the list_sections attribute on your ModelAdmin. When configured, rows will display an arrow button that reveals additional content.

    Sections are implemented by defining classes that inherit from either TableSection or TemplateSection from unfold.sections and adding them to the list_sections list in your ModelAdmin.