Coverage for extras/dashboard/utils.py: 38%
36 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
1import uuid
3from django.conf import settings
4from django.core.exceptions import ObjectDoesNotExist
5from django.utils.translation import gettext as _
7from extras.constants import DEFAULT_DASHBOARD
8from netbox.registry import registry
10__all__ = (
11 'get_dashboard',
12 'get_default_dashboard',
13 'get_widget_class',
14 'register_widget',
15)
18def register_widget(cls):
19 """
20 Decorator for registering a DashboardWidget class.
21 """
22 app_label = cls.__module__.split('.', maxsplit=1)[0]
23 label = f'{app_label}.{cls.__name__}'
24 registry['widgets'][label] = cls
26 return cls
29def get_widget_class(name):
30 """
31 Return a registered DashboardWidget class identified by its name.
32 """
33 try:
34 return registry['widgets'][name]
35 except KeyError:
36 raise ValueError(_("Unregistered widget class: {name}").format(name=name))
39def get_dashboard(user):
40 """
41 Return the Dashboard for a given User if one exists, or generate a default dashboard.
42 """
43 if user.is_anonymous:
44 dashboard = get_default_dashboard()
45 else:
46 try:
47 dashboard = user.dashboard
48 except ObjectDoesNotExist:
49 # Create a dashboard for this user
50 dashboard = get_default_dashboard()
51 dashboard.user = user
52 dashboard.save()
54 return dashboard
57def get_default_dashboard(config=None):
58 from extras.models import Dashboard
60 dashboard = Dashboard()
61 config = config or settings.DEFAULT_DASHBOARD or DEFAULT_DASHBOARD
63 for widget in config:
64 id = str(uuid.uuid4())
65 dashboard.layout.append({
66 'id': id,
67 'w': widget['width'],
68 'h': widget['height'],
69 'x': widget.get('x'),
70 'y': widget.get('y'),
71 })
72 dashboard.config[id] = {
73 'class': widget['widget'],
74 'title': widget.get('title'),
75 'color': widget.get('color'),
76 'config': widget.get('config', {}),
77 }
79 return dashboard