Skip to content

nautobot.apps.ui

Utilities for apps to integrate with and extend the existing Nautobot UI.

nautobot.apps.ui.Banner

Class that may be returned by a registered plugin_banners function.

Source code in nautobot/extras/plugins/__init__.py
class Banner:
    """Class that may be returned by a registered plugin_banners function."""

    def __init__(self, content, banner_class=BannerClassChoices.CLASS_INFO):
        self.content = content
        if banner_class not in BannerClassChoices.values():
            raise ValueError("Banner class must be a choice within BannerClassChoices.")
        self.banner_class = banner_class

nautobot.apps.ui.BannerClassChoices

Bases: ChoiceSet

Styling choices for custom banners.

Source code in nautobot/extras/choices.py
class BannerClassChoices(ChoiceSet):
    """Styling choices for custom banners."""

    CLASS_SUCCESS = "success"
    CLASS_INFO = "info"
    CLASS_WARNING = "warning"
    CLASS_DANGER = "danger"

    CHOICES = (
        (CLASS_SUCCESS, "Success"),
        (CLASS_INFO, "Info"),
        (CLASS_WARNING, "Warning"),
        (CLASS_DANGER, "Danger"),
    )

nautobot.apps.ui.HomePageItem

Bases: HomePageBase, PermissionsMixin

Defines properties that can be used for a panel item.

Source code in nautobot/core/apps/__init__.py
class HomePageItem(HomePageBase, PermissionsMixin):
    """Defines properties that can be used for a panel item."""

    items = []
    template_path = None

    @property
    def initial_dict(self):
        return {
            "custom_template": self.custom_template,
            "custom_data": self.custom_data,
            "description": self.description,
            "link": self.link,
            "model": self.model,
            "permissions": self.permissions,
            "template_path": self.template_path,
            "weight": self.weight,
        }

    @property
    def fixed_fields(self):
        return ()

    def __init__(
        self,
        name,
        link=None,
        model=None,
        custom_template=None,
        custom_data=None,
        description=None,
        permissions=None,
        weight=1000,
    ):
        """
        Ensure item properties.

        Args:
            name (str): The name of the item.
            link (str): The link to be used for this item.
            model (str): The model to being used for this item to calculate the total count of objects.
            custom_template (str): Name of custom template.
            custom_data (dict): Custom data to be passed to the custom template.
        """
        super().__init__(permissions)

        self.name = name
        self.custom_template = custom_template
        self.custom_data = custom_data
        self.description = description
        self.link = link
        self.model = model
        self.weight = weight

        if model is not None and custom_template is not None:
            raise ValueError("Cannot specify model and custom_template at the same time.")

__init__(name, link=None, model=None, custom_template=None, custom_data=None, description=None, permissions=None, weight=1000)

Ensure item properties.

Parameters:

Name Type Description Default
name str

The name of the item.

required
link str

The link to be used for this item.

None
model str

The model to being used for this item to calculate the total count of objects.

None
custom_template str

Name of custom template.

None
custom_data dict

Custom data to be passed to the custom template.

None
Source code in nautobot/core/apps/__init__.py
def __init__(
    self,
    name,
    link=None,
    model=None,
    custom_template=None,
    custom_data=None,
    description=None,
    permissions=None,
    weight=1000,
):
    """
    Ensure item properties.

    Args:
        name (str): The name of the item.
        link (str): The link to be used for this item.
        model (str): The model to being used for this item to calculate the total count of objects.
        custom_template (str): Name of custom template.
        custom_data (dict): Custom data to be passed to the custom template.
    """
    super().__init__(permissions)

    self.name = name
    self.custom_template = custom_template
    self.custom_data = custom_data
    self.description = description
    self.link = link
    self.model = model
    self.weight = weight

    if model is not None and custom_template is not None:
        raise ValueError("Cannot specify model and custom_template at the same time.")

nautobot.apps.ui.HomePagePanel

Bases: HomePageBase, PermissionsMixin

Defines properties that can be used for a panel.

