nautobot.apps.views - Nautobot Documentation

Skip to content

# `nautobot.apps.views`

Utilities for apps to implement UI views.

## `nautobot.apps.views.AdminRequiredMixin`

Bases: `AccessMixin`

Allows access only to admin users.

## `nautobot.apps.views.BulkComponentCreateView`

Bases: `UIComponentsMixin`, `GetReturnURLMixin`, `ObjectPermissionRequiredMixin`, `View`

Add one or more components (e.g. interfaces, console ports, etc.) to a set of Devices or VirtualMachines.

## `nautobot.apps.views.BulkCreateView`

Bases: `UIComponentsMixin`, `GetReturnURLMixin`, `ObjectPermissionRequiredMixin`, `View`

Create new objects in bulk.

queryset: Base queryset for the objects being created form: Form class which provides the `pattern` field model_form: The ModelForm used to create individual objects pattern_target: Name of the field to be evaluated as a pattern (if any) template_name: The name of the template

## `nautobot.apps.views.BulkDeleteView`

Bases: `UIComponentsMixin`, `GetReturnURLMixin`, `ObjectPermissionRequiredMixin`, `BulkEditAndBulkDeleteModelMixin`, `View`

Delete objects in bulk.

queryset: Custom queryset to use when retrieving objects (e.g. to select related objects) filterset: FilterSet to apply when deleting by QuerySet table: The table used to display devices being deleted form: The form class used to delete objects in bulk template_name: The name of the template

### `get_form()`

Provide a standard bulk delete form if none has been specified for the view

## `nautobot.apps.views.BulkEditView`

Bases: `UIComponentsMixin`, `GetReturnURLMixin`, `ObjectPermissionRequiredMixin`, `BulkEditAndBulkDeleteModelMixin`, `View`

Edit objects in bulk.

queryset: Custom queryset to use when retrieving objects (e.g. to select related objects) filter: FilterSet to apply when deleting by QuerySet table: The table used to display devices being edited form: The form class used to edit objects in bulk template_name: The name of the template

### `extra_post_save_action(obj, form)`

Extra actions after a form is saved

## `nautobot.apps.views.BulkImportView`

Bases: `UIComponentsMixin`, `GetReturnURLMixin`, `ObjectPermissionRequiredMixin`, `View`

Import objects in bulk (CSV format).

Deprecated - replaced by ImportObjects system Job.

queryset: Base queryset for the model table: The django-tables2 Table used to render the list of imported objects template_name: The name of the template

## `nautobot.apps.views.BulkRenameView`

Bases: `UIComponentsMixin`, `GetReturnURLMixin`, `ObjectPermissionRequiredMixin`, `View`

An extendable view for renaming objects in bulk.

### `get_selected_objects_parents_name(selected_objects)`

Return selected_objects parent name.

This method is intended to be overridden by child classes to return the parent name of the selected objects.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`selected_objects` | `list[BaseModel]` | The objects being renamed | required

Returns:

Type | Description
--- | ---
`str` | The parent name of the selected objects

## `nautobot.apps.views.ComponentCreateView`

Bases: `UIComponentsMixin`, `GetReturnURLMixin`, `ObjectPermissionRequiredMixin`, `View`

Add one or more components (e.g. interfaces, console ports, etc.) to a Device or VirtualMachine.

## `nautobot.apps.views.ContentTypePermissionRequiredMixin`

Bases: `AccessMixin`

Similar to Django's built-in PermissionRequiredMixin, but extended to check model-level permission assignments. This is related to ObjectPermissionRequiredMixin, except that is does not enforce object-level permissions, and fits within Nautobot's custom permission enforcement system.

An optional iterable of statically declared permissions to evaluate in addition to those

derived from the object type

### `get_required_permission()`

Return the specific permission necessary to perform the requested action on an object.

## `nautobot.apps.views.GenericView`

Bases: `UIComponentsMixin`, `LoginRequiredMixin`, `View`

Base class for non-object-related views.

Enforces authentication, which Django's base View does not by default.

## `nautobot.apps.views.GetReturnURLMixin`

Provides logic for determining where a user should be redirected after processing a form.

## `nautobot.apps.views.NautobotHTMLRenderer`

Bases: `BrowsableAPIRenderer`

Inherited from BrowsableAPIRenderer to do most of the heavy lifting for getting the context needed for templates and template rendering.

### `construct_table(view, **kwargs)`

Helper function to construct and paginate the table for rendering used in the ObjectListView, ObjectBulkUpdateView and ObjectBulkDestroyView.

### `construct_user_permissions(request, model)`

