Skip to main content

PyPI version

django-tab-menus

A Django app for rendering flexible navigation menus and AJAX-loaded tab interfaces. Supports dropdowns, badges, keyboard shortcuts, permission-based visibility, and integration with django-ajax-helpers.

Installation

pip install django-tab-menus

Add to INSTALLED_APPS:

INSTALLED_APPS = [
    ...
    'django_menus',
]

Upgrading from 0.0.x

  • The menu JavaScript no longer needs jQuery or Popper. Dropdowns are positioned by a bundled copy of Floating UI, which {% lib_include module='django_menus.includes' %} loads before django_menus.js.
  • Bootstrap 5 is supported through CSS_FRAMEWORK = 'bootstrap5' (needs django-ajax-helpers 1.0.1 or later).
  • Attribute values, including tooltips, are now escaped by default. Mark any value you escape yourself as safe; see Escaping.
  • Click-opened dropdowns also close on an outside click or Escape.

To stay on the jQuery version, pin django-tab-menus<1.0.

Quick Start

The simplest menu is built with HtmlMenu and rendered in a template:

from django_menus.menu import HtmlMenu, MenuItem, MenuMixin
from django.views.generic import TemplateView

class MyView(MenuMixin, TemplateView):
    template_name = 'my_template.html'

    def setup_menu(self):
        self.add_menu('main', 'base').add_items(
            'home',          # Django URL name — label auto-derived from view
            ('about', 'About Us'),
            ('contact', 'Contact'),
        )

In the template:

{% load django_menu_tags %}
{% menu_content 'main' %}

MenuMixin injects all menus into the template context under menus, so menus.main is also accessible directly.

Two ready-made view classes save the boilerplate: MenuTemplateView is MenuMixin + TemplateView, and AjaxMenuTemplateView additionally mixes in django-ajax-helpers AJAX handling (needed for badge refresh, tabs and context menus).

Menu Types

Pass a template name as the second argument to add_menu() (or as template= on HtmlMenu):

Name Layout
'base' Bootstrap navbar
'button_group' Inline button group
'buttons' Stacked buttons
'tabs' Tab bar
'breadcrumb' Breadcrumb trail
'dropdown' Standalone dropdown

Adding Items

String shorthand

Passing a URL name string resolves the view and auto-derives the label from view.menu_display or the URL name:

menu.add_items('dashboard', 'reports', 'settings')

Tuple shorthand

menu.add_items(
    ('reports', 'My Reports'),                          # (url_name, label)
    ('reports', 'My Reports', {'css_classes': 'btn-primary'}),  # with kwargs
)

MenuItem class

The full item API:

MenuItem(
    url,                        # URL name, raw URL, JS string, or AJAX command
    menu_display=None,          # str, tuple, or MenuItemDisplay instance
    link_type=MenuItem.URL_NAME,
    css_classes=None,           # str or list
    font_awesome=None,          # e.g. 'fas fa-edit'
    tooltip=None,
    tooltip_placement=None,     # default: right in dropdowns and context menus, else bottom
    badge=None,                 # MenuItemBadge instance
    dropdown=None,              # tuple of items for a nested dropdown
    show_caret=True,
    key=None,                   # keyboard shortcut, e.g. 'alt-s' or ['alt-s', 'shift-S']
    url_args=None,
    url_kwargs=None,
    attributes=None,            # dict of extra HTML attributes
    visible=True,
    disabled=False,
    target=None,                # link target, e.g. '_blank'
)

Raw HTML

HtmlMenuItem injects arbitrary HTML into a menu slot:

from django_menus.menu import HtmlMenuItem

menu.add_items(HtmlMenuItem(html='<span class="navbar-text">v2.1</span>'))
Constant Behaviour
MenuItem.URL_NAME Django URL name resolved via reverse() (default)
MenuItem.HREF Raw URL string
MenuItem.AJAX_GET_URL_NAME URL name loaded via AJAX GET
MenuItem.AJAX_BUTTON Submits an AJAX button (django-ajax-helpers)
MenuItem.JAVASCRIPT Executes a JavaScript expression
MenuItem.AJAX_COMMAND Sends an ajax_helpers command dict
# Raw URL
MenuItem('/some/path/', 'External', MenuItem.HREF)

# JavaScript
MenuItem("alert('hello')", 'Alert', MenuItem.JAVASCRIPT)

# AJAX GET (loads content without full page reload)
MenuItem('my_view', 'Load Content', MenuItem.AJAX_GET_URL_NAME)

