Initial NetBox Floor Planner plugin

Drag & drop SVG floor plan designer for NetBox 4.7.2+ with rack/device
placement, smart snapping, undo/redo, view mode with status colouring,
SVG/PNG export, REST layout API and English/German translations.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-11-04 12:18:13 +01:00
commit c4dc5d53ce
31 files changed
+3041

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
__pycache__/
*.py[cod]
*.egg-info/
build/
dist/
.venv/
+4
View File
@@ -0,0 +1,4 @@
include README.md
recursive-include netbox_floorplanner/templates *
recursive-include netbox_floorplanner/static *
recursive-include netbox_floorplanner/locale *
+163
View File
@@ -0,0 +1,163 @@
# NetBox Floor Planner
`netbox_floorplanner` is a NetBox plugin that adds a modern, drag & drop floor plan designer for sites and locations: place racks, devices, walls, doors, windows, areas and infrastructure on a to-scale plan, then use it as an interactive map that links straight back into NetBox.
It is a from-scratch alternative to the community `netbox-floorplan-plugin`, with a canvas-style editor in the spirit of draw.io instead of a form-based workflow.
| | |
|---|---|
| **Package** | `netbox-floorplanner` |
| **Plugin name** | `netbox_floorplanner` |
| **NetBox** | 4.7.2 or newer |
| **Python** | 3.12 or newer |
| **Languages** | English, German (follows the NetBox user language) |
## Requirements
- NetBox **4.7.2 or newer**. Older versions are rejected at startup (`min_version = 4.7.2`).
- Python 3.12 or newer.
- No additional Python dependencies and no JavaScript build step. The designer is plain JavaScript and SVG and uses the Material Design Icons that ship with NetBox.
## Installation and updates
1. Install the package into the NetBox virtual environment. Pin a release tag or commit for production:
```bash
source /opt/netbox/venv/bin/activate
pip install "git+https://<your-git-server>/<owner>/[email protected]"
```
2. Add the same source to `local_requirements.txt`, so NetBox upgrades (`upgrade.sh`) reinstall the plugin automatically:
```text
git+https://<your-git-server>/<owner>/[email protected]
```
For private repositories use a deploy token or SSH key and keep the credentials out of this file.
3. Enable the plugin in `configuration.py`:
```python
PLUGINS = [
'netbox_floorplanner',
]
PLUGINS_CONFIG = {
'netbox_floorplanner': {
# optional, see "Configuration"
},
}
```
4. Run the migrations, collect the static files and restart NetBox:
```bash
cd /opt/netbox/netbox
python manage.py migrate netbox_floorplanner
python manage.py collectstatic --no-input
sudo systemctl restart netbox netbox-rq
```
Before updating, back up the database and try the update on a staging instance first. After every update, run `migrate` and `collectstatic` again. The static files are versioned, so browsers pick up the new designer automatically.
## Main features
- **Drag & drop designer:** drag shapes, racks and devices from the palette onto the plan, or click an entry to drop it in the middle of the view.
- **To-scale plans:** 1 unit = 1 cm. Racks are sized from their `outer_width` and `outer_depth` (mm or inch), with a configurable fallback.
- **Editing:** move, resize with 8 handles, free rotation with 15° snapping, multi-selection (Shift+click or rubber band), z-order, copy/paste/duplicate, arrow-key nudging and 100 undo/redo steps.
- **Smart snapping:** snaps to the grid, plus magnetic alignment to the edges of neighbouring items and room walls, with visible guide lines. Hold **Alt** to place freely.
- **Shape library:** wall, door (with swing arc), window, area/zone, column, cooling unit, power/UPS and free text labels, each with an editable colour.
- **NetBox integration:**
- The palette lists the site's racks (filtered by location) and its non-racked devices, such as access points and cameras. Objects already placed are marked and can only be placed once.
- A **Floor Plans** tab on Site and Location pages, with a pre-filled "Add floor plan" button.
- A **Show on floor plan** button on Rack and Device pages that opens the plan, zooms to the object and highlights it.
- **Interactive view mode:** pan, zoom, tooltips (status, role, tenant, height, device count), click to open the rack or device (Ctrl+click opens a new tab), colouring by type, status or role, and a search box that highlights matches.
- **Background drawings:** upload a CAD or architectural image per plan, stretched to the room size with adjustable opacity.
- **Export:** SVG (vector) and high-resolution PNG, with the background embedded.
- **NetBox native:** change logging, journaling, tags, custom fields, global search, CSV/YAML import, bulk delete, object permissions, REST API, dark mode and fullscreen.
### Keyboard shortcuts (designer)
| Key | Action |
|---|---|
| Drag / Shift+click / drag on empty space | Move / multi-select / rubber-band select |
| Alt (while dragging) | Disable snapping |
| Space+drag, middle mouse | Pan |
| Mouse wheel, `+` / `-` / `0` | Zoom / fit to screen |
| `R` / Shift+`R` | Rotate 90° clockwise / counter-clockwise |
| Arrow keys (Shift = one grid step) | Nudge by 1 cm |
| Del / Backspace | Delete |
| Ctrl+Z, Ctrl+Y / Ctrl+Shift+Z | Undo, redo |
| Ctrl+C / Ctrl+V / Ctrl+D / Ctrl+A | Copy / paste / duplicate / select all |
| Ctrl+S | Save |
| Esc | Clear selection |
## Configuration
All settings are optional and go under `PLUGINS_CONFIG['netbox_floorplanner']`.
| Setting | Default | Description |
|---|---|---|
| `default_width` | `2000` | Initial width (cm) for new floor plans |
| `default_depth` | `1500` | Initial depth (cm) for new floor plans |
| `default_grid_size` | `50` | Initial grid size (cm) for new floor plans |
| `default_rack_width` | `60` | Rack footprint width (cm) when the rack has no `outer_width` |
| `default_rack_depth` | `120` | Rack footprint depth (cm) when the rack has no `outer_depth` |
## REST API
| Endpoint | Methods | Description |
|---|---|---|
| `/api/plugins/floorplanner/floorplans/` | GET, POST, PUT, PATCH, DELETE | Standard NetBox CRUD for floor plans |
| `/api/plugins/floorplanner/floorplans/<id>/layout/` | GET, PUT | Read or atomically replace the complete layout |
Example layout payload:
```json
{
"settings": { "width": 2000, "depth": 1500, "grid_size": 50 },
"items": [
{ "item_type": "rack", "x": 300, "y": 200, "width": 60, "height": 120, "rotation": 0, "rack": 12 },
{ "item_type": "wall", "x": 0, "y": 600, "width": 800, "height": 15, "rotation": 0 },
{ "item_type": "label", "label": "Cold aisle A", "x": 300, "y": 330, "width": 200, "height": 40 }
]
}
```
`item_type` is one of `rack`, `device`, `wall`, `door`, `window`, `area`, `column`, `cooling`, `power` or `label`. `x` and `y` are the top-left corner of the unrotated shape in cm, and `rotation` is applied around its centre.
## Important semantics
- **Coordinates are centimetres.** The `height` field of an item is its depth on the floor (the Y extent), not its height in rack units.
- **The layout is saved as a whole.** Saving replaces all items of the plan in one transaction and writes a single change-log entry on the floor plan. Item IDs are not stable across saves, so reference racks and devices instead.
- **Racks and devices can be placed at most once per plan,** and must belong to the plan's site. Pasted copies of linked items become unlinked shapes.
- **Deleting a rack or device removes its item** from every floor plan. Deleting a site or location deletes its floor plans.
- **Permissions:** viewing a plan requires `view_floorplan`, and the designer and the layout `PUT` require `change_floorplan`. The rack and device lists in the palette follow the user's normal NetBox permissions.
- **The designer is a client-side editor.** Unsaved changes live only in the browser tab. The page warns before you navigate away from unsaved changes.
## Translations
The UI is in English and German and follows the language selected in the NetBox user preferences. The German catalogue is in `netbox_floorplanner/locale/de/LC_MESSAGES/`. After changing `django.po`, recompile it:
```bash
cd netbox_floorplanner && django-admin compilemessages -l de
```
## Uninstall
1. Optional: export the plans you want to keep (SVG/PNG or `GET …/layout/`).
2. Drop the plugin tables:
```bash
python manage.py migrate netbox_floorplanner zero
```
3. Remove `netbox_floorplanner` from `PLUGINS` and `PLUGINS_CONFIG`, and its line from `local_requirements.txt`.
4. Uninstall the package and restart NetBox:
```bash
pip uninstall netbox-floorplanner
sudo systemctl restart netbox netbox-rq
```
Uploaded background images stay in `MEDIA_ROOT/floorplanner/` and can be deleted manually.
+26
View File
@@ -0,0 +1,26 @@
from django.utils.translation import gettext_lazy as _
from netbox.plugins import PluginConfig
__version__ = '0.1.0'
class FloorPlannerConfig(PluginConfig):
name = 'netbox_floorplanner'
verbose_name = _('Floor Planner')
description = _('Drag & drop floor plan designer for sites and locations')
version = __version__
author = 'Louis'
base_url = 'floorplanner'
min_version = '4.7.2'
default_settings = {
# Default dimensions (cm) for new floor plans
'default_width': 2000,
'default_depth': 1500,
'default_grid_size': 50,
# Rack footprint (cm) used when a rack has no outer dimensions
'default_rack_width': 60,
'default_rack_depth': 120,
}
config = FloorPlannerConfig
View File
Whitespace-only changes.
+109
View File
@@ -0,0 +1,109 @@
from dcim.api.serializers import LocationSerializer, SiteSerializer
from dcim.choices import DeviceStatusChoices, RackStatusChoices
from dcim.models import Device, Rack
from django.utils.translation import gettext as _
from netbox.api.serializers import NetBoxModelSerializer
from rest_framework import serializers
from ..models import FloorPlan, FloorPlanItem
__all__ = ('FloorPlanSerializer', 'FloorPlanItemSerializer', 'LayoutSerializer')
class FloorPlanSerializer(NetBoxModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name='plugins-api:netbox_floorplanner-api:floorplan-detail')
site = SiteSerializer(nested=True)
location = LocationSerializer(nested=True, required=False, allow_null=True, default=None)
item_count = serializers.IntegerField(read_only=True, required=False)
class Meta:
model = FloorPlan
fields = (
'id', 'url', 'display', 'name', 'site', 'location', 'width', 'depth', 'grid_size',
'background_image', 'background_opacity', 'description', 'comments', 'item_count',
'tags', 'custom_fields', 'created', 'last_updated',
)
brief_fields = ('id', 'url', 'display', 'name', 'description')
def _object_info(obj, status_choices):
"""Compact representation of a linked NetBox object for the designer."""
role = getattr(obj, 'role', None)
tenant = getattr(obj, 'tenant', None)
info = {
'id': obj.pk,
'name': obj.name or str(obj),
'url': obj.get_absolute_url(),
'status': obj.status,
'status_label': str(dict(status_choices).get(obj.status, obj.status)),
'status_color': status_choices.colors.get(obj.status, 'gray'),
'role': role.name if role else None,
'role_color': f'#{role.color}' if role and role.color else None,
'tenant': tenant.name if tenant else None,
}
if isinstance(obj, Rack):
info['u_height'] = obj.u_height
info['device_count'] = getattr(obj, 'device_count', None)
return info
class FloorPlanItemSerializer(serializers.ModelSerializer):
rack = serializers.PrimaryKeyRelatedField(queryset=Rack.objects.all(), required=False, allow_null=True)
device = serializers.PrimaryKeyRelatedField(queryset=Device.objects.all(), required=False, allow_null=True)
object = serializers.SerializerMethodField(read_only=True)
class Meta:
model = FloorPlanItem
fields = (
'id', 'item_type', 'label', 'x', 'y', 'width', 'height', 'rotation', 'color', 'z_index',
'rack', 'device', 'properties', 'object',
)
read_only_fields = ('id',)
def get_object(self, item):
if item.rack_id:
return _object_info(item.rack, RackStatusChoices)
if item.device_id:
return _object_info(item.device, DeviceStatusChoices)
return None
def validate_color(self, value):
if value and not (len(value) == 7 and value.startswith('#')):
raise serializers.ValidationError(_('Color must be a hex value like #3b82f6.'))
return value
def validate(self, data):
floorplan = self.context.get('floorplan')
for field in ('rack', 'device'):
obj = data.get(field)
if obj is not None and floorplan is not None and obj.site_id != floorplan.site_id:
raise serializers.ValidationError({field: _('{obj} does not belong to site {site}.').format(
obj=obj, site=floorplan.site,
)})
if data.get('rack') and data.get('device'):
raise serializers.ValidationError(_('An item can be linked to a rack or a device, not both.'))
return data
class LayoutSettingsSerializer(serializers.ModelSerializer):
class Meta:
model = FloorPlan
fields = ('width', 'depth', 'grid_size')
class LayoutSerializer(serializers.Serializer):
settings = LayoutSettingsSerializer(required=False)
items = FloorPlanItemSerializer(many=True)
def validate_items(self, items):
seen = set()
for item in items:
for field in ('rack', 'device'):
obj = item.get(field)
if obj is None:
continue
key = (field, obj.pk)
if key in seen:
raise serializers.ValidationError(_('{obj} is placed more than once.').format(obj=obj))
seen.add(key)
return items
+10
View File
@@ -0,0 +1,10 @@
from netbox.api.routers import NetBoxRouter
from . import views
app_name = 'netbox_floorplanner-api'
router = NetBoxRouter()
router.register('floorplans', views.FloorPlanViewSet)
urlpatterns = router.urls
+58
View File
@@ -0,0 +1,58 @@
from django.db import transaction
from django.db.models import Count
from netbox.api.viewsets import NetBoxModelViewSet
from rest_framework.decorators import action
from rest_framework.response import Response
from .. import filtersets
from ..models import FloorPlan, FloorPlanItem
from .serializers import FloorPlanItemSerializer, FloorPlanSerializer, LayoutSerializer
class FloorPlanViewSet(NetBoxModelViewSet):
queryset = FloorPlan.objects.select_related('site', 'location').prefetch_related('tags').annotate(
item_count=Count('items')
)
serializer_class = FloorPlanSerializer
filterset_class = filtersets.FloorPlanFilterSet
@action(detail=True, methods=['get', 'put'], url_path='layout')
def layout(self, request, pk=None):
"""
GET returns all items of the floor plan; PUT replaces the complete layout
atomically. The queryset is restricted by NetBox according to the HTTP
method, so PUT requires the change permission on the floor plan.
"""
floorplan = self.get_object()
if request.method == 'PUT':
serializer = LayoutSerializer(data=request.data, context={'floorplan': floorplan, 'request': request})
serializer.is_valid(raise_exception=True)
with transaction.atomic():
floorplan.snapshot()
for attr, value in serializer.validated_data.get('settings', {}).items():
setattr(floorplan, attr, value)
floorplan.items.all().delete()
FloorPlanItem.objects.bulk_create([
FloorPlanItem(floorplan=floorplan, **item)
for item in serializer.validated_data['items']
])
floorplan.full_clean()
floorplan.save()
items = floorplan.items.select_related(
'rack__role', 'rack__tenant', 'device__role', 'device__tenant',
).annotate(device_count=Count('rack__devices'))
# device_count is annotated on the item; expose it on the rack for the serializer
for item in items:
if item.rack_id:
item.rack.device_count = item.device_count
return Response({
'settings': {
'width': floorplan.width,
'depth': floorplan.depth,
'grid_size': floorplan.grid_size,
},
'items': FloorPlanItemSerializer(items, many=True, context={'request': request}).data,
})
+28
View File
@@ -0,0 +1,28 @@
from django.utils.translation import gettext_lazy as _
from utilities.choices import ChoiceSet
class ItemTypeChoices(ChoiceSet):
TYPE_RACK = 'rack'
TYPE_DEVICE = 'device'
TYPE_WALL = 'wall'
TYPE_DOOR = 'door'
TYPE_WINDOW = 'window'
TYPE_AREA = 'area'
TYPE_COLUMN = 'column'
TYPE_COOLING = 'cooling'
TYPE_POWER = 'power'
TYPE_LABEL = 'label'
CHOICES = [
(TYPE_RACK, _('Rack'), 'blue'),
(TYPE_DEVICE, _('Device'), 'purple'),
(TYPE_WALL, _('Wall'), 'gray'),
(TYPE_DOOR, _('Door'), 'orange'),
(TYPE_WINDOW, _('Window'), 'cyan'),
(TYPE_AREA, _('Area'), 'green'),
(TYPE_COLUMN, _('Column'), 'gray'),
(TYPE_COOLING, _('Cooling unit'), 'teal'),
(TYPE_POWER, _('Power / UPS'), 'yellow'),
(TYPE_LABEL, _('Label'), 'dark'),
]
+45
View File
@@ -0,0 +1,45 @@
import django_filters
from dcim.models import Location, Site
from django.db.models import Q
from django.utils.translation import gettext_lazy as _
from netbox.filtersets import NetBoxModelFilterSet
from .models import FloorPlan
__all__ = ('FloorPlanFilterSet',)
class FloorPlanFilterSet(NetBoxModelFilterSet):
site_id = django_filters.ModelMultipleChoiceFilter(
queryset=Site.objects.all(),
label=_('Site (ID)'),
)
site = django_filters.ModelMultipleChoiceFilter(
field_name='site__slug',
queryset=Site.objects.all(),
to_field_name='slug',
label=_('Site (slug)'),
)
location_id = django_filters.ModelMultipleChoiceFilter(
queryset=Location.objects.all(),
label=_('Location (ID)'),
)
rack_id = django_filters.NumberFilter(
field_name='items__rack_id',
distinct=True,
label=_('Contains rack (ID)'),
)
class Meta:
model = FloorPlan
fields = ('id', 'name', 'description', 'width', 'depth', 'grid_size')
def search(self, queryset, name, value):
if not value.strip():
return queryset
return queryset.filter(
Q(name__icontains=value)
| Q(description__icontains=value)
| Q(site__name__icontains=value)
| Q(location__name__icontains=value)
)
+74
View File
@@ -0,0 +1,74 @@
from dcim.models import Location, Site
from django import forms
from django.utils.translation import gettext_lazy as _
from netbox.forms import NetBoxModelFilterSetForm, NetBoxModelForm, NetBoxModelImportForm
from netbox.plugins import get_plugin_config
from utilities.forms.fields import (
CSVModelChoiceField, CommentField, DynamicModelChoiceField, DynamicModelMultipleChoiceField, TagFilterField,
)
from utilities.forms.rendering import FieldSet
from .models import FloorPlan
__all__ = ('FloorPlanForm', 'FloorPlanFilterForm', 'FloorPlanImportForm')
class FloorPlanForm(NetBoxModelForm):
site = DynamicModelChoiceField(label=_('Site'), queryset=Site.objects.all())
location = DynamicModelChoiceField(
label=_('Location'),
queryset=Location.objects.all(),
required=False,
query_params={'site_id': '$site'},
)
comments = CommentField()
fieldsets = (
FieldSet('name', 'site', 'location', 'description', 'tags', name=_('Floor plan')),
FieldSet('width', 'depth', 'grid_size', name=_('Dimensions (cm)')),
FieldSet('background_image', 'background_opacity', name=_('Background')),
)
class Meta:
model = FloorPlan
fields = (
'name', 'site', 'location', 'description', 'width', 'depth', 'grid_size',
'background_image', 'background_opacity', 'comments', 'tags',
)
widgets = {
'background_image': forms.ClearableFileInput(attrs={'accept': 'image/*'}),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if not self.instance.pk:
for field, setting in (('width', 'default_width'), ('depth', 'default_depth'),
('grid_size', 'default_grid_size')):
self.fields[field].initial = get_plugin_config('netbox_floorplanner', setting)
class FloorPlanFilterForm(NetBoxModelFilterSetForm):
model = FloorPlan
fieldsets = (
FieldSet('q', 'filter_id', 'tag'),
FieldSet('site_id', 'location_id', name=_('Location')),
)
site_id = DynamicModelMultipleChoiceField(queryset=Site.objects.all(), required=False, label=_('Site'))
location_id = DynamicModelMultipleChoiceField(
queryset=Location.objects.all(),
required=False,
query_params={'site_id': '$site_id'},
label=_('Location'),
)
tag = TagFilterField(model)
class FloorPlanImportForm(NetBoxModelImportForm):
site = CSVModelChoiceField(label=_('Site'), queryset=Site.objects.all(), to_field_name='name')
location = CSVModelChoiceField(
label=_('Location'), queryset=Location.objects.all(), to_field_name='name', required=False,
)
class Meta:
model = FloorPlan
fields = ('name', 'site', 'location', 'description', 'width', 'depth', 'grid_size', 'comments', 'tags')
Binary file not shown.
@@ -0,0 +1,391 @@
# German translation for netbox-floorplanner.
msgid ""
msgstr ""
"Project-Id-Version: netbox-floorplanner 0.1.0\n"
"Language: de\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
# Plugin / navigation
msgid "Floor Planner"
msgstr "Grundrissplaner"
msgid "Drag & drop floor plan designer for sites and locations"
msgstr "Drag-&-Drop-Grundrissdesigner für Standorte und Räume"
msgid "Floor Plans"
msgstr "Grundrisse"
msgid "Add"
msgstr "Hinzufügen"
msgid "Import"
msgstr "Importieren"
# Item types
msgid "Rack"
msgstr "Rack"
msgid "Device"
msgstr "Gerät"
msgid "Wall"
msgstr "Wand"
msgid "Door"
msgstr "Tür"
msgid "Window"
msgstr "Fenster"
msgid "Area"
msgstr "Bereich"
msgid "Column"
msgstr "Säule"
msgid "Cooling unit"
msgstr "Klimagerät"
msgid "Power / UPS"
msgstr "Strom / USV"
msgid "Label"
msgstr "Beschriftung"
# Model fields
msgid "name"
msgstr "Name"
msgid "site"
msgstr "Standort"
msgid "location"
msgstr "Raum"
msgid "width"
msgstr "Breite"
msgid "depth"
msgstr "Tiefe"
msgid "grid size"
msgstr "Rastergröße"
msgid "background image"
msgstr "Hintergrundbild"
msgid "background opacity"
msgstr "Deckkraft des Hintergrunds"
msgid "description"
msgstr "Beschreibung"
msgid "comments"
msgstr "Kommentare"
msgid "floor plan"
msgstr "Grundriss"
msgid "floor plans"
msgstr "Grundrisse"
msgid "floor plan item"
msgstr "Grundriss-Element"
msgid "floor plan items"
msgstr "Grundriss-Elemente"
msgid "type"
msgstr "Typ"
msgid "label"
msgstr "Beschriftung"
msgid "X"
msgstr "X"
msgid "Y"
msgstr "Y"
msgid "height"
msgstr "Höhe"
msgid "rotation"
msgstr "Drehung"
msgid "color"
msgstr "Farbe"
msgid "z-index"
msgstr "Ebene"
msgid "rack"
msgstr "Rack"
msgid "device"
msgstr "Gerät"
msgid "properties"
msgstr "Eigenschaften"
msgid "Room width in centimeters"
msgstr "Raumbreite in Zentimetern"
msgid "Room depth in centimeters"
msgstr "Raumtiefe in Zentimetern"
msgid "Grid spacing in centimeters (used for snapping)"
msgstr "Rasterabstand in Zentimetern (für das Einrasten)"
msgid "Optional architectural drawing shown behind the plan, stretched to the room size"
msgstr "Optionale Bauzeichnung hinter dem Plan, auf die Raumgröße gestreckt"
msgid "Opacity of the background image in percent"
msgstr "Deckkraft des Hintergrundbilds in Prozent"
msgid "The location must belong to the selected site."
msgstr "Der Raum muss zum ausgewählten Standort gehören."
# Filters, forms, tables
msgid "Site (ID)"
msgstr "Standort (ID)"
msgid "Site (slug)"
msgstr "Standort (Slug)"
msgid "Location (ID)"
msgstr "Raum (ID)"
msgid "Contains rack (ID)"
msgstr "Enthält Rack (ID)"
msgid "Site"
msgstr "Standort"
msgid "Location"
msgstr "Raum"
msgid "Floor plan"
msgstr "Grundriss"
msgid "Dimensions (cm)"
msgstr "Abmessungen (cm)"
msgid "Background"
msgstr "Hintergrund"
msgid "Name"
msgstr "Name"
msgid "Width (cm)"
msgstr "Breite (cm)"
msgid "Depth (cm)"
msgstr "Tiefe (cm)"
msgid "Items"
msgstr "Elemente"
msgid "Racks"
msgstr "Racks"
# API validation
msgid "Color must be a hex value like #3b82f6."
msgstr "Die Farbe muss ein Hex-Wert wie #3b82f6 sein."
msgid "{obj} does not belong to site {site}."
msgstr "{obj} gehört nicht zum Standort {site}."
msgid "An item can be linked to a rack or a device, not both."
msgstr "Ein Element kann mit einem Rack oder einem Gerät verknüpft sein, nicht mit beiden."
msgid "{obj} is placed more than once."
msgstr "{obj} ist mehrfach platziert."
# Views / templates
msgid "Designer"
msgstr "Designer"
msgid "Open designer"
msgstr "Designer öffnen"
msgid "Dimensions"
msgstr "Abmessungen"
msgid "Grid size"
msgstr "Rastergröße"
msgid "Description"
msgstr "Beschreibung"
msgid "Add floor plan"
msgstr "Grundriss hinzufügen"
msgid "Show on floor plan"
msgstr "Im Grundriss anzeigen"
# Designer (JavaScript)
msgid "Save"
msgstr "Speichern"
msgid "Saving…"
msgstr "Speichere…"
msgid "Saved"
msgstr "Gespeichert"
msgid "Unsaved changes"
msgstr "Ungespeicherte Änderungen"
msgid "Save failed"
msgstr "Speichern fehlgeschlagen"
msgid "You have unsaved changes. Leave anyway?"
msgstr "Es gibt ungespeicherte Änderungen. Trotzdem verlassen?"
msgid "Undo"
msgstr "Rückgängig"
msgid "Redo"
msgstr "Wiederholen"
msgid "Delete"
msgstr "Löschen"
msgid "Duplicate"
msgstr "Duplizieren"
msgid "Rotate 90°"
msgstr "90° drehen"
msgid "Bring to front"
msgstr "In den Vordergrund"
msgid "Send to back"
msgstr "In den Hintergrund"
msgid "Zoom in"
msgstr "Vergrößern"
msgid "Zoom out"
msgstr "Verkleinern"
msgid "Fit to screen"
msgstr "An Bildschirm anpassen"
msgid "Snap to grid"
msgstr "Am Raster ausrichten"
msgid "Show grid"
msgstr "Raster anzeigen"
msgid "Fullscreen"
msgstr "Vollbild"
msgid "Export SVG"
msgstr "Als SVG exportieren"
msgid "Export PNG"
msgstr "Als PNG exportieren"
msgid "Shapes"
msgstr "Formen"
msgid "Devices"
msgstr "Geräte"
msgid "Search…"
msgstr "Suchen…"
msgid "Loading…"
msgstr "Lade…"
msgid "No racks found"
msgstr "Keine Racks gefunden"
msgid "No devices found"
msgstr "Keine Geräte gefunden"
msgid "Already placed"
msgstr "Bereits platziert"
msgid "Drag onto the plan or click to add"
msgstr "Auf den Plan ziehen oder zum Hinzufügen klicken"
msgid "Properties"
msgstr "Eigenschaften"
msgid "Nothing selected – plan settings"
msgstr "Nichts ausgewählt – Planeinstellungen"
msgid "{n} items selected"
msgstr "{n} Elemente ausgewählt"
msgid "Type"
msgstr "Typ"
msgid "X (cm)"
msgstr "X (cm)"
msgid "Y (cm)"
msgstr "Y (cm)"
msgid "Height (cm)"
msgstr "Höhe (cm)"
msgid "Rotation (°)"
msgstr "Drehung (°)"
msgid "Color"
msgstr "Farbe"
msgid "Reset color"
msgstr "Farbe zurücksetzen"
msgid "Linked object"
msgstr "Verknüpftes Objekt"
msgid "Open object"
msgstr "Objekt öffnen"
msgid "Grid size (cm)"
msgstr "Rastergröße (cm)"
msgid "Status"
msgstr "Status"
msgid "Role"
msgstr "Rolle"
msgid "Tenant"
msgstr "Mandant"
msgid "Height (U)"
msgstr "Höhe (HE)"
msgid "Devices in rack"
msgstr "Geräte im Rack"
msgid "Color by"
msgstr "Einfärben nach"
msgid "Item type"
msgstr "Elementtyp"
msgid "Highlight…"
msgstr "Hervorheben…"
msgid "Keyboard shortcuts"
msgstr "Tastenkürzel"
msgid "Drag: move · Alt: no snapping · Shift+click: multi-select · Space+drag / middle mouse: pan · Wheel: zoom · R: rotate · Del: delete · Ctrl+Z/Y: undo/redo · Ctrl+C/V/D: copy/paste/duplicate · Ctrl+S: save"
msgstr "Ziehen: verschieben · Alt: ohne Einrasten · Umschalt+Klick: Mehrfachauswahl · Leertaste+Ziehen / mittlere Maustaste: Ansicht verschieben · Mausrad: Zoom · R: drehen · Entf: löschen · Strg+Z/Y: rückgängig/wiederholen · Strg+C/V/D: kopieren/einfügen/duplizieren · Strg+S: speichern"
msgid "Wheel: zoom · Drag: pan · Click a rack or device to open it"
msgstr "Mausrad: Zoom · Ziehen: Ansicht verschieben · Rack oder Gerät anklicken, um es zu öffnen"
msgid "This floor plan is empty."
msgstr "Dieser Grundriss ist leer."
@@ -0,0 +1,74 @@
import django.core.validators
import django.db.models.deletion
import taggit.managers
import utilities.json
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('dcim', '__first__'),
('extras', '__first__'),
]
operations = [
migrations.CreateModel(
name='FloorPlan',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False)),
('created', models.DateTimeField(auto_now_add=True, null=True)),
('last_updated', models.DateTimeField(auto_now=True, null=True)),
('custom_field_data', models.JSONField(blank=True, default=dict, encoder=utilities.json.CustomFieldJSONEncoder)),
('name', models.CharField(max_length=100)),
('width', models.PositiveIntegerField(default=2000, validators=[django.core.validators.MinValueValidator(100), django.core.validators.MaxValueValidator(100000)])),
('depth', models.PositiveIntegerField(default=1500, validators=[django.core.validators.MinValueValidator(100), django.core.validators.MaxValueValidator(100000)])),
('grid_size', models.PositiveIntegerField(default=50, validators=[django.core.validators.MinValueValidator(5), django.core.validators.MaxValueValidator(1000)])),
('background_image', models.ImageField(blank=True, upload_to='floorplanner/')),
('background_opacity', models.PositiveSmallIntegerField(default=40, validators=[django.core.validators.MaxValueValidator(100)])),
('description', models.CharField(blank=True, max_length=200)),
('comments', models.TextField(blank=True)),
('site', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='floorplans', to='dcim.site')),
('location', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='floorplans', to='dcim.location')),
('tags', taggit.managers.TaggableManager(through='extras.TaggedItem', to='extras.Tag')),
],
options={
'verbose_name': 'floor plan',
'verbose_name_plural': 'floor plans',
'ordering': ('site', 'location', 'name'),
},
),
migrations.AddConstraint(
model_name='floorplan',
constraint=models.UniqueConstraint(
fields=('site', 'location', 'name'),
name='netbox_floorplanner_floorplan_unique_site_location_name',
),
),
migrations.CreateModel(
name='FloorPlanItem',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False)),
('item_type', models.CharField(max_length=30)),
('label', models.CharField(blank=True, max_length=100)),
('x', models.IntegerField(default=0)),
('y', models.IntegerField(default=0)),
('width', models.PositiveIntegerField(default=60)),
('height', models.PositiveIntegerField(default=60)),
('rotation', models.SmallIntegerField(default=0, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(359)])),
('color', models.CharField(blank=True, max_length=7)),
('z_index', models.SmallIntegerField(default=0)),
('properties', models.JSONField(blank=True, default=dict)),
('floorplan', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='items', to='netbox_floorplanner.floorplan')),
('rack', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='floorplan_items', to='dcim.rack')),
('device', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='floorplan_items', to='dcim.device')),
],
options={
'verbose_name': 'floor plan item',
'verbose_name_plural': 'floor plan items',
'ordering': ('floorplan', 'z_index', 'pk'),
},
),
]
Whitespace-only changes.
+133
View File
@@ -0,0 +1,133 @@
from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from netbox.models import NetBoxModel
from .choices import ItemTypeChoices
__all__ = ('FloorPlan', 'FloorPlanItem')
class FloorPlan(NetBoxModel):
name = models.CharField(verbose_name=_('name'), max_length=100)
site = models.ForeignKey(
to='dcim.Site',
on_delete=models.CASCADE,
related_name='floorplans',
verbose_name=_('site'),
)
location = models.ForeignKey(
to='dcim.Location',
on_delete=models.CASCADE,
related_name='floorplans',
blank=True,
null=True,
verbose_name=_('location'),
)
width = models.PositiveIntegerField(
verbose_name=_('width'),
default=2000,
validators=[MinValueValidator(100), MaxValueValidator(100000)],
help_text=_('Room width in centimeters'),
)
depth = models.PositiveIntegerField(
verbose_name=_('depth'),
default=1500,
validators=[MinValueValidator(100), MaxValueValidator(100000)],
help_text=_('Room depth in centimeters'),
)
grid_size = models.PositiveIntegerField(
verbose_name=_('grid size'),
default=50,
validators=[MinValueValidator(5), MaxValueValidator(1000)],
help_text=_('Grid spacing in centimeters (used for snapping)'),
)
background_image = models.ImageField(
verbose_name=_('background image'),
upload_to='floorplanner/',
blank=True,
help_text=_('Optional architectural drawing shown behind the plan, stretched to the room size'),
)
background_opacity = models.PositiveSmallIntegerField(
verbose_name=_('background opacity'),
default=40,
validators=[MaxValueValidator(100)],
help_text=_('Opacity of the background image in percent'),
)
description = models.CharField(verbose_name=_('description'), max_length=200, blank=True)
comments = models.TextField(verbose_name=_('comments'), blank=True)
class Meta:
ordering = ('site', 'location', 'name')
verbose_name = _('floor plan')
verbose_name_plural = _('floor plans')
constraints = (
models.UniqueConstraint(
fields=('site', 'location', 'name'),
name='netbox_floorplanner_floorplan_unique_site_location_name',
),
)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('plugins:netbox_floorplanner:floorplan', args=[self.pk])
def clean(self):
super().clean()
if self.location_id and self.site_id and self.location.site_id != self.site_id:
raise ValidationError({'location': _('The location must belong to the selected site.')})
class FloorPlanItem(models.Model):
"""
A single shape on a floor plan. Items are always written as a whole layout
through the layout API endpoint; changes are change-logged on the parent plan.
"""
floorplan = models.ForeignKey(
to=FloorPlan,
on_delete=models.CASCADE,
related_name='items',
verbose_name=_('floor plan'),
)
item_type = models.CharField(verbose_name=_('type'), max_length=30, choices=ItemTypeChoices)
label = models.CharField(verbose_name=_('label'), max_length=100, blank=True)
x = models.IntegerField(verbose_name=_('X'), default=0)
y = models.IntegerField(verbose_name=_('Y'), default=0)
width = models.PositiveIntegerField(verbose_name=_('width'), default=60)
height = models.PositiveIntegerField(verbose_name=_('height'), default=60)
rotation = models.SmallIntegerField(
verbose_name=_('rotation'),
default=0,
validators=[MinValueValidator(0), MaxValueValidator(359)],
)
color = models.CharField(verbose_name=_('color'), max_length=7, blank=True)
z_index = models.SmallIntegerField(verbose_name=_('z-index'), default=0)
rack = models.ForeignKey(
to='dcim.Rack',
on_delete=models.CASCADE,
related_name='floorplan_items',
blank=True,
null=True,
verbose_name=_('rack'),
)
device = models.ForeignKey(
to='dcim.Device',
on_delete=models.CASCADE,
related_name='floorplan_items',
blank=True,
null=True,
verbose_name=_('device'),
)
properties = models.JSONField(verbose_name=_('properties'), default=dict, blank=True)
class Meta:
ordering = ('floorplan', 'z_index', 'pk')
verbose_name = _('floor plan item')
verbose_name_plural = _('floor plan items')
def __str__(self):
return self.label or f'{self.get_item_type_display()} #{self.pk}'
+30
View File
@@ -0,0 +1,30 @@
from django.utils.translation import gettext_lazy as _
from netbox.plugins import PluginMenu, PluginMenuButton, PluginMenuItem
menu = PluginMenu(
label=_('Floor Planner'),
icon_class='mdi mdi-floor-plan',
groups=(
(_('Floor Plans'), (
PluginMenuItem(
link='plugins:netbox_floorplanner:floorplan_list',
link_text=_('Floor Plans'),
permissions=['netbox_floorplanner.view_floorplan'],
buttons=(
PluginMenuButton(
link='plugins:netbox_floorplanner:floorplan_add',
title=_('Add'),
icon_class='mdi mdi-plus-thick',
permissions=['netbox_floorplanner.add_floorplan'],
),
PluginMenuButton(
link='plugins:netbox_floorplanner:floorplan_bulk_import',
title=_('Import'),
icon_class='mdi mdi-upload',
permissions=['netbox_floorplanner.add_floorplan'],
),
),
),
)),
),
)
+16
View File
@@ -0,0 +1,16 @@
from netbox.search import SearchIndex
from .models import FloorPlan
class FloorPlanIndex(SearchIndex):
model = FloorPlan
fields = (
('name', 100),
('description', 500),
('comments', 5000),
)
display_attrs = ('site', 'location', 'description')
indexes = (FloorPlanIndex,)
@@ -0,0 +1,160 @@
.fp-root {
--fp-bg: #f1f5f9;
--fp-floor: #ffffff;
--fp-grid: #e2e8f0;
--fp-wall: #334155;
--fp-text: #0f172a;
--fp-panel: #ffffff;
--fp-border: #dee2e6;
--fp-accent: #206bc4;
--fp-muted: #6c757d;
display: flex;
flex-direction: column;
border: 1px solid var(--fp-border);
border-radius: 6px;
background: var(--fp-panel);
overflow: hidden;
outline: none;
}
[data-bs-theme="dark"] .fp-root {
--fp-bg: #111827;
--fp-floor: #1f2937;
--fp-grid: #2d3a4d;
--fp-wall: #94a3b8;
--fp-text: #e5e7eb;
--fp-panel: #182433;
--fp-border: #2c3e50;
--fp-muted: #9aa5b1;
}
.fp-root:fullscreen { border-radius: 0; }
.fp-root:fullscreen .fp-body { height: auto; flex: 1; }
.fp-toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
padding: 6px 8px;
border-bottom: 1px solid var(--fp-border);
}
.fp-group { align-items: center; }
.fp-btn { border: 1px solid var(--fp-border); background: transparent; color: inherit; }
.fp-btn:hover { background: rgba(32, 107, 196, .1); }
.fp-btn.active { background: rgba(32, 107, 196, .18); color: var(--fp-accent); border-color: var(--fp-accent); }
.fp-btn:disabled { opacity: .4; }
.fp-btn .mdi { font-size: 1.1rem; line-height: 1; }
.fp-zoom-label { min-width: 52px; text-align: center; font-size: .8rem; font-variant-numeric: tabular-nums; }
.fp-select { width: auto; }
.fp-search { width: 200px; }
.fp-spacer { flex: 1; }
.fp-save-state { font-size: .8rem; color: var(--fp-muted); }
.fp-save-state.dirty { color: #f59f00; }
.fp-save-state.ok { color: #2fb344; }
.fp-save-state.error { color: #d63939; }
.fp-body { display: flex; height: 72vh; min-height: 420px; }
.fp-view .fp-body { height: 62vh; }
.fp-canvas { position: relative; flex: 1; min-width: 0; background: var(--fp-bg); }
.fp-svg { display: block; width: 100%; height: 100%; user-select: none; touch-action: none; cursor: default; }
.fp-view .fp-svg { cursor: grab; }
.fp-svg.fp-panning, .fp-svg.fp-panning * { cursor: grab !important; }
.fp-edit .fp-item { cursor: move; }
.fp-view .fp-item.fp-linked { cursor: pointer; }
.fp-item.fp-linked:hover > rect:first-child { filter: brightness(1.12); }
.fp-item.fp-dimmed { opacity: .2; }
.fp-selection { fill: none; stroke: var(--fp-accent); pointer-events: none; }
.fp-handle { fill: #ffffff; stroke: var(--fp-accent); }
.fp-rot { cursor: grab; }
.fp-rot-line { stroke: var(--fp-accent); pointer-events: none; }
.fp-band { fill: rgba(32, 107, 196, .08); stroke: var(--fp-accent); pointer-events: none; }
.fp-guide { stroke: #e8590c; pointer-events: none; }
.fp-highlight { fill: none; stroke: #f59f00; pointer-events: none; animation: fp-pulse 1.2s ease-in-out infinite; }
@keyframes fp-pulse { 50% { stroke-opacity: .2; } }
.fp-palette, .fp-panel {
width: 240px;
flex-shrink: 0;
overflow-y: auto;
padding: 8px;
font-size: .85rem;
}
.fp-palette { border-right: 1px solid var(--fp-border); }
.fp-panel { border-left: 1px solid var(--fp-border); }
.fp-palette-title {
font-size: .7rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: .04em;
color: var(--fp-muted);
margin: 10px 0 6px;
}
.fp-palette-title:first-child { margin-top: 0; }
.fp-shapes { display: grid; grid-template-columns: 1fr 1fr; gap: 4px; }
.fp-shapes .fp-entry { flex-direction: column; justify-content: center; text-align: center; padding: 6px 4px; }
.fp-shapes .fp-entry .mdi { font-size: 1.3rem; }
.fp-entry {
display: flex;
align-items: center;
gap: 6px;
padding: 4px 6px;
border: 1px solid var(--fp-border);
border-radius: 4px;
margin-bottom: 3px;
cursor: grab;
background: var(--fp-panel);
}
.fp-entry:hover { border-color: var(--fp-accent); background: rgba(32, 107, 196, .06); }
.fp-entry.disabled { opacity: .5; cursor: default; }
.fp-entry.disabled:hover { border-color: var(--fp-border); background: var(--fp-panel); }
.fp-entry-label { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.fp-shapes .fp-entry-label { flex: none; font-size: .75rem; }
.fp-entry-sub { font-size: .7rem; color: var(--fp-muted); }
.fp-entry-check { color: #2fb344; }
.fp-objlist { max-height: 30vh; overflow-y: auto; }
.fp-palette-search { margin-top: 10px; }
.fp-muted { color: var(--fp-muted); font-size: .8rem; }
.fp-hint { margin-top: 10px; font-size: .75rem; color: var(--fp-muted); }
.fp-field { display: block; margin-bottom: 8px; width: 100%; }
.fp-field > span { display: block; font-size: .75rem; color: var(--fp-muted); margin-bottom: 2px; }
.fp-row { display: flex; gap: 6px; }
.fp-color { display: flex; gap: 6px; }
.fp-type-badge { font-weight: 600; margin-bottom: 8px; }
.fp-info { display: grid; grid-template-columns: auto 1fr; gap: 2px 8px; margin-bottom: 10px; font-size: .8rem; }
.fp-info dt { font-weight: 400; color: var(--fp-muted); }
.fp-info dd { margin: 0; overflow: hidden; text-overflow: ellipsis; }
.fp-tooltip {
position: absolute;
z-index: 10;
pointer-events: none;
min-width: 160px;
max-width: 280px;
padding: 8px 10px;
border-radius: 6px;
background: var(--fp-panel);
border: 1px solid var(--fp-border);
box-shadow: 0 4px 16px rgba(0, 0, 0, .15);
font-size: .8rem;
}
.fp-statusbar {
padding: 4px 8px;
border-top: 1px solid var(--fp-border);
font-size: .72rem;
color: var(--fp-muted);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
@media (max-width: 992px) {
.fp-body { flex-direction: column; height: auto; }
.fp-canvas { height: 60vh; }
.fp-palette, .fp-panel { width: auto; max-height: 30vh; border: none; border-top: 1px solid var(--fp-border); }
}
File diff suppressed because it is too large. Load diff
+81
View File
@@ -0,0 +1,81 @@
"""
User-facing strings of the JavaScript designer. The English text is the msgid,
so the designer falls back to English if a translation is missing.
"""
from django.utils.translation import gettext, gettext_noop
JS_STRINGS = (
gettext_noop('Save'),
gettext_noop('Saving…'),
gettext_noop('Saved'),
gettext_noop('Unsaved changes'),
gettext_noop('Save failed'),
gettext_noop('You have unsaved changes. Leave anyway?'),
gettext_noop('Undo'),
gettext_noop('Redo'),
gettext_noop('Delete'),
gettext_noop('Duplicate'),
gettext_noop('Rotate 90°'),
gettext_noop('Bring to front'),
gettext_noop('Send to back'),
gettext_noop('Zoom in'),
gettext_noop('Zoom out'),
gettext_noop('Fit to screen'),
gettext_noop('Snap to grid'),
gettext_noop('Show grid'),
gettext_noop('Fullscreen'),
gettext_noop('Export SVG'),
gettext_noop('Export PNG'),
gettext_noop('Shapes'),
gettext_noop('Racks'),
gettext_noop('Devices'),
gettext_noop('Search…'),
gettext_noop('Loading…'),
gettext_noop('No racks found'),
gettext_noop('No devices found'),
gettext_noop('Already placed'),
gettext_noop('Drag onto the plan or click to add'),
gettext_noop('Properties'),
gettext_noop('Floor plan'),
gettext_noop('Nothing selected – plan settings'),
gettext_noop('{n} items selected'),
gettext_noop('Type'),
gettext_noop('Label'),
gettext_noop('X (cm)'),
gettext_noop('Y (cm)'),
gettext_noop('Width (cm)'),
gettext_noop('Depth (cm)'),
gettext_noop('Height (cm)'),
gettext_noop('Rotation (°)'),
gettext_noop('Color'),
gettext_noop('Reset color'),
gettext_noop('Linked object'),
gettext_noop('Open object'),
gettext_noop('Grid size (cm)'),
gettext_noop('Status'),
gettext_noop('Role'),
gettext_noop('Tenant'),
gettext_noop('Height (U)'),
gettext_noop('Devices in rack'),
gettext_noop('Color by'),
gettext_noop('Item type'),
gettext_noop('Highlight…'),
gettext_noop('Rack'),
gettext_noop('Device'),
gettext_noop('Wall'),
gettext_noop('Door'),
gettext_noop('Window'),
gettext_noop('Area'),
gettext_noop('Column'),
gettext_noop('Cooling unit'),
gettext_noop('Power / UPS'),
gettext_noop('Label'),
gettext_noop('Keyboard shortcuts'),
gettext_noop('Drag: move · Alt: no snapping · Shift+click: multi-select · Space+drag / middle mouse: pan · Wheel: zoom · R: rotate · Del: delete · Ctrl+Z/Y: undo/redo · Ctrl+C/V/D: copy/paste/duplicate · Ctrl+S: save'),
gettext_noop('Wheel: zoom · Drag: pan · Click a rack or device to open it'),
gettext_noop('This floor plan is empty.'),
)
def get_js_strings():
return {s: gettext(s) for s in JS_STRINGS}
+26
View File
@@ -0,0 +1,26 @@
import django_tables2 as tables
from django.utils.translation import gettext_lazy as _
from netbox.tables import NetBoxTable, columns
from .models import FloorPlan
__all__ = ('FloorPlanTable',)
class FloorPlanTable(NetBoxTable):
name = tables.Column(verbose_name=_('Name'), linkify=True)
site = tables.Column(verbose_name=_('Site'), linkify=True)
location = tables.Column(verbose_name=_('Location'), linkify=True)
width = tables.Column(verbose_name=_('Width (cm)'))
depth = tables.Column(verbose_name=_('Depth (cm)'))
item_count = tables.Column(verbose_name=_('Items'))
rack_count = tables.Column(verbose_name=_('Racks'))
tags = columns.TagColumn(url_name='plugins:netbox_floorplanner:floorplan_list')
class Meta(NetBoxTable.Meta):
model = FloorPlan
fields = (
'pk', 'id', 'name', 'site', 'location', 'width', 'depth', 'grid_size', 'item_count', 'rack_count',
'description', 'tags', 'created', 'last_updated',
)
default_columns = ('name', 'site', 'location', 'width', 'depth', 'rack_count', 'description')
+22
View File
@@ -0,0 +1,22 @@
from netbox.plugins import PluginTemplateExtension
from .models import FloorPlanItem
class RackFloorPlanButton(PluginTemplateExtension):
"""Adds a "Show on floor plan" button to racks and devices that are placed on a plan."""
models = ['dcim.rack', 'dcim.device']
def buttons(self):
obj = self.context['object']
field = 'rack' if obj._meta.model_name == 'rack' else 'device'
item = FloorPlanItem.objects.filter(**{field: obj}).select_related('floorplan').first()
if item is None:
return ''
return self.render('netbox_floorplanner/inc/floorplan_button.html', extra_context={
'floorplan': item.floorplan,
'highlight': f'{field}-{obj.pk}',
})
template_extensions = [RackFloorPlanButton]
@@ -0,0 +1,65 @@
{% extends 'generic/object.html' %}
{% load helpers %}
{% load i18n %}
{% block extra_controls %}
{% if perms.netbox_floorplanner.change_floorplan %}
<a href="{% url 'plugins:netbox_floorplanner:floorplan_designer' pk=object.pk %}" class="btn btn-primary">
<i class="mdi mdi-pencil-ruler"></i> {% trans "Open designer" %}
</a>
{% endif %}
{% endblock %}
{% block content %}
<div class="row mb-3">
<div class="col col-12">
{% include 'netbox_floorplanner/inc/designer.html' %}
</div>
</div>
<div class="row">
<div class="col col-12 col-xl-6">
<div class="card">
<h2 class="card-header">{% trans "Floor plan" %}</h2>
<table class="table table-hover attr-table">
<tr>
<th scope="row">{% trans "Name" %}</th>
<td>{{ object.name }}</td>
</tr>
<tr>
<th scope="row">{% trans "Site" %}</th>
<td>{{ object.site|linkify }}</td>
</tr>
<tr>
<th scope="row">{% trans "Location" %}</th>
<td>{{ object.location|linkify|placeholder }}</td>
</tr>
<tr>
<th scope="row">{% trans "Dimensions" %}</th>
<td>{{ object.width }} × {{ object.depth }} cm</td>
</tr>
<tr>
<th scope="row">{% trans "Grid size" %}</th>
<td>{{ object.grid_size }} cm</td>
</tr>
<tr>
<th scope="row">{% trans "Items" %}</th>
<td>{{ object.item_count }}</td>
</tr>
<tr>
<th scope="row">{% trans "Racks" %}</th>
<td>{{ object.rack_count }}</td>
</tr>
<tr>
<th scope="row">{% trans "Description" %}</th>
<td>{{ object.description|placeholder }}</td>
</tr>
</table>
</div>
{% include 'inc/panels/tags.html' %}
</div>
<div class="col col-12 col-xl-6">
{% include 'inc/panels/custom_fields.html' %}
{% include 'inc/panels/comments.html' %}
</div>
</div>
{% endblock %}
@@ -0,0 +1,5 @@
{% extends 'generic/object.html' %}
{% block content %}
{% include 'netbox_floorplanner/inc/designer.html' %}
{% endblock %}
@@ -0,0 +1,5 @@
{% load static %}
<link rel="stylesheet" href="{% static 'netbox_floorplanner/floorplanner.css' %}?v=0.1.0">
<div class="fp-root" data-fp-config="fp-config"></div>
{{ designer_config|json_script:"fp-config" }}
<script src="{% static 'netbox_floorplanner/floorplanner.js' %}?v=0.1.0"></script>
@@ -0,0 +1,4 @@
{% load i18n %}
<a href="{{ floorplan.get_absolute_url }}?highlight={{ highlight }}" class="btn btn-outline-primary">
<i class="mdi mdi-floor-plan"></i> {% trans "Show on floor plan" %}
</a>
@@ -0,0 +1,10 @@
{% extends 'generic/object_children.html' %}
{% load i18n %}
{% block extra_controls %}
{% if perms.netbox_floorplanner.add_floorplan %}
<a href="{% url 'plugins:netbox_floorplanner:floorplan_add' %}?{{ add_params }}&return_url={{ request.path }}" class="btn btn-primary">
<i class="mdi mdi-plus-thick"></i> {% trans "Add floor plan" %}
</a>
{% endif %}
{% endblock %}
+9
View File
@@ -0,0 +1,9 @@
from django.urls import include, path
from utilities.urls import get_model_urls
from . import views # noqa: F401 – registers the model views
urlpatterns = (
path('floorplans/', include(get_model_urls('netbox_floorplanner', 'floorplan', detail=False))),
path('floorplans/<int:pk>/', include(get_model_urls('netbox_floorplanner', 'floorplan'))),
)
+164
View File
@@ -0,0 +1,164 @@
from dcim.models import Location, Site
from django.db.models import Count, Q
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from netbox.plugins import get_plugin_config
from netbox.views import generic
from utilities.permissions import get_permission_for_model
from utilities.views import ViewTab, register_model_view
from . import filtersets, forms, tables
from .choices import ItemTypeChoices
from .models import FloorPlan
from .strings import get_js_strings
def floorplans_queryset():
return FloorPlan.objects.select_related('site', 'location').annotate(
item_count=Count('items', distinct=True),
rack_count=Count('items', filter=Q(items__rack__isnull=False), distinct=True),
)
def designer_config(request, floorplan, mode):
"""Configuration handed to the JavaScript designer via json_script."""
rack_filter = f'site_id={floorplan.site_id}'
if floorplan.location_id:
rack_filter += f'&location_id={floorplan.location_id}'
return {
'mode': mode,
'id': floorplan.pk,
'name': floorplan.name,
'settings': {
'width': floorplan.width,
'depth': floorplan.depth,
'grid_size': floorplan.grid_size,
},
'background': {
'url': floorplan.background_image.url if floorplan.background_image else None,
'opacity': floorplan.background_opacity / 100,
},
'api': {
'layout': reverse('plugins-api:netbox_floorplanner-api:floorplan-layout', args=[floorplan.pk]),
'racks': reverse('dcim-api:rack-list') + f'?{rack_filter}&limit=1000&ordering=name',
'devices': reverse('dcim-api:device-list') + f'?{rack_filter}&rack_id=null&limit=1000&ordering=name',
},
'highlight': request.GET.get('highlight', ''),
'defaults': {
'rack_width': get_plugin_config('netbox_floorplanner', 'default_rack_width'),
'rack_depth': get_plugin_config('netbox_floorplanner', 'default_rack_depth'),
},
'types': {choice[0]: str(choice[1]) for choice in ItemTypeChoices.CHOICES},
'strings': get_js_strings(),
}
@register_model_view(FloorPlan, 'list', path='', detail=False)
class FloorPlanListView(generic.ObjectListView):
queryset = floorplans_queryset()
table = tables.FloorPlanTable
filterset = filtersets.FloorPlanFilterSet
filterset_form = forms.FloorPlanFilterForm
@register_model_view(FloorPlan)
class FloorPlanView(generic.ObjectView):
queryset = floorplans_queryset()
def get_extra_context(self, request, instance):
return {'designer_config': designer_config(request, instance, 'view')}
@register_model_view(FloorPlan, 'designer', path='designer')
class FloorPlanDesignerView(generic.ObjectView):
queryset = FloorPlan.objects.select_related('site', 'location')
template_name = 'netbox_floorplanner/floorplan_designer.html'
tab = ViewTab(
label=_('Designer'),
permission='netbox_floorplanner.change_floorplan',
weight=100,
)
def get_required_permission(self):
return get_permission_for_model(FloorPlan, 'change')
def get_extra_context(self, request, instance):
return {'designer_config': designer_config(request, instance, 'edit')}
@register_model_view(FloorPlan, 'add', detail=False)
@register_model_view(FloorPlan, 'edit')
class FloorPlanEditView(generic.ObjectEditView):
queryset = FloorPlan.objects.all()
form = forms.FloorPlanForm
def alter_object(self, obj, request, url_args, url_kwargs):
# Allow pre-filling site/location from the Site or Location tab
if not obj.pk:
if site_id := request.GET.get('site'):
obj.site_id = site_id
if location_id := request.GET.get('location'):
obj.location_id = location_id
return obj
@register_model_view(FloorPlan, 'delete')
class FloorPlanDeleteView(generic.ObjectDeleteView):
queryset = FloorPlan.objects.all()
@register_model_view(FloorPlan, 'bulk_import', path='import', detail=False)
class FloorPlanBulkImportView(generic.BulkImportView):
queryset = FloorPlan.objects.all()
model_form = forms.FloorPlanImportForm
@register_model_view(FloorPlan, 'bulk_delete', path='delete', detail=False)
class FloorPlanBulkDeleteView(generic.BulkDeleteView):
queryset = floorplans_queryset()
filterset = filtersets.FloorPlanFilterSet
table = tables.FloorPlanTable
#
# "Floor plans" tabs on Site and Location
#
class BaseFloorPlanChildrenView(generic.ObjectChildrenView):
child_model = FloorPlan
table = tables.FloorPlanTable
filterset = filtersets.FloorPlanFilterSet
template_name = 'netbox_floorplanner/object_floorplans.html'
filter_field = None
def get_children(self, request, parent):
return floorplans_queryset().restrict(request.user, 'view').filter(**{self.filter_field: parent})
def get_extra_context(self, request, instance):
return {'add_params': f'{self.filter_field}={instance.pk}' + (
f'&site={instance.site_id}' if self.filter_field == 'location' else ''
)}
@register_model_view(Site, 'floorplans', path='floorplans')
class SiteFloorPlansView(BaseFloorPlanChildrenView):
queryset = Site.objects.all()
filter_field = 'site'
tab = ViewTab(
label=_('Floor Plans'),
badge=lambda obj: obj.floorplans.count(),
permission='netbox_floorplanner.view_floorplan',
weight=1500,
)
@register_model_view(Location, 'floorplans', path='floorplans')
class LocationFloorPlansView(BaseFloorPlanChildrenView):
queryset = Location.objects.all()
filter_field = 'location'
tab = ViewTab(
label=_('Floor Plans'),
badge=lambda obj: obj.floorplans.count(),
permission='netbox_floorplanner.view_floorplan',
weight=1500,
)
+26
View File
@@ -0,0 +1,26 @@
[build-system]
requires = ["setuptools>=69", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "netbox-floorplanner"
version = "0.1.0"
description = "Modern drag & drop floor plan designer for NetBox 4.7+"
readme = "README.md"
license = "Apache-2.0"
requires-python = ">=3.12"
authors = [{ name = "Louis" }]
classifiers = [
"Framework :: Django",
"Programming Language :: Python :: 3",
]
[tool.setuptools.packages.find]
include = ["netbox_floorplanner*"]
[tool.setuptools.package-data]
netbox_floorplanner = [
"templates/**/*",
"static/**/*",
"locale/**/*",
]