Helper function to gather the user's permissions to add, change, delete and view the model, and then render the action buttons accordingly allowed in the ObjectListView UI.

### `get_context(data, accepted_media_type, renderer_context)`

Override get_context() from BrowsableAPIRenderer to obtain the context data we need to render our templates. context variable contains template context needed to render Nautobot generic templates / circuits templates. Override this function to add additional key/value pair to pass it to your templates.

### `get_dynamic_filter_form(view, request, *args, filterset_class=None, **kwargs)`

Helper function to obtain the filter_form_class, and then initialize and return the filter_form used in the ObjectListView UI.

### `render(data, accepted_media_type=None, renderer_context=None)`

Overrode render() from BrowsableAPIRenderer to set self.template with NautobotViewSet's get_template_name() before it is rendered.

### `validate_action_buttons(view, request)`

Verify actions in self.action_buttons are valid view actions.

## `nautobot.apps.views.NautobotUIViewSet`

Bases: `ObjectDetailViewMixin`, `ObjectListViewMixin`, `ObjectEditViewMixin`, `ObjectDestroyViewMixin`, `ObjectBulkDestroyViewMixin`, `ObjectBulkCreateViewMixin`, `ObjectBulkUpdateViewMixin`, `ObjectChangeLogViewMixin`, `ObjectNotesViewMixin`

Nautobot BaseViewSet that is intended for UI use only. It provides default Nautobot functionalities such as `create()`, `update()`, `partial_update()`, `bulk_update()`, `destroy()`, `bulk_destroy()`, `retrieve()` `notes()`, `changelog()` and `list()` actions.

## `nautobot.apps.views.NautobotViewSetMixin`

Bases: `GenericViewSet`, `UIComponentsMixin`, `AccessMixin`, `GetReturnURLMixin`, `FormView`

NautobotViewSetMixin is an aggregation of various mixins from DRF, Django and Nautobot to achieve the desired behavior pattern for NautobotUIViewSet

### `check_permissions(request)`

Check whether the user has the permissions needed to perform certain actions.

### `dispatch(request, *args, **kwargs)`

Override the default dispatch() method to check permissions first. Used to determine whether the user has permissions to a view and object-level permissions. Using AccessMixin handle_no_permission() to deal with Object-Level permissions and API-Level permissions in one pass.

### `extra_post_save_action(obj, form)`

Extra actions after a form is saved

### `form_invalid(form)`

Handle invalid forms.

### `form_save(form, **kwargs)`

Generic method to save the object from form. Should be overriden by user if customization is needed.

### `form_valid(form)`

Handle valid forms and redirect to success_url.

### `get_action()`

Helper method for retrieving action and if action not set defaulting to action name.

### `get_extra_context(request, instance=None)`

Return any additional context data for the template.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`request` | `Request` | The current request | required
`instance` | `Model` | The specific object being viewed, if any | `None`

### `get_filter_params(request)`

Helper function - take request.GET and discard any parameters that are not used for queryset filtering.

### `get_form(*args, **kwargs)`

Helper function to get form for different views if specified. If not, return instantiated form using form_class.

### `get_form_class(**kwargs)`

Helper function to get form_class for different views.

### `get_object()`

Returns the object the view is displaying. You may want to override this if you need to provide non-standard queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf.

### `get_permissions_for_model(model, actions)`

Resolve the named permissions for a given model (or instance) and a list of actions (e.g. view or add).

:param model: A model or instance :param actions: A list of actions to perform on the model

### `get_queryset()`

Get the list of items for this view. This must be an iterable, and may be a queryset. Defaults to using `self.queryset`. This method should always be used rather than accessing `self.queryset` directly, as `self.queryset` gets evaluated only once, and those results are cached for all subsequent requests. Override the original `get_queryset()` to apply permission specific to the user and action.

### `get_required_permission()`

Obtain the permissions needed to perform certain actions on a model.

## `nautobot.apps.views.ObjectBulkCreateViewMixin`

Bases: `NautobotViewSetMixin`

UI mixin to bulk create model instances.

Deprecated - use ImportObjects system Job instead.

## `nautobot.apps.views.ObjectBulkDestroyViewMixin`

Bases: `NautobotViewSetMixin`, `BulkDestroyModelMixin`, `BulkEditAndBulkDeleteModelMixin`

UI mixin to bulk destroy model instances.

### `bulk_destroy(request, *args, **kwargs)`

Call perform_bulk_destroy(). The function exist to keep the DRF's get/post pattern of {action}/perform_{action}, we will need it when we transition from using forms to serializers in the UI. User should override this function to handle any actions as needed before bulk destroy.