Source code in nautobot/core/apps/__init__.py
class HomePagePanel(HomePageBase, PermissionsMixin):
    """Defines properties that can be used for a panel."""

    items = None
    template_path = None

    @property
    def initial_dict(self):
        return {
            "custom_template": self.custom_template,
            "custom_data": self.custom_data,
            "weight": self.weight,
            "items": {},
            "permissions": self.permissions,
            "template_path": self.template_path,
        }

    @property
    def fixed_fields(self):
        return ()

    def __init__(self, name, permissions=None, custom_data=None, custom_template=None, items=None, weight=1000):
        """
        Ensure panel properties.

        Args:
            name (str): The name of the panel.
            permissions (list): The permissions required to view this panel.
            custom_data (dict): Custom data to be passed to the custom template.
            custom_template (str): Name of custom template.
            items (list): List of items to be rendered in this panel.
            weight (int): The weight of this panel.
        """
        super().__init__(permissions)
        self.custom_data = custom_data
        self.custom_template = custom_template
        self.name = name
        self.weight = weight

        if items is not None and custom_template is not None:
            raise ValueError("Cannot specify items and custom_template at the same time.")
        if items is not None:
            if not isinstance(items, (list, tuple)):
                raise TypeError("Items must be passed as a tuple or list.")
            elif not all(isinstance(item, (HomePageGroup, HomePageItem)) for item in items):
                raise TypeError("All items defined in a panel must be an instance of HomePageGroup or HomePageItem")
            self.items = items
        else:
            self.items = []

__init__(name, permissions=None, custom_data=None, custom_template=None, items=None, weight=1000)

Ensure panel properties.

Parameters:

Name Type Description Default
name str

The name of the panel.

required
permissions list

The permissions required to view this panel.

None
custom_data dict

Custom data to be passed to the custom template.

None
custom_template str

Name of custom template.

None
items list

List of items to be rendered in this panel.

None
weight int

The weight of this panel.

1000
Source code in nautobot/core/apps/__init__.py
def __init__(self, name, permissions=None, custom_data=None, custom_template=None, items=None, weight=1000):
    """
    Ensure panel properties.

    Args:
        name (str): The name of the panel.
        permissions (list): The permissions required to view this panel.
        custom_data (dict): Custom data to be passed to the custom template.
        custom_template (str): Name of custom template.
        items (list): List of items to be rendered in this panel.
        weight (int): The weight of this panel.
    """
    super().__init__(permissions)
    self.custom_data = custom_data
    self.custom_template = custom_template
    self.name = name
    self.weight = weight

    if items is not None and custom_template is not None:
        raise ValueError("Cannot specify items and custom_template at the same time.")
    if items is not None:
        if not isinstance(items, (list, tuple)):
            raise TypeError("Items must be passed as a tuple or list.")
        elif not all(isinstance(item, (HomePageGroup, HomePageItem)) for item in items):
            raise TypeError("All items defined in a panel must be an instance of HomePageGroup or HomePageItem")
        self.items = items
    else:
        self.items = []

nautobot.apps.ui.NavMenuGroup

Bases: NavMenuBase, PermissionsMixin

This class represents a group of menu items within a NavMenuTab.

It has a name (display string) and a weight which controls its position relative to other groups/items.

In Nautobot 1.x this could only contain NavMenuItems as children; in 2.x this has been relaxed to also permit a top-level NavMenuGroup to contain other NavMenuGroup objects.

Source code in nautobot/core/apps/__init__.py
class NavMenuGroup(NavMenuBase, PermissionsMixin):
    """
    This class represents a group of menu items within a `NavMenuTab`.

    It has a `name` (display string) and a `weight` which controls its position relative to other groups/items.

    In Nautobot 1.x this could only contain `NavMenuItem`s as children;
    in 2.x this has been relaxed to also permit a top-level `NavMenuGroup` to contain other `NavMenuGroup` objects.
    """

    items = []

    @property
    def initial_dict(self) -> dict:
        """Attributes to be stored when adding this item to the nav menu data for the first time."""
        return {
            "weight": self.weight,
            "permissions": self.permissions,
            "items": {},
        }

    @property
    def fixed_fields(self) -> tuple:
        """Tuple of (name, attribute) entries describing fields that may not be altered after declaration."""
        return (("weight", self.weight),)

    def __init__(self, name, weight=1000, permissions=None, items=None):
        """
        Ensure group properties.

        Args:
            name (str): The name of the group.
            weight (int): The weight of this group.
            permissions (set): The permissions to access this group.
            items (list): List of items to be rendered in this group.
        """
        super().__init__(permissions)
        self.name = name
        self.weight = weight

        if items is not None and not isinstance(items, (list, tuple)):
            raise TypeError("Items must be passed as a tuple or list.")
        if not all(isinstance(item, (type(self), NavMenuItem)) for item in items):
            raise TypeError("All items defined in a group must be an instance of NavMenuGroup or NavMenuItem")
        self.items = items

fixed_fields: tuple property

Tuple of (name, attribute) entries describing fields that may not be altered after declaration.