# URL with args
MenuItem('profile', 'Profile', url_args=[user.pk])
MenuItem('profile', 'Profile', url_kwargs={'pk': user.pk})
# Shorthand: keyword args prefixed with url_ become URL kwargs
MenuItem('profile', 'Profile', url_pk=user.pk)

AjaxButtonMenuItem is a convenience class for posting an ajax-helpers button without writing the JavaScript yourself:

from django_menus.menu import AjaxButtonMenuItem

menu.add_items(AjaxButtonMenuItem('refresh', 'Refresh'))   # posts {"button": "refresh"}

AdminMenuItem links to an object's change page in Django admin:

from django_menus.menu import AdminMenuItem

menu.add_items(AdminMenuItem(company))                        # icon-only, tooltip 'Django Admin'
menu.add_items(AdminMenuItem(company, 'Admin', css_classes='btn-sm btn-outline-secondary'))

Visibility is decided by the admin itself: the site's has_permission() (active staff) and the registered ModelAdmin's has_view_or_change_permission(request, obj), so per-object permission overrides are respected. It is re-checked for every request. The item hides itself if the object is unsaved or its model isn't registered with the site.

site= takes an AdminSite instance or its name (default 'admin'); an unknown name raises ImproperlyConfigured. visible= (a bool or callable taking the request) narrows it further. An icon supplied in menu_display (tuple or MenuItemDisplay) replaces the default fas fa-tools.

MenuItemDisplay

Controls display properties — text, icon, CSS classes, tooltip, and HTML attributes:

from django_menus.menu import MenuItemDisplay

# Keyword form
MenuItemDisplay(text='Save', font_awesome='fas fa-save', css_classes='btn-primary', tooltip='Save record')

# Tuple shorthand (text, icon, css_classes, tooltip, attributes)
MenuItem('save_view', ('Save', 'fas fa-save', 'btn-primary'))

# On a view class — auto-picked up when the URL is resolved
class MyView(TemplateView):
    menu_display = MenuItemDisplay('My View', 'fas fa-star', 'btn-success')

Dropdowns

Pass a dropdown tuple to any MenuItem:

from django_menus.menu import DividerItem, HeaderItem

menu.add_items(
    MenuItem(menu_display='Actions', dropdown=(
        HeaderItem('Record'),
        'edit_view',
        'delete_view',
        DividerItem(),
        'archive_view',
    )),
)

HeaderItem renders a non-clickable section header (dropdown-header); DividerItem a separator line. Options: show_caret=False hides the caret; no_hover=True requires a click to open.

Megamenus

A long dropdown can be drawn as columns instead: pass dropdown_template='mega' and start each column with a HeaderItem. icon (Font Awesome classes) and colour (any CSS colour; color also works) style the column's heading, tint the column and colour its hover. colour is written into an inline style unchecked, so take it from code or settings, never from user input.

MenuItem(menu_display='Settings', placement='bottom-end', dropdown_template='mega', dropdown=(
    HeaderItem('Financial', icon='fas fa-coins', colour='#21965b'),
    'tax_rates', 'exchange_rates', 'payment_terms',
    HeaderItem('Users', icon='fas fa-user-shield', colour='#7a4fc9'),
    'user_admin', 'permissions',
))

The item list is the same as for a plain dropdown, so switching between the two is just the template. Items before the first header form a column without a heading, HeaderItem() with no text starts a new column without one (and renders nothing in a plain dropdown), dividers are dropped, and a header with nothing visible under it is left out along with its column. If no column has anything visible, the parent item is hidden. Items' tooltips open below, as elsewhere, rather than to the right over the next column. Columns wrap onto a second row rather than run off a narrow window, and stack below 768px. Use placement='bottom-end' for a menu near the right of the navbar. icon and colour are ignored by the other templates. Styling lives in django_menus.css under .mega-menu.

AJAX-loaded dropdowns

AjaxMenuDropDownItem renders a button whose dropdown contents are fetched from the server when clicked — useful when the items are expensive to build or depend on live data. The click posts {"ajax": "<dropdown_view_name>"} (default 'dropdown_menu') to the current view, which responds with add_ajax_dropdown_menu:

from django_menus.menu import AjaxMenuDropDownItem

class MyView(AjaxMenuTemplateView):
    def setup_menu(self):
        self.add_menu('menu_items', 'button_group').add_items(
            AjaxMenuDropDownItem(menu_display='Options', css_classes='btn-success'))

    def ajax_dropdown_menu(self, *args, pos, **kwargs):
        return self.add_ajax_dropdown_menu('view1', 'view2', ('view4', 'View 4'), pos=pos)