### `perform_bulk_destroy(request, **kwargs)`

request.POST "_delete": Function to render the user selection of objects in a table form/BulkDestroyConfirmationForm via Response that is passed to NautobotHTMLRenderer. request.POST "_confirm": Function to validate the table form/BulkDestroyConfirmationForm and to perform the action of bulk destroy. Render the form with errors if exceptions are raised.

## `nautobot.apps.views.ObjectBulkUpdateViewMixin`

Bases: `NautobotViewSetMixin`, `BulkUpdateModelMixin`, `BulkEditAndBulkDeleteModelMixin`

UI mixin to bulk update model instances.

### `bulk_update(request, *args, **kwargs)`

Call perform_bulk_update(). The function exist to keep the DRF's get/post pattern of {action}/perform_{action}, we will need it when we transition from using forms to serializers in the UI. User should override this function to handle any actions as needed before bulk update.

### `perform_bulk_update(request, **kwargs)`

request.POST "_edit": Function to render the user selection of objects in a table form/BulkUpdateForm via Response that is passed to NautobotHTMLRenderer. request.POST "_apply": Function to validate the table form/BulkUpdateForm and to perform the action of bulk update. Render the form with errors if exceptions are raised.

## `nautobot.apps.views.ObjectChangeLogViewMixin`

Bases: `NautobotViewSetMixin`

UI mixin to list a model's changelog queryset.

Specify to explicitly identify the base object detail template to render.

If not provided, "/.html", "/_retrieve.html", or "generic/object_retrieve.html" will be used, as per `get_base_template()`.

## `nautobot.apps.views.ObjectDeleteView`

Bases: `UIComponentsMixin`, `GetReturnURLMixin`, `ObjectPermissionRequiredMixin`, `View`

Delete a single object.

queryset: The base queryset for the object being deleted template_name: The name of the template

### `get_object(kwargs)`

Retrieve an object based on `kwargs`.

## `nautobot.apps.views.ObjectDestroyViewMixin`

Bases: `NautobotViewSetMixin`, `DestroyModelMixin`

UI mixin to destroy a model instance.

### `destroy(request, *args, **kwargs)`

request.GET: render the ObjectDeleteConfirmationForm which is passed to NautobotHTMLRenderer as Response. request.POST: call perform_destroy() which validates the form and perform the action of delete. Override to add more variables to Response

### `perform_destroy(request, **kwargs)`

Function to validate the ObjectDeleteConfirmationForm and to delete the object.

## `nautobot.apps.views.ObjectDetailViewMixin`

Bases: `NautobotViewSetMixin`, `RetrieveModelMixin`

UI mixin to retrieve a model instance.

### `retrieve(request, *args, **kwargs)`

Retrieve a model instance.

## `nautobot.apps.views.ObjectDynamicGroupsView`

Bases: `GenericView`

Present a list of dynamic groups associated to a particular object.

Note that this isn't currently widely used, as most object detail views currently render the table inline rather than using this separate view. This may change in the future.

Specify to explicitly identify the base object detail template to render.

If not provided, "/.html", "/_retrieve.html", or "generic/object_retrieve.html" will be used, as per `get_base_template()`.

## `nautobot.apps.views.ObjectEditView`

Bases: `UIComponentsMixin`, `GetReturnURLMixin`, `ObjectPermissionRequiredMixin`, `View`

Create or edit a single object.

queryset: The base queryset for the object being modified model_form: The form used to create or edit the object template_name: The name of the template

### `get_extra_context(request, instance)`

Return any additional context data for the template.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`request` | `HttpRequest` | The current request | required
`instance` | `Model` | The object being edited | required

Returns:

Type | Description
--- | ---
`dict` | Additional context data

### `get_object(kwargs)`

Retrieve an object based on `kwargs`.

### `successful_post(request, obj, created, logger)`

Callback after the form is successfully saved but before redirecting the user.

## `nautobot.apps.views.ObjectEditViewMixin`

Bases: `NautobotViewSetMixin`, `CreateModelMixin`, `UpdateModelMixin`

UI mixin to create or update a model instance.

### `create(request, *args, **kwargs)`

request.GET: render the ObjectForm which is passed to NautobotHTMLRenderer as Response. request.POST: call perform_create() which validates the form and perform the action of create. Override to add more variables to Response.

### `extra_message(**kwargs)`

Append extra message at the end of create or update success message.

### `extra_message_context(obj)`

Context variables for this extra message.

### `perform_create(request, *args, **kwargs)`

