Coverage for netbox/views/generic/mixins.py: 24%
27 statements
« prev ^ index » next coverage.py v7.15.2, created at 2026-10-10 18:35 +0000
« prev ^ index » next coverage.py v7.15.2, created at 2026-10-10 18:35 +0000
1from django.shortcuts import get_object_or_404
3from extras.models import TableConfig
4from utilities.permissions import get_permission_for_model
6__all__ = (
7 'ActionsMixin',
8 'TableMixin',
9)
12class ActionsMixin:
13 """
14 Maps action names to the set of required permissions for each. Object list views reference this mapping to
15 determine whether to render the applicable button for each action: The button will be rendered only if the user
16 possesses the specified permission(s).
18 Standard actions include: add, import, export, bulk_edit, and bulk_delete. Some views extend this default map
19 with custom actions, such as bulk_sync.
20 """
21 actions = tuple()
23 def get_permitted_actions(self, user, model=None):
24 """
25 Return a tuple of actions for which the given user is permitted to do.
26 """
27 model = model or self.queryset.model
29 # Resolve required permissions for each action
30 permitted_actions = []
31 for action in self.actions:
32 required_permissions = [
33 get_permission_for_model(model, perm) for perm in action.permissions_required
34 ]
35 if not required_permissions or user.has_perms(required_permissions):
36 permitted_actions.append(action)
38 return permitted_actions
41class TableMixin:
43 def get_table(self, data, request, bulk_actions=True):
44 """
45 Return the django-tables2 Table instance to be used for rendering the objects list.
47 Args:
48 data: Queryset or iterable containing table data
49 request: The current request
50 bulk_actions: Render checkboxes for object selection
51 """
53 # If a TableConfig has been specified, apply it & update the user's saved preference
54 if tableconfig_id := request.GET.get('tableconfig_id'):
55 tableconfig = get_object_or_404(TableConfig, pk=tableconfig_id)
56 if request.user.is_authenticated:
57 table = self.table.__name__
58 request.user.config.set(f'tables.{table}.columns', tableconfig.columns)
59 request.user.config.set(f'tables.{table}.ordering', tableconfig.ordering, commit=True)
61 table = self.table(data)
62 if 'pk' in table.base_columns and bulk_actions:
63 table.columns.show('pk')
64 table.configure(request)
66 return table