initial_dict: dict property

Attributes to be stored when adding this item to the nav menu data for the first time.

__init__(name, weight=1000, permissions=None, items=None)

Ensure group properties.

Parameters:

Name Type Description Default
name str

The name of the group.

required
weight int

The weight of this group.

1000
permissions set

The permissions to access this group.

None
items list

List of items to be rendered in this group.

None
Source code in nautobot/core/apps/__init__.py
def __init__(self, name, weight=1000, permissions=None, items=None):
    """
    Ensure group properties.

    Args:
        name (str): The name of the group.
        weight (int): The weight of this group.
        permissions (set): The permissions to access this group.
        items (list): List of items to be rendered in this group.
    """
    super().__init__(permissions)
    self.name = name
    self.weight = weight

    if items is not None and not isinstance(items, (list, tuple)):
        raise TypeError("Items must be passed as a tuple or list.")
    if not all(isinstance(item, (type(self), NavMenuItem)) for item in items):
        raise TypeError("All items defined in a group must be an instance of NavMenuGroup or NavMenuItem")
    self.items = items

nautobot.apps.ui.NavMenuItem

Bases: NavMenuBase, PermissionsMixin

This class represents a navigation menu item that leads to a specific page (a "leaf" in the nav menu, if you will).

These are contained within NavMenuGroup objects.

Links are specified as Django reverse URL strings.

Source code in nautobot/core/apps/__init__.py
class NavMenuItem(NavMenuBase, PermissionsMixin):
    """
    This class represents a navigation menu item that leads to a specific page (a "leaf" in the nav menu, if you will).

    These are contained within `NavMenuGroup` objects.

    Links are specified as Django reverse URL strings.
    """

    @property
    def initial_dict(self) -> dict:
        """Attributes to be stored when adding this item to the nav menu data for the first time."""
        return {
            "weight": self.weight,
            "permissions": self.permissions,
            "link": self.link,
        }

    @property
    def fixed_fields(self) -> tuple:
        """Tuple of (name, attribute) entries describing fields that may not be altered after declaration."""
        return (
            ("weight", self.weight),
            ("permissions", self.permissions),
            ("link", self.link),
        )

    def __init__(self, link, name, args=None, kwargs=None, permissions=None, weight=1000):
        """
        Ensure item properties.

        Args:
            link (str): The named link to be used for this item. `reverse(link, args, kwargs)` will be called.
            name (str): The name of the item.
            args (list): Arguments that are being passed to the url with reverse() method
            kwargs (dict): Keyword arguments are are being passed to the url with reverse() method
            permissions (list): The permissions required to view this item.
            weight (int): The weight of this item.
        """
        super().__init__(permissions)
        self.name = name
        self.weight = weight
        try:
            self.link = reverse(link, args=args, kwargs=kwargs)
        except NoReverseMatch as e:
            logger.error("Error in link construction for %s: %s", self.name, e)
            self.link = ""

fixed_fields: tuple property

Tuple of (name, attribute) entries describing fields that may not be altered after declaration.

initial_dict: dict property

Attributes to be stored when adding this item to the nav menu data for the first time.

__init__(link, name, args=None, kwargs=None, permissions=None, weight=1000)

Ensure item properties.

Parameters:

Name Type Description Default
link str

The named link to be used for this item. reverse(link, args, kwargs) will be called.

required
name str

The name of the item.

required
args list

Arguments that are being passed to the url with reverse() method

None
kwargs dict

Keyword arguments are are being passed to the url with reverse() method

None
permissions list

The permissions required to view this item.

None
weight int

The weight of this item.

1000
Source code in nautobot/core/apps/__init__.py
def __init__(self, link, name, args=None, kwargs=None, permissions=None, weight=1000):
    """
    Ensure item properties.

    Args:
        link (str): The named link to be used for this item. `reverse(link, args, kwargs)` will be called.
        name (str): The name of the item.
        args (list): Arguments that are being passed to the url with reverse() method
        kwargs (dict): Keyword arguments are are being passed to the url with reverse() method
        permissions (list): The permissions required to view this item.
        weight (int): The weight of this item.
    """
    super().__init__(permissions)
    self.name = name
    self.weight = weight
    try:
        self.link = reverse(link, args=args, kwargs=kwargs)
    except NoReverseMatch as e:
        logger.error("Error in link construction for %s: %s", self.name, e)
        self.link = ""

nautobot.apps.ui.NavMenuTab

Bases: NavMenuBase, PermissionsMixin

This class represents a top-level Nautobot "menu context" such as Inventory or Networks.