Function to validate the ObjectForm and to create a new object.

### `perform_update(request, *args, **kwargs)`

Function to validate the ObjectEditForm and to update/partial_update an existing object.

### `update(request, *args, **kwargs)`

request.GET: render the ObjectEditForm which is passed to NautobotHTMLRenderer as Response. request.POST: call perform_update() which validates the form and perform the action of update/partial_update of an existing object. Override to add more variables to Response.

## `nautobot.apps.views.ObjectImportView`

Bases: `UIComponentsMixin`, `GetReturnURLMixin`, `ObjectPermissionRequiredMixin`, `View`

Import a single object (YAML or JSON format).

queryset: Base queryset for the objects being created model_form: The ModelForm used to create individual objects related_object_forms: A dictionary mapping of forms to be used for the creation of related (child) objects template_name: The name of the template

## `nautobot.apps.views.ObjectListView`

Bases: `UIComponentsMixin`, `ObjectPermissionRequiredMixin`, `View`

List a series of objects.

The queryset of objects to display. Note: Prefetching related objects is not necessary, as the

table will prefetch objects as needed depending on the columns being displayed.

filter: A django-filter FilterSet that is applied to the queryset filter_form: The form used to render filter options table: The django-tables2 Table used to render the objects list template_name: The name of the template non_filter_params: List of query parameters that are not used for queryset filtering

### `get_filter_params(request)`

Helper function - take request.GET and discard any parameters that are not used for queryset filtering.

### `queryset_to_yaml()`

Export the queryset of objects as concatenated YAML documents.

### `validate_action_buttons(request)`

Verify actions in self.action_buttons are valid view actions.

## `nautobot.apps.views.ObjectListViewMixin`

Bases: `NautobotViewSetMixin`, `ListModelMixin`

UI mixin to list a model queryset

### `filter_queryset(queryset)`

Filter a query with request querystrings.

### `list(request, *args, **kwargs)`

List the model instances.

### `queryset_to_yaml()`

Export the queryset of objects as concatenated YAML documents.

## `nautobot.apps.views.ObjectNotesView`

Bases: `GenericView`

Present a list of notes associated to a particular object.

Specify to explicitly identify the base object detail template to render.

If not provided, "/.html", "/_retrieve.html", or "generic/object_retrieve.html" will be used, as per `get_base_template()`.

## `nautobot.apps.views.ObjectNotesViewMixin`

Bases: `NautobotViewSetMixin`

UI Mixin for an Object's Notes.

Specify to explicitly identify the base object detail template to render.

If not provided, "/.html", "/_retrieve.html", or "generic/object_retrieve.html" will be used, as per `get_base_template()`.

## `nautobot.apps.views.ObjectPermissionRequiredMixin`

Bases: `AccessMixin`

Similar to Django's built-in PermissionRequiredMixin, but extended to check for both model-level and object-level permission assignments. If the user has only object-level permissions assigned, the view's queryset is filtered to return only those objects on which the user is permitted to perform the specified action.

An optional iterable of statically declared permissions to evaluate in addition to those

derived from the object type

### `get_required_permission()`

Return the specific permission necessary to perform the requested action on an object.

## `nautobot.apps.views.ObjectView`

Bases: `UIComponentsMixin`, `ObjectPermissionRequiredMixin`, `View`

Retrieve a single object for display.

queryset: The base queryset for retrieving the object template_name: Name of the template to use

### `get(request, *args, **kwargs)`

Generic GET handler for accessing an object.

### `get_extra_context(request, instance)`

Return any additional context data for the template.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`request` | `Request` | The current request | required
`instance` | `Model` | The object being viewed | required

Returns:

Type | Description
--- | ---
`dict` | Additional context data

### `get_template_name()`

Return self.template_name if set. Otherwise, resolve the template path by model app_label and name.

## `nautobot.apps.views.UIComponentsMixin`

Mixin that resolves UI components (e.g., breadcrumbs, titles) either from: 1) the current view class (preferred), 2) a related view class for a given model (via `lookup.get_view_for_model()`), 3) or a default component class.

The public helpers (`get_view_titles()`, `get_breadcrumbs()`) return concrete component instances ready to use in renderers/templates.

It should be used in views that use the `nautobot.apps.views.GenericView` and standard Nautobot templates.

Example usage:

    def get(self, request, *args, **kwargs):
        context = {
            ...
            "breadcrumbs": self.get_breadcrumbs(model),
        }
        context["title"] = self.get_view_titles(model).render(context)

        return render(
            request,
            "extras/plugins_list.html",
            context,
        )