An optional value= on the item is passed through to the handler, so one handler can serve several buttons.

Context Menus

ContextMenuMixin attaches a right-click menu to any element matching context_menu_selector (default '.context_menu'). The right-click posts {"ajax": "context_menu"} to the view, which builds the menu on demand:

from django_menus.menu import ContextMenuMixin, AjaxMenuTemplateView, HeaderItem, MenuItem

class MyView(ContextMenuMixin, AjaxMenuTemplateView):
    template_name = 'my_template.html'

    def ajax_context_menu(self, *args, **kwargs):
        return self.add_context_menu(
            HeaderItem('Actions'),
            'view1', 'view2',
            ('test_button', 'Send to View', MenuItem.AJAX_BUTTON),
        )
<div class="context_menu" id="area_one">Right click me</div>

<!-- Per-element handler override: posts {"ajax": "special_context_menu"} instead -->
<div class="context_menu" id="area_two" data-ajax="special_context_menu">Right click me</div>

The clicked element's id is available in the handler kwargs, so the menu can vary per row/area. The view must include django-ajax-helpers handling (e.g. AjaxMenuTemplateView).

Badges

Attach a MenuItemBadge to any MenuItem:

from django_menus.menu import MenuItemBadge

def my_badge_fn(badge):
    badge.text = MyModel.objects.filter(unread=True).count()
    badge.css_class = 'danger'   # Bootstrap colour name

MenuItem('inbox', 'Inbox', badge=MenuItemBadge('inbox-badge', my_badge_fn))

The badge is rendered inside a <span id="inbox-badge"> so it can be refreshed via AJAX without a page reload. Badges show on dropdown items too. Use AjaxMenuTemplateView.timer_menu() to poll for updates.

Keyboard Shortcuts

# Single key
MenuItem('save_view', 'Save', key='alt-s')

# Multiple bindings
MenuItem('save_view', 'Save', key=['alt-s', 'shift-S'])

Supported modifiers: alt-, shift-. The key name is case-sensitive (e.g. 'F2' for the function key).

Shortcuts from every menu on the page — including menus loaded later via AJAX — are merged into a single document-level listener, so multiple menus can define keys without clobbering each other. Shortcuts are suppressed while a django-modals dialog is open.

Permissions

view_permission

Define a classmethod on a view to control whether the menu item pointing to that view is visible:

class SecretView(TemplateView):
    @classmethod
    def view_permission(cls, request, menu_item):
        return request.user.is_staff

menu_permissions

Define on a view to control non-URL-resolved items (e.g. AJAX buttons) while that view is active:

class MyView(TemplateView):
    @classmethod
    def menu_permissions(cls, request, menu_item):
        return request.user.has_perm('myapp.can_edit')

Callable visible

visible accepts a callable taking the request, for items whose target view you do not own:

MenuItem('admin:index', 'Admin', visible=lambda request: request.user.is_staff)

Menu Registry

A long dropdown listed in one central setup_menu() conflicts on every merge. The registry lets each view declare its own place instead, so adding a page touches only the app that owns it.

Declare the sections once:

DJANGO_MENUS_SECTIONS = {
    'settings': {'title': 'Settings'},
    'reports': {
        'title': 'Reports',
        'groups': ['sales', 'purchases', ('stock', 'Stock')],
        'sort': 'order',
    },
}

Then each view says where it belongs:

from django_menus.menu import MenuEntry

class ExchangeRateList(ListView):
    menu_display = 'Exchange Rates'
    menu_entry = MenuEntry('settings')

class StockReorderReport(ListView):
    menu_display = 'Stock Reorder'
    menu_entry = MenuEntry('reports', 'stock')

and the central menu shrinks to a skeleton:

def setup_menu(self):
    self.add_menu('main_menu').add_items(
        'dashboard_view',
        registry.menu_item('reports', self.request),
        registry.menu_item('settings', self.request,
                           MenuItem('page_info', 'Page Info', link_type=MenuItem.AJAX_BUTTON),
                           MenuItem('admin:index', 'Admin', visible=lambda r: r.user.is_staff)),
    )

The URLConf is walked once, lazily and cached; MenuItems are built per request, so view_permission and callable visible behave exactly as they do in a hand-written menu.

MenuEntry