It has a name (the menu context name) and a weight (which is mostly irrelevant these days).

It contains a list of NavMenuGroup instances as children.

In Nautobot 1.x, these could be augmented arbitrarily by apps and plugins; but in 2.0 and later there is a fixed list of these (nautobot.core.apps.MENU_TABS) that cannot be altered.

Source code in nautobot/core/apps/__init__.py
class NavMenuTab(NavMenuBase, PermissionsMixin):
    """
    This class represents a top-level Nautobot "menu context" such as Inventory or Networks.

    It has a `name` (the menu context name) and a `weight` (which is mostly irrelevant these days).

    It contains a list of `NavMenuGroup` instances as children.

    In Nautobot 1.x, these could be augmented arbitrarily by apps and plugins;
    but in 2.0 and later there is a fixed list of these (`nautobot.core.apps.MENU_TABS`) that cannot be altered.
    """

    groups = []

    @property
    def initial_dict(self) -> dict:
        """Attributes to be stored when adding this item to the nav menu data for the first time."""
        return {
            "groups": {},
            "permissions": self.permissions,
        }

    @property
    def fixed_fields(self) -> tuple:
        """Tuple of (name, attribute) entries describing fields that may not be altered after declaration."""
        return (("weight", self.weight),)

    def __init__(self, name, permissions=None, groups=None):
        """
        Ensure tab properties.

        Args:
            name (str): The name of the tab.
            permissions (list): The permissions required to view this tab.
            groups (list): List of groups to be rendered in this tab.
        """
        super().__init__(permissions)
        if name not in MENU_TABS:
            raise ValueError(f"NavMenuTab name must be one of {MENU_TABS}")
        self.name = name
        if groups is not None:
            if not isinstance(groups, (list, tuple)):
                raise TypeError("Groups must be passed as a tuple or list.")
            if not all(isinstance(group, NavMenuGroup) for group in groups):
                raise TypeError("All groups defined in a tab must be an instance of NavMenuGroup")
            self.groups = groups

fixed_fields: tuple property

Tuple of (name, attribute) entries describing fields that may not be altered after declaration.

initial_dict: dict property

Attributes to be stored when adding this item to the nav menu data for the first time.

__init__(name, permissions=None, groups=None)

Ensure tab properties.

Parameters:

Name Type Description Default
name str

The name of the tab.

required
permissions list

The permissions required to view this tab.

None
groups list

List of groups to be rendered in this tab.

None
Source code in nautobot/core/apps/__init__.py
def __init__(self, name, permissions=None, groups=None):
    """
    Ensure tab properties.

    Args:
        name (str): The name of the tab.
        permissions (list): The permissions required to view this tab.
        groups (list): List of groups to be rendered in this tab.
    """
    super().__init__(permissions)
    if name not in MENU_TABS:
        raise ValueError(f"NavMenuTab name must be one of {MENU_TABS}")
    self.name = name
    if groups is not None:
        if not isinstance(groups, (list, tuple)):
            raise TypeError("Groups must be passed as a tuple or list.")
        if not all(isinstance(group, NavMenuGroup) for group in groups):
            raise TypeError("All groups defined in a tab must be an instance of NavMenuGroup")
        self.groups = groups

nautobot.apps.ui.TemplateExtension

This class is used to register plugin content to be injected into core Nautobot templates. It contains methods that are overridden by plugin authors to return template content.

The model attribute on the class defines the which model detail page this class renders content for. It should be set as a string in the form <app_label>.<model_name>. render() provides the following context data:

  • object - The object being viewed
  • request - The current request
  • settings - Global Nautobot settings
  • config - Plugin-specific configuration parameters