Attributes:

Name | Type | Description
--- | --- | ---
`breadcrumbs` | `ClassVar[Optional[Breadcrumbs]]` | Optional component declared on the view class. May be: - `None` (no local definition, fall back), - a component class (will be instantiated), - or a pre-instantiated component (returned as-is).
`view_titles` | `ClassVar[Optional[Titles]]` | Same contract as `breadcrumbs`, but for titles.

### `get_breadcrumbs(model=None, view_type='List')` `classmethod`

Resolve and return the `Breadcrumbs` component instance.

Resolution order mirrors `get_view_titles()`: 1) Use `.breadcrumbs` if set locally. 2) Else, if `model` is provided, copy the `breadcrumbs` from the view class associated with that model via `lookup.get_view_for_model(model, action)`. 3) Else return a new default `Breadcrumbs()`.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`model` | `Union[None, str, Type[Model], Model]` | A Django model class, instance, dotted name string, or `None`. Passed to `lookup.get_view_for_model()` to find the related view class. If `None`, only local/default resolution is used. | `None`
`view_type` | `str` | Logical view type used by `lookup.get_view_for_model()` (e.g., `"List"` or empty to construct `"DeviceView"` string). | `'List'`

Returns:

Name | Type | Description
--- | --- | ---
`Breadcrumbs` | `Breadcrumbs` | A concrete `Breadcrumbs` component instance.

### `get_view_titles(model=None, view_type='List')` `classmethod`

Resolve and return the `Titles` component instance.

Resolution order

1) If `.view_titles` is set on the current view, use it. 2) Else, if `model` is provided, copy the `view_titles` from the view class associated with that model via `lookup.get_view_for_model(model, action)`. 3) Else, instantiate and return the default `Titles()`.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`model` | `Union[None, str, Type[Model], Model]` | A Django model class, instance, dotted name string, or `None`. Passed to `lookup.get_view_for_model()` to find the related view class. If `None`, only local/default resolution is used. | `None`
`view_type` | `str` | Logical view type used by `lookup.get_view_for_model()` (e.g., `"List"` or empty to construct `"DeviceView"` string). | `'List'`

Returns:

Name | Type | Description
--- | --- | ---
`Titles` | `Titles` | A concrete `Titles` component instance ready to use.

## `nautobot.apps.views.check_and_call_git_repository_function(request, pk, func)`

Helper for checking Git permissions and worker availability, then calling provided function if all is well Args: request (HttpRequest): request object. pk (UUID): GitRepository pk value. func (function): Enqueue git repo function. Returns: (Union[HttpResponseForbidden,redirect]): HttpResponseForbidden if user does not have permission to run the job, otherwise redirect to the job result page.

## `nautobot.apps.views.check_filter_for_display(filters, field_name, values)`

Return any additional context data for the template.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`filters` | `OrderedDict` | The output of `.get_filters()` of a desired FilterSet | required
`field_name` | `str` | The name of the filter to get a label for and lookup values | required
`values` | `list[str]` | List of strings that may be PKs to look up | required

Returns:

Type | Description
--- | ---
`dict` | A dict containing: - name: (str) Field name - display: (str) Resolved field name, whether that's a field label or fallback to inputted `field_name` if label unavailable - values: (list) List of dictionaries with the same `name` and `display` keys

## `nautobot.apps.views.csv_format(data)`

Convert the given list of data to a CSV row string.

Encapsulate any data which contains a comma within double quotes.

Obsolete, as CSV rendering in Nautobot core is now handled by nautobot.core.api.renderers.NautobotCSVRenderer.

## `nautobot.apps.views.get_csv_form_fields_from_serializer_class(serializer_class)`

From the given serializer class, build a list of field dicts suitable for rendering in the CSV import form.

## `nautobot.apps.views.get_obj_from_context(context, key=None)`

From the given context, return the `object` that is in the context.

If a key is specified, return the value for that key. Otherwise return the value for either of the keys `"obj"` or `"object"` as default behavior.

## `nautobot.apps.views.get_paginate_count(request, saved_view=None)`

Determine the length of a page, using the following in order:

    1. per_page URL query parameter
    2. Saved view config
    3. Saved user preference
    4. PAGINATE_COUNT global setting.

## `nautobot.apps.views.handle_protectederror(obj_list, request, e)`

Generate a user-friendly error message in response to a ProtectedError exception.

## `nautobot.apps.views.prepare_cloned_fields(instance)`

Compile an object's `clone_fields` list into a string of URL query parameters. Tags are automatically cloned where applicable.