Argument Purpose
section Key in DJANGO_MENUS_SECTIONS. Required.
group Group within a grouped section. Required for grouped sections.
url_name Only needed when the view is reachable under more than one url name.
url_args / url_kwargs Arguments for reverse(), when the url pattern takes any.
display Overrides menu_display in this section only — tabs and breadcrumbs keep the view's own label.
order Sort position, used when the section sets sort: 'order'.
anything else Passed to MenuItem() — font_awesome, css_classes, key, tooltip…

Set menu_entry to a list to put one view in several sections. menu_entry is not inherited — a view is in the menu only if it declares one itself, so the archived, grouped and pk-taking subclasses of a listed page do not each add a duplicate item. A subclass that should appear as well declares a MenuEntry of its own.

Section options

Key Default Meaning
title capitalised section name Label of the parent item built by menu_item().
font_awesome — Icon for the parent item.
groups none Group names in render order. A (name, header) pair emits a HeaderItem; (name, header, {'icon': ..., 'colour': ...}) styles it as a megamenu column heading (header may be None). In a mega section every group starts its own column, with or without a header.
sort 'alpha' 'alpha' by display text, 'order' by MenuEntry(order=...), or 'declared' by URLConf order.
divider on when grouped Insert a DividerItem between groups.
mega False Draw the section's dropdown as a megamenu, a column per group header.
default_group first group Group for entries that name none.

Dividers and headers are only emitted between groups that still have visible items for this request, so a group hidden by permissions never leaves a stray separator behind.

API

from django_menus.menu import registry

registry.dropdown(section, request, *extra)   # ordered list of items
registry.menu_item(section, request, *extra)  # parent MenuItem with the dropdown attached
registry.extra(item, group=..., order=..., sort_text=...)   # place a caller-built item
registry.specs(section)                       # what the scan found, for diagnostics

extra items are ordinary MenuItems built at the call site — use them for anything the URLConf cannot describe, such as an AJAX_BUTTON or a third-party view with no view class. They sort by their own display text alongside the registered items.

Checking it

Mistyped sections and groups, ambiguous url names and missing url arguments are reported by manage.py check (ids django_menus.E001–E008, W001–W002) and raise ImproperlyConfigured when the registry scans.

manage.py show_menu prints the resolved tree so ordering is inspectable without running the site:

manage.py show_menu                          # every configured section
manage.py show_menu reports --user ian       # one section, as a given user
manage.py show_menu --view dashboard_view    # the menus a view actually builds
manage.py show_menu --view dashboard_view --show-hidden --format json

AJAX Tab Interfaces

AjaxMenuTabs handles a tab bar where each tab loads its content via AJAX:

from django_menus.menu import AjaxMenuTabs, MenuItem

class MyTabView(AjaxMenuTabs):
    template_name = 'my_tabs.html'
    tab_template = 'my_tab_content.html'

    def setup_menu(self):
        super().setup_menu()
        self.add_menu('tab_menu', 'tabs').add_items(
            ('tab1_view', 'First Tab', MenuItem.AJAX_GET_URL_NAME),
            ('tab2_view', 'Second Tab', MenuItem.AJAX_GET_URL_NAME),
        )

    def tab_context(self, **kwargs):
        context = super().tab_context(**kwargs)
        context['data'] = MyModel.objects.all()
        return context

    def main_context(self, **kwargs):
        # Only called on the initial (non-AJAX) page load
        return {'title': 'My Tabs'}
  • tab_context() is called on every request (initial and AJAX).
  • main_context() is called only on the initial page load.
  • additional_content lists extra areas to refresh on tab switch: [(name, AjaxMenuTabs.MENU_CONTENT)] for a menu, or [(name, AjaxMenuTabs.TEMPLATE_CONTENT)] for a template fragment.

Global Button Defaults

Pre-configure named button styles in settings.py so any menu item whose display text matches the key inherits the style automatically:

from django_menus.menu import MenuItemDisplay

DJANGO_MENUS_BUTTON_DEFAULTS = {
    'save':   MenuItemDisplay('Save',   'fas fa-save',   'btn-primary'),
    'delete': MenuItemDisplay('Delete', 'fas fa-trash',  'btn-danger'),
    'edit':   MenuItemDisplay('Edit',   'fas fa-pen',    'btn-secondary'),
}

Then in any view:

self.add_menu('actions', 'button_group').add_items(
    MenuItem('save_view',   'save'),    # picks up the global style
    MenuItem('delete_view', 'delete'),
)

Individual menus can override or extend the global set with button_defaults=, without affecting other menus:

self.add_menu('actions', 'button_group',
              button_defaults={'save': MenuItemDisplay('Save', 'fas fa-check', 'btn-outline-primary')})

Escaping

Three settings control how labels and attributes are written:

DJANGO_MENUS_ESCAPE_ATTRIBUTES = True        # default True
DJANGO_MENUS_ESCAPE_LABELS = False           # default False
DJANGO_MENUS_BLOCK_EVENT_ATTRIBUTES = False  # default False
  • DJANGO_MENUS_ESCAPE_ATTRIBUTES escapes attribute values (including title from tooltip=) and drops attribute names that are not plain names, so a quote in a value cannot break out of the tag. A value marked safe is written as it is.
  • DJANGO_MENUS_ESCAPE_LABELS escapes labels, HeaderItem text and MenuItemBadge text. Mark HTML with safe=True on MenuItem, MenuItemDisplay, HeaderItem or MenuItemBadge, or pass it through mark_safe/format_html.
  • DJANGO_MENUS_BLOCK_EVENT_ATTRIBUTES drops on* attributes such as onclick; use the JAVASCRIPT or AJAX link types instead.

DJANGO_MENUS_BUTTON_DEFAULTS keys match the unescaped label in every mode.

Bootstrap 4 / 5

Markup follows the CSS_FRAMEWORK setting shared with django-ajax-helpers (the same setting that decides what {% lib_include %} loads):

CSS_FRAMEWORK = 'bootstrap5'   # default 'bootstrap4'

It switches navbar alignment (ms-auto/me-auto), button spacing, the context-menu caret, badge classes (badge rounded-pill text-bg-<colour>) and tooltip data-bs-placement. Custom menu templates receive the active class set as css, e.g. {{ css.align_end }}. Bootstrap 5 needs django-ajax-helpers 1.0.1 or later (1.0.0 breaks AJAX posts).

Template Tags

{% load django_menu_tags %}

{# Render a menu by name from the context variable 'menus' #}
{% menu_content 'main_menu' %}

{# Render any menu object directly #}
{% show_menu menus.main_menu %}

{# Render a single button inline — keyword args are passed to MenuItem #}
{% display_button url='my_view' menu_display='Click me' %}

{# Render a template content fragment by context variable name #}
{% template_content 'tab_template' %}

Running the Example Project

# With Docker
docker-compose up
# Bootstrap 4: http://localhost:8009
# Bootstrap 5: http://localhost:8010

# Without Docker
cd django_examples
pip install -r requirements.txt
python manage.py migrate
python manage.py runserver

# Bootstrap 5 (needs django-ajax-helpers >= 1.0.1)
python manage.py runserver --settings=django_examples.settings_bs5

The Bootstrap 5 variant only sets CSS_FRAMEWORK = 'bootstrap5'. django-tab-menus' own JavaScript needs neither jQuery nor Popper (dropdowns are positioned by a bundled copy of Floating UI), so it works in both modes.

Metadata

Release files for django-tab-menus 1.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-tab-menus 1.1.0
File Size Uploaded Provenance Actions
django_tab_menus-1.1.0.tar.gz 73.5 kB With provenance Details for django_tab_menus-1.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-tab-menus 1.1.0
File Interpreter ABI Platform Actions
django_tab_menus-1.1.0-py3-none-any.whl Python 3 none any Details for django_tab_menus-1.1.0-py3-none-any.whl

Total release size: 128.3 kB

Release files / django_tab_menus-1.1.0.tar.gz

Download URL django_tab_menus-1.1.0.tar.gz
Size 73.5 kB
Tags Source
SHA-256 checksum
How to use checksums
3554daf6634e4c41cf5d37890efc403d1d48a05aada66bbcfa4a74b7ba68cba5
BLAKE2b-256 checksum
How to use checksums
21d0ca2d8e9b18797a5e93f7ac8038be108214f7649138cc3005549282f52d7c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 10, 2026.

Transparency log

Release files / django_tab_menus-1.1.0-py3-none-any.whl

Download URL django_tab_menus-1.1.0-py3-none-any.whl
Size 54.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f7993f1f6576853033b937fb0ce1b21d4acd4a349e2143ad96e31f9eb5bae341
BLAKE2b-256 checksum
How to use checksums
72271599a0d6b90fdd097f81a2d0ce7d4aebd9a76460e623b34e3aafa4fde000
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 10, 2026.

Transparency log

Security for django-tab-menus 1.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for django_tab_menus-1.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 10, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page