Source code in nautobot/extras/plugins/__init__.py
class TemplateExtension:
    """
    This class is used to register plugin content to be injected into core Nautobot templates. It contains methods
    that are overridden by plugin authors to return template content.

    The `model` attribute on the class defines the which model detail page this class renders content for. It
    should be set as a string in the form `<app_label>.<model_name>`. `render()` provides the following context data:

    * object - The object being viewed
    * request - The current request
    * settings - Global Nautobot settings
    * config - Plugin-specific configuration parameters
    """

    model = None

    def __init__(self, context):
        self.context = context

    def render(self, template_name, extra_context=None):
        """
        Convenience method for rendering the specified Django template using the default context data. An additional
        context dictionary may be passed as `extra_context`.
        """
        if extra_context is None:
            extra_context = {}
        elif not isinstance(extra_context, dict):
            raise TypeError("extra_context must be a dictionary")

        return get_template(template_name).render({**self.context, **extra_context})

    def left_page(self):
        """
        Content that will be rendered on the left of the detail page view. Content should be returned as an
        HTML string. Note that content does not need to be marked as safe because this is automatically handled.
        """
        raise NotImplementedError

    def right_page(self):
        """
        Content that will be rendered on the right of the detail page view. Content should be returned as an
        HTML string. Note that content does not need to be marked as safe because this is automatically handled.
        """
        raise NotImplementedError

    def full_width_page(self):
        """
        Content that will be rendered within the full width of the detail page view. Content should be returned as an
        HTML string. Note that content does not need to be marked as safe because this is automatically handled.
        """
        raise NotImplementedError

    def buttons(self):
        """
        Buttons that will be rendered and added to the existing list of buttons on the detail page view. Content
        should be returned as an HTML string. Note that content does not need to be marked as safe because this is
        automatically handled.
        """
        raise NotImplementedError

    def detail_tabs(self):
        """
        Tabs that will be rendered and added to the existing list of tabs on the detail page view.
        Tabs will be ordered by their position in the list.

        Content should be returned as a list of dicts in the following format:
        ```
        [
            {
                "title": "<title>",
                "url": "<url for the tab link>",
            },
            {
                "title": "<title>",
                "url": "<url for the tab link>",
            },
        ]
        ```
        """
        raise NotImplementedError

buttons()

Buttons that will be rendered and added to the existing list of buttons on the detail page view. Content should be returned as an HTML string. Note that content does not need to be marked as safe because this is automatically handled.

Source code in nautobot/extras/plugins/__init__.py
def buttons(self):
    """
    Buttons that will be rendered and added to the existing list of buttons on the detail page view. Content
    should be returned as an HTML string. Note that content does not need to be marked as safe because this is
    automatically handled.
    """
    raise NotImplementedError

detail_tabs()

Tabs that will be rendered and added to the existing list of tabs on the detail page view. Tabs will be ordered by their position in the list.

Content should be returned as a list of dicts in the following format:

[
    {
        "title": "<title>",
        "url": "<url for the tab link>",
    },
    {
        "title": "<title>",
        "url": "<url for the tab link>",
    },
]

Source code in nautobot/extras/plugins/__init__.py
def detail_tabs(self):
    """
    Tabs that will be rendered and added to the existing list of tabs on the detail page view.
    Tabs will be ordered by their position in the list.

    Content should be returned as a list of dicts in the following format:
    ```
    [
        {
            "title": "<title>",
            "url": "<url for the tab link>",
        },
        {
            "title": "<title>",
            "url": "<url for the tab link>",
        },
    ]
    ```
    """
    raise NotImplementedError

full_width_page()

Content that will be rendered within the full width of the detail page view. Content should be returned as an HTML string. Note that content does not need to be marked as safe because this is automatically handled.

Source code in nautobot/extras/plugins/__init__.py
def full_width_page(self):
    """
    Content that will be rendered within the full width of the detail page view. Content should be returned as an
    HTML string. Note that content does not need to be marked as safe because this is automatically handled.
    """
    raise NotImplementedError

left_page()

Content that will be rendered on the left of the detail page view. Content should be returned as an HTML string. Note that content does not need to be marked as safe because this is automatically handled.

Source code in nautobot/extras/plugins/__init__.py
def left_page(self):
    """
    Content that will be rendered on the left of the detail page view. Content should be returned as an
    HTML string. Note that content does not need to be marked as safe because this is automatically handled.
    """
    raise NotImplementedError

render(template_name, extra_context=None)

Convenience method for rendering the specified Django template using the default context data. An additional context dictionary may be passed as extra_context.

Source code in nautobot/extras/plugins/__init__.py
def render(self, template_name, extra_context=None):
    """
    Convenience method for rendering the specified Django template using the default context data. An additional
    context dictionary may be passed as `extra_context`.
    """
    if extra_context is None:
        extra_context = {}
    elif not isinstance(extra_context, dict):
        raise TypeError("extra_context must be a dictionary")

    return get_template(template_name).render({**self.context, **extra_context})

right_page()

Content that will be rendered on the right of the detail page view. Content should be returned as an HTML string. Note that content does not need to be marked as safe because this is automatically handled.

Source code in nautobot/extras/plugins/__init__.py
def right_page(self):
    """
    Content that will be rendered on the right of the detail page view. Content should be returned as an
    HTML string. Note that content does not need to be marked as safe because this is automatically handled.
    """
    raise NotImplementedError