Compare commits

..

24 Commits

Author SHA1 Message Date
Martin Hauser
21d039c0a9 fix(extras): Reject unknown custom fields
Add validation to reject unknown custom field names during API updates.
Ensure model.clean() normalization is preserved in serializers to remove
stale custom field data from both the database and change logs.
Filter stale keys during serialization to prevent lingering references.

Fixes #21529
2026-04-08 23:31:45 +02:00
github-actions
dbb871b75a Update source translation strings 2026-04-08 05:32:13 +00:00
Jeremy Stretch
d75583828b Fixes #21835: Remove misleading help text from ColorField (#21852) 2026-04-07 22:50:41 +02:00
Martin Hauser
7ff7c6d17e feat(ui): Add colored rendering for related object attributes
Introduce `colored` parameter to `RelatedObjectAttr`,
`NestedObjectAttr`, and `ObjectListAttr` to render objects as colored
badges when they expose a `color` attribute.
Update badge template tag to support hex colors and optional URLs.
Apply colored rendering to circuit types, device roles, rack roles,
inventory item roles, and VM roles.

Fixes #21430
2026-04-07 16:40:18 -04:00
Jeremy Stretch
296e708e09 Fixes #21814: Correct display of custom script "last run" time (#21853) 2026-04-07 18:11:12 +02:00
Jeremy Stretch
1bbecef77d Fixes #21841: Fix display of the "edit" button for script modules (#21851) 2026-04-07 08:48:40 -07:00
Jeremy Stretch
1ebeb71ad8 Fixes #21845: Remove whitespace from connection values in interface CSV exports (#21850) 2026-04-07 10:38:22 -05:00
Martin Hauser
d6a1cc5558 test(tables): Add reusable StandardTableTestCase
Introduce `TableTestCases.StandardTableTestCase`, a shared base class
for model-backed table smoke tests. It currently discovers sortable
columns from list-view querysets and verifies that each renders without
exceptions in both ascending and descending order.

Add per-table smoke tests across circuits, core, dcim, extras, ipam,
tenancy, users, virtualization, vpn, and wireless apps.

Fixes #21766
2026-04-06 13:53:13 -04:00
github-actions
09f7df0726 Update source translation strings 2026-04-04 05:26:28 +00:00
Martin Hauser
f242f17ce5 Fixes #21542: Increase supported interface speed values above 2.1 Tbps (#21834) 2026-04-03 16:55:11 -05:00
bctiemann
7d71503ea2 Merge pull request #21837 from netbox-community/21795-update-humanize_speed-to-support-decimal-gbpstbps-output
Closes #21795: Improve humanize_speed formatting for decimal Gbps/Tbps values
2026-04-03 13:06:55 -04:00
Jeremy Stretch
d0651f6474 Release v4.5.7 (#21838) 2026-04-03 12:24:24 -04:00
Jeremy Stretch
fecd4e2f97 Closes #21839: Document the RQ configuration parameter 2026-04-03 12:01:15 -04:00
Martin Hauser
e07a5966ae feat(dcim): Support decimal Gbps/Tbps output in humanize_speed
Update the humanize_speed template filter to always use the largest
appropriate unit, even when the result is not a whole number.
Previously, values like 2500000 Kbps rendered as "2500 Mbps" instead of
"2.5 Gbps", and 1600000000 Kbps rendered as "1600 Gbps" instead of
"1.6 Tbps".

Fixes #21795
2026-04-03 15:36:42 +02:00
github-actions
f058ee3d60 Update source translation strings 2026-04-03 05:31:13 +00:00
bctiemann
49ba0dd495 Fix filtering of object-type custom fields when "is empty" is selected (#21829) 2026-04-02 16:17:49 -07:00
Martin Hauser
b4ee2cf447 fix(dcim): Refresh stale CablePath references during serialization (#21815)
Cable edits can delete and recreate CablePath rows while endpoint
instances remain in memory. Deferred event serialization can then
encounter a stale `_path` reference and raise `CablePath.DoesNotExist`.

Refresh stale `_path` references through `PathEndpoint.path` and route
internal callers through that accessor. Update `EventContext` to track
the latest serialization source for coalesced duplicate enqueues, while
eagerly freezing delete-event payloads before row removal.

Also avoid mutating `event_rule.action_data` when merging the event
payload.

Fixes #21498
2026-04-02 15:49:42 -07:00
Jason Novinger
34098bb20a Fixes #21760: Add 1C2P:2C1P breakout cable profile (#21824)
* Add Breakout1C2Px2C1PCableProfile class
* Add BREAKOUT_1C2P_2C1P choice
* Add new CableProfileChoices (BREAKOUT_1C2P_2C1P)

---------

Co-authored-by: Paulo Santos <paulo.banon@gmail.com>
2026-04-02 23:33:35 +02:00
Jonathan Senecal
a19daa5466 Fixes #21095: Add IEC unit labels support and rename humanize helpers to be unit-agnostic (#21789) 2026-04-02 14:30:49 -07:00
bctiemann
40eec679d9 Fixes: #21696 - Upgrade to django-rq==4.0.1 (#21805) 2026-04-02 14:09:53 -07:00
Martin Hauser
57556e3fdb fix(tables): Correct sortable column definitions across tables
Fix broken sorting metadata caused by incorrect accessors, field
references, and naming mismatches in several table definitions.

Update accessor paths for provider_account and device order_by; add
order_by mapping for the is_active property column; correct field name
typos such as termination_count to terminations_count; rename the
ssl_validation column to ssl_verification to match the model field; and
mark computed columns as orderable=False where sorting is not supported.

Fixes #21825
2026-04-02 16:20:53 -04:00
Arthur Hanson
f2d8ae29c2 21701 Allow scripts to be uploaded via post to API (#21756)
* #21701 allow upload script via API

* #21701 allow upload script via API

* add extra test

* change to use Script api endpoint

* ruff fix

* review feedback:

* review feedback:

* review feedback:

* Fix permission check, perform_create delegation, and test mock setup

- destroy() now checks extras.delete_script (queryset is Script.objects.all())
- create() delegates to self.perform_create() instead of calling serializer.save() directly
- Add comment explaining why update/partial_update intentionally return 405
- Fix test_upload_script_module: set mock_storage.save.return_value so file_path
  receives a real string after the _save_upload return-value fix; add DB existence check

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Return 400 instead of 500 on duplicate script module upload

Catch IntegrityError from the unique (file_root, file_path) constraint
and re-raise as a ValidationError so the API returns a 400 with a clear
message rather than a 500.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Validate upload_file + data_source conflict for multipart requests

DRF 3.16 Serializer.get_value() uses parse_html_dict() or empty for all
HTML/multipart input. A flat key like data_source=2 produces an empty
dict ({}), which is falsy, so it falls back to empty and the nested
field is silently skipped. data.get('data_source') is therefore always
None in multipart requests, bypassing the conflict check.

Fix: also check self.initial_data for data_source and data_file in all
three guards in validate(), so the raw submitted value is detected even
when DRF's HTML parser drops the deserialized object.

Add test_upload_with_data_source_fails to cover the multipart conflict
path explicitly.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Require data_file when data_source is specified

data_source alone is not a valid creation payload — a data_file must
also be provided to identify which file within the source to sync.
Add the corresponding validation error and a test to cover the case.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Align ManagedFileForm validation with API serializer rules

Add the missing checks to ManagedFileForm.clean():
- upload_file + data_source is rejected (matches API)
- data_source without data_file is rejected with a specific message
- Update the 'nothing provided' error to mention data source + data file

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Revert "Align ManagedFileForm validation with API serializer rules"

This reverts commit f0ac7c3bd2.

* Align API validation messages with UI; restore complete checks

- Match UI error messages for upload+data_file conflict and no-source case
- Keep API-only guards for upload+data_source and data_source-without-data_file
- Restore test_upload_with_data_source_fails

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Run source/file conflict checks before super().validate() / full_clean()

super().validate() calls full_clean() on the model instance, which raises
a unique-constraint error for (file_root, file_path) when file_path is
empty (e.g. data_source-only requests). Move the conflict guards above the
super() call so they produce clear, actionable error messages before
full_clean() has a chance to surface confusing database-level errors.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* destroy() deletes ScriptModule, not Script

DELETE /api/extras/scripts/<pk>/ now deletes the entire ScriptModule
(matching the UI's delete view), including modules with no Script
children (e.g. sync hasn't run yet). Permission check updated to
delete_scriptmodule. The queryset restriction for destroy is removed
since the module is deleted via script.module, not super().destroy().

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* review feedback:

* cleanup

* cleanup

* cleanup

* cleanup

* change to ScriptModule

* change to ScriptModule

* change to ScriptModule

* update docs

* cleanup

* restore file

* cleanup

* cleanup

* cleanup

* cleanup

* cleanup

* keep only upload functionality

* cleanup

* cleanup

* cleanup

* change to scripts/upload api

* cleanup

* cleanup

* cleanup

* cleanup

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 08:42:14 -04:00
github-actions
f6eb5dda0f Update source translation strings 2026-04-02 05:30:39 +00:00
Mark Robert Coleman
c7bbfb24c5 Fix single {module} token rejection at nested module bay depth (#21740)
* Fix single {module} token rejection at nested depth (#20474)

A module type with a single {module} placeholder in component template
names could not be installed in a nested module bay (depth > 1) because
the form validation required an exact match between the token count and
the tree depth. This resolves the issue by treating a single {module}
token as a reference to the immediate parent bay's position, regardless
of nesting depth. Multi-token behavior is unchanged.

Refactors resolve_name() and resolve_label() into a shared
_resolve_module_placeholder() helper to eliminate duplication.

Fixes: #20474

* Address review feedback for PR #21740 (fixes #20474)

- Rebase on latest main to resolve merge conflicts
- Extract shared module bay traversal and {module} token resolution
  into dcim/utils.py (get_module_bay_positions, resolve_module_placeholder)
- Update ModuleCommonForm, ModularComponentTemplateModel, and
  ModuleBayTemplate to use shared utility functions
- Add {module} token validation to ModuleSerializer.validate() so the
  API enforces the same rules as the UI form
- Remove duplicated _get_module_bay_tree (form) and _get_module_tree
  (model) methods in favor of the shared routine
2026-04-01 16:19:43 -07:00
343 changed files with 17708 additions and 24493 deletions

View File

@@ -15,7 +15,7 @@ body:
attributes:
label: NetBox version
description: What version of NetBox are you currently running?
placeholder: v4.5.6
placeholder: v4.5.7
validations:
required: true
- type: dropdown

View File

@@ -27,7 +27,7 @@ body:
attributes:
label: NetBox Version
description: What version of NetBox are you currently running?
placeholder: v4.5.6
placeholder: v4.5.7
validations:
required: true
- type: dropdown

View File

@@ -8,7 +8,7 @@ body:
attributes:
label: NetBox Version
description: What version of NetBox are you currently running?
placeholder: v4.5.6
placeholder: v4.5.7
validations:
required: true
- type: dropdown

View File

@@ -92,7 +92,7 @@ jobs:
pip install coverage tblib
- name: Build documentation
run: zensical build
run: mkdocs build
- name: Collect static files
run: python netbox/manage.py collectstatic --no-input

View File

@@ -21,11 +21,11 @@ repos:
language: system
pass_filenames: false
types: [python]
- id: zensical-build
- id: mkdocs-build
name: "Build documentation"
description: "Build the documentation with Zensical"
description: "Build the documentation with mkdocs"
files: 'docs/'
entry: zensical build
entry: mkdocs build
language: system
pass_filenames: false
- id: yarn-validate

View File

@@ -1,10 +1,10 @@
version: 2
build:
os: ubuntu-24.04
os: ubuntu-22.04
tools:
python: "3.12"
commands:
- pip install -r requirements.txt
- python -m zensical build --config-file mkdocs.yml
- mkdir -p $READTHEDOCS_OUTPUT/html/
- cp -r netbox/project-static/docs/* $READTHEDOCS_OUTPUT/html/
mkdocs:
configuration: mkdocs.yml
python:
install:
- requirements: requirements.txt

View File

@@ -4,7 +4,7 @@ colorama
# The Python web framework on which NetBox is built
# https://docs.djangoproject.com/en/stable/releases/
Django==6.0.*
Django==5.2.*
# Django middleware which permits cross-domain API requests
# https://github.com/adamchainz/django-cors-headers/blob/main/CHANGELOG.rst
@@ -35,9 +35,7 @@ django-pglocks
# Prometheus metrics library for Django
# https://github.com/korfuri/django-prometheus/blob/master/CHANGELOG.md
# TODO: 2.4.1 is incompatible with Django>=6.0, but a fixed release is expected
# https://github.com/django-commons/django-prometheus/issues/494
django-prometheus>=2.4.0,<2.5.0,!=2.4.1
django-prometheus
# Django caching backend using Redis
# https://github.com/jazzband/django-redis/blob/master/CHANGELOG.rst
@@ -49,8 +47,7 @@ django-rich
# Django integration for RQ (Reqis queuing)
# https://github.com/rq/django-rq/blob/master/CHANGELOG.md
# See https://github.com/netbox-community/netbox/issues/21696
django-rq<4.0
django-rq
# Provides a variety of storage backends
# https://github.com/jschneier/django-storages/blob/master/CHANGELOG.rst
@@ -101,6 +98,10 @@ jsonschema
# https://python-markdown.github.io/changelog/
Markdown
# MkDocs
# https://github.com/mkdocs/mkdocs/releases
mkdocs<2.0
# MkDocs Material theme (for documentation build)
# https://squidfunk.github.io/mkdocs-material/changelog/
mkdocs-material
@@ -174,7 +175,3 @@ tablib
# Timezone data (required by django-timezone-field on Python 3.9+)
# https://github.com/python/tzdata/blob/master/NEWS.md
tzdata
# Documentation builder (succeeds mkdocs)
# https://github.com/zensical/zensical
zensical

View File

@@ -2,7 +2,7 @@
"openapi": "3.0.3",
"info": {
"title": "NetBox REST API",
"version": "4.5.6",
"version": "4.5.7",
"license": {
"name": "Apache v2 License"
}
@@ -25468,7 +25468,7 @@
"type": "array",
"items": {
"type": "string",
"x-spec-enum-id": "5e0f85310f0184ea"
"x-spec-enum-id": "f566e6df6572f5d0"
}
},
"explode": true,
@@ -25488,7 +25488,7 @@
"type": "array",
"items": {
"type": "string",
"x-spec-enum-id": "5e0f85310f0184ea"
"x-spec-enum-id": "f566e6df6572f5d0"
}
},
"explode": true,
@@ -25501,7 +25501,7 @@
"type": "array",
"items": {
"type": "string",
"x-spec-enum-id": "5e0f85310f0184ea"
"x-spec-enum-id": "f566e6df6572f5d0"
}
},
"explode": true,
@@ -25514,7 +25514,7 @@
"type": "array",
"items": {
"type": "string",
"x-spec-enum-id": "5e0f85310f0184ea"
"x-spec-enum-id": "f566e6df6572f5d0"
}
},
"explode": true,
@@ -25527,7 +25527,7 @@
"type": "array",
"items": {
"type": "string",
"x-spec-enum-id": "5e0f85310f0184ea"
"x-spec-enum-id": "f566e6df6572f5d0"
}
},
"explode": true,
@@ -25540,7 +25540,7 @@
"type": "array",
"items": {
"type": "string",
"x-spec-enum-id": "5e0f85310f0184ea"
"x-spec-enum-id": "f566e6df6572f5d0"
}
},
"explode": true,
@@ -25553,7 +25553,7 @@
"type": "array",
"items": {
"type": "string",
"x-spec-enum-id": "5e0f85310f0184ea"
"x-spec-enum-id": "f566e6df6572f5d0"
}
},
"explode": true,
@@ -25566,7 +25566,7 @@
"type": "array",
"items": {
"type": "string",
"x-spec-enum-id": "5e0f85310f0184ea"
"x-spec-enum-id": "f566e6df6572f5d0"
}
},
"explode": true,
@@ -25579,7 +25579,7 @@
"type": "array",
"items": {
"type": "string",
"x-spec-enum-id": "5e0f85310f0184ea"
"x-spec-enum-id": "f566e6df6572f5d0"
}
},
"explode": true,
@@ -25592,7 +25592,7 @@
"type": "array",
"items": {
"type": "string",
"x-spec-enum-id": "5e0f85310f0184ea"
"x-spec-enum-id": "f566e6df6572f5d0"
}
},
"explode": true,
@@ -25605,7 +25605,7 @@
"type": "array",
"items": {
"type": "string",
"x-spec-enum-id": "5e0f85310f0184ea"
"x-spec-enum-id": "f566e6df6572f5d0"
}
},
"explode": true,
@@ -25618,7 +25618,7 @@
"type": "array",
"items": {
"type": "string",
"x-spec-enum-id": "5e0f85310f0184ea"
"x-spec-enum-id": "f566e6df6572f5d0"
}
},
"explode": true,
@@ -138591,6 +138591,50 @@
}
}
},
"/api/extras/scripts/upload/": {
"post": {
"operationId": "extras_scripts_upload_create",
"description": "Post a list of script module objects.",
"tags": [
"extras"
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ScriptModuleRequest"
}
},
"multipart/form-data": {
"schema": {
"$ref": "#/components/schemas/ScriptModuleRequest"
}
}
},
"required": true
},
"security": [
{
"cookieAuth": []
},
{
"tokenAuth": []
}
],
"responses": {
"201": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ScriptModule"
}
}
},
"description": ""
}
}
}
},
"/api/extras/subscriptions/": {
"get": {
"operationId": "extras_subscriptions_list",
@@ -228046,13 +228090,14 @@
"trunk-4c6p",
"trunk-4c8p",
"trunk-8c4p",
"breakout-1c2p-2c1p",
"breakout-1c4p-4c1p",
"breakout-1c6p-6c1p",
"breakout-2c4p-8c1p-shuffle"
],
"type": "string",
"description": "* `single-1c1p` - 1C1P\n* `single-1c2p` - 1C2P\n* `single-1c4p` - 1C4P\n* `single-1c6p` - 1C6P\n* `single-1c8p` - 1C8P\n* `single-1c12p` - 1C12P\n* `single-1c16p` - 1C16P\n* `trunk-2c1p` - 2C1P trunk\n* `trunk-2c2p` - 2C2P trunk\n* `trunk-2c4p` - 2C4P trunk\n* `trunk-2c4p-shuffle` - 2C4P trunk (shuffle)\n* `trunk-2c6p` - 2C6P trunk\n* `trunk-2c8p` - 2C8P trunk\n* `trunk-2c12p` - 2C12P trunk\n* `trunk-4c1p` - 4C1P trunk\n* `trunk-4c2p` - 4C2P trunk\n* `trunk-4c4p` - 4C4P trunk\n* `trunk-4c4p-shuffle` - 4C4P trunk (shuffle)\n* `trunk-4c6p` - 4C6P trunk\n* `trunk-4c8p` - 4C8P trunk\n* `trunk-8c4p` - 8C4P trunk\n* `breakout-1c4p-4c1p` - 1C4P:4C1P breakout\n* `breakout-1c6p-6c1p` - 1C6P:6C1P breakout\n* `breakout-2c4p-8c1p-shuffle` - 2C4P:8C1P breakout (shuffle)",
"x-spec-enum-id": "5e0f85310f0184ea"
"description": "* `single-1c1p` - 1C1P\n* `single-1c2p` - 1C2P\n* `single-1c4p` - 1C4P\n* `single-1c6p` - 1C6P\n* `single-1c8p` - 1C8P\n* `single-1c12p` - 1C12P\n* `single-1c16p` - 1C16P\n* `trunk-2c1p` - 2C1P trunk\n* `trunk-2c2p` - 2C2P trunk\n* `trunk-2c4p` - 2C4P trunk\n* `trunk-2c4p-shuffle` - 2C4P trunk (shuffle)\n* `trunk-2c6p` - 2C6P trunk\n* `trunk-2c8p` - 2C8P trunk\n* `trunk-2c12p` - 2C12P trunk\n* `trunk-4c1p` - 4C1P trunk\n* `trunk-4c2p` - 4C2P trunk\n* `trunk-4c4p` - 4C4P trunk\n* `trunk-4c4p-shuffle` - 4C4P trunk (shuffle)\n* `trunk-4c6p` - 4C6P trunk\n* `trunk-4c8p` - 4C8P trunk\n* `trunk-8c4p` - 8C4P trunk\n* `breakout-1c2p-2c1p` - 1C2P:2C1P breakout\n* `breakout-1c4p-4c1p` - 1C4P:4C1P breakout\n* `breakout-1c6p-6c1p` - 1C6P:6C1P breakout\n* `breakout-2c4p-8c1p-shuffle` - 2C4P:8C1P breakout (shuffle)",
"x-spec-enum-id": "f566e6df6572f5d0"
},
"label": {
"type": "string",
@@ -228078,6 +228123,7 @@
"4C6P trunk",
"4C8P trunk",
"8C4P trunk",
"1C2P:2C1P breakout",
"1C4P:4C1P breakout",
"1C6P:6C1P breakout",
"2C4P:8C1P breakout (shuffle)"
@@ -228282,13 +228328,14 @@
"trunk-4c6p",
"trunk-4c8p",
"trunk-8c4p",
"breakout-1c2p-2c1p",
"breakout-1c4p-4c1p",
"breakout-1c6p-6c1p",
"breakout-2c4p-8c1p-shuffle"
],
"type": "string",
"description": "* `single-1c1p` - 1C1P\n* `single-1c2p` - 1C2P\n* `single-1c4p` - 1C4P\n* `single-1c6p` - 1C6P\n* `single-1c8p` - 1C8P\n* `single-1c12p` - 1C12P\n* `single-1c16p` - 1C16P\n* `trunk-2c1p` - 2C1P trunk\n* `trunk-2c2p` - 2C2P trunk\n* `trunk-2c4p` - 2C4P trunk\n* `trunk-2c4p-shuffle` - 2C4P trunk (shuffle)\n* `trunk-2c6p` - 2C6P trunk\n* `trunk-2c8p` - 2C8P trunk\n* `trunk-2c12p` - 2C12P trunk\n* `trunk-4c1p` - 4C1P trunk\n* `trunk-4c2p` - 4C2P trunk\n* `trunk-4c4p` - 4C4P trunk\n* `trunk-4c4p-shuffle` - 4C4P trunk (shuffle)\n* `trunk-4c6p` - 4C6P trunk\n* `trunk-4c8p` - 4C8P trunk\n* `trunk-8c4p` - 8C4P trunk\n* `breakout-1c4p-4c1p` - 1C4P:4C1P breakout\n* `breakout-1c6p-6c1p` - 1C6P:6C1P breakout\n* `breakout-2c4p-8c1p-shuffle` - 2C4P:8C1P breakout (shuffle)",
"x-spec-enum-id": "5e0f85310f0184ea"
"description": "* `single-1c1p` - 1C1P\n* `single-1c2p` - 1C2P\n* `single-1c4p` - 1C4P\n* `single-1c6p` - 1C6P\n* `single-1c8p` - 1C8P\n* `single-1c12p` - 1C12P\n* `single-1c16p` - 1C16P\n* `trunk-2c1p` - 2C1P trunk\n* `trunk-2c2p` - 2C2P trunk\n* `trunk-2c4p` - 2C4P trunk\n* `trunk-2c4p-shuffle` - 2C4P trunk (shuffle)\n* `trunk-2c6p` - 2C6P trunk\n* `trunk-2c8p` - 2C8P trunk\n* `trunk-2c12p` - 2C12P trunk\n* `trunk-4c1p` - 4C1P trunk\n* `trunk-4c2p` - 4C2P trunk\n* `trunk-4c4p` - 4C4P trunk\n* `trunk-4c4p-shuffle` - 4C4P trunk (shuffle)\n* `trunk-4c6p` - 4C6P trunk\n* `trunk-4c8p` - 4C8P trunk\n* `trunk-8c4p` - 8C4P trunk\n* `breakout-1c2p-2c1p` - 1C2P:2C1P breakout\n* `breakout-1c4p-4c1p` - 1C4P:4C1P breakout\n* `breakout-1c6p-6c1p` - 1C6P:6C1P breakout\n* `breakout-2c4p-8c1p-shuffle` - 2C4P:8C1P breakout (shuffle)",
"x-spec-enum-id": "f566e6df6572f5d0"
},
"tenant": {
"oneOf": [
@@ -254488,8 +254535,7 @@
"size": {
"type": "integer",
"maximum": 2147483647,
"minimum": 0,
"title": "Size (MB)"
"minimum": 0
},
"owner": {
"oneOf": [
@@ -254774,14 +254820,15 @@
"trunk-4c6p",
"trunk-4c8p",
"trunk-8c4p",
"breakout-1c2p-2c1p",
"breakout-1c4p-4c1p",
"breakout-1c6p-6c1p",
"breakout-2c4p-8c1p-shuffle",
""
],
"type": "string",
"description": "* `single-1c1p` - 1C1P\n* `single-1c2p` - 1C2P\n* `single-1c4p` - 1C4P\n* `single-1c6p` - 1C6P\n* `single-1c8p` - 1C8P\n* `single-1c12p` - 1C12P\n* `single-1c16p` - 1C16P\n* `trunk-2c1p` - 2C1P trunk\n* `trunk-2c2p` - 2C2P trunk\n* `trunk-2c4p` - 2C4P trunk\n* `trunk-2c4p-shuffle` - 2C4P trunk (shuffle)\n* `trunk-2c6p` - 2C6P trunk\n* `trunk-2c8p` - 2C8P trunk\n* `trunk-2c12p` - 2C12P trunk\n* `trunk-4c1p` - 4C1P trunk\n* `trunk-4c2p` - 4C2P trunk\n* `trunk-4c4p` - 4C4P trunk\n* `trunk-4c4p-shuffle` - 4C4P trunk (shuffle)\n* `trunk-4c6p` - 4C6P trunk\n* `trunk-4c8p` - 4C8P trunk\n* `trunk-8c4p` - 8C4P trunk\n* `breakout-1c4p-4c1p` - 1C4P:4C1P breakout\n* `breakout-1c6p-6c1p` - 1C6P:6C1P breakout\n* `breakout-2c4p-8c1p-shuffle` - 2C4P:8C1P breakout (shuffle)",
"x-spec-enum-id": "5e0f85310f0184ea"
"description": "* `single-1c1p` - 1C1P\n* `single-1c2p` - 1C2P\n* `single-1c4p` - 1C4P\n* `single-1c6p` - 1C6P\n* `single-1c8p` - 1C8P\n* `single-1c12p` - 1C12P\n* `single-1c16p` - 1C16P\n* `trunk-2c1p` - 2C1P trunk\n* `trunk-2c2p` - 2C2P trunk\n* `trunk-2c4p` - 2C4P trunk\n* `trunk-2c4p-shuffle` - 2C4P trunk (shuffle)\n* `trunk-2c6p` - 2C6P trunk\n* `trunk-2c8p` - 2C8P trunk\n* `trunk-2c12p` - 2C12P trunk\n* `trunk-4c1p` - 4C1P trunk\n* `trunk-4c2p` - 4C2P trunk\n* `trunk-4c4p` - 4C4P trunk\n* `trunk-4c4p-shuffle` - 4C4P trunk (shuffle)\n* `trunk-4c6p` - 4C6P trunk\n* `trunk-4c8p` - 4C8P trunk\n* `trunk-8c4p` - 8C4P trunk\n* `breakout-1c2p-2c1p` - 1C2P:2C1P breakout\n* `breakout-1c4p-4c1p` - 1C4P:4C1P breakout\n* `breakout-1c6p-6c1p` - 1C6P:6C1P breakout\n* `breakout-2c4p-8c1p-shuffle` - 2C4P:8C1P breakout (shuffle)",
"x-spec-enum-id": "f566e6df6572f5d0"
},
"tenant": {
"oneOf": [
@@ -262819,15 +262866,13 @@
"type": "integer",
"maximum": 2147483647,
"minimum": 0,
"nullable": true,
"title": "Memory (MB)"
"nullable": true
},
"disk": {
"type": "integer",
"maximum": 2147483647,
"minimum": 0,
"nullable": true,
"title": "Disk (MB)"
"nullable": true
},
"description": {
"type": "string",
@@ -270340,6 +270385,56 @@
"data"
]
},
"ScriptModule": {
"type": "object",
"description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)",
"properties": {
"id": {
"type": "integer",
"readOnly": true
},
"display": {
"type": "string",
"readOnly": true
},
"file_path": {
"type": "string",
"readOnly": true
},
"created": {
"type": "string",
"format": "date-time",
"readOnly": true
},
"last_updated": {
"type": "string",
"format": "date-time",
"readOnly": true,
"nullable": true
}
},
"required": [
"created",
"display",
"file_path",
"id",
"last_updated"
]
},
"ScriptModuleRequest": {
"type": "object",
"description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)",
"properties": {
"file": {
"type": "string",
"format": "binary",
"writeOnly": true
}
},
"required": [
"file"
]
},
"Service": {
"type": "object",
"description": "Base serializer class for models inheriting from PrimaryModel.",
@@ -275384,8 +275479,7 @@
"size": {
"type": "integer",
"maximum": 2147483647,
"minimum": 0,
"title": "Size (MB)"
"minimum": 0
},
"owner": {
"allOf": [
@@ -275456,8 +275550,7 @@
"size": {
"type": "integer",
"maximum": 2147483647,
"minimum": 0,
"title": "Size (MB)"
"minimum": 0
},
"owner": {
"oneOf": [
@@ -275662,15 +275755,13 @@
"type": "integer",
"maximum": 2147483647,
"minimum": 0,
"nullable": true,
"title": "Memory (MB)"
"nullable": true
},
"disk": {
"type": "integer",
"maximum": 2147483647,
"minimum": 0,
"nullable": true,
"title": "Disk (MB)"
"nullable": true
},
"description": {
"type": "string",
@@ -275926,15 +276017,13 @@
"type": "integer",
"maximum": 2147483647,
"minimum": 0,
"nullable": true,
"title": "Memory (MB)"
"nullable": true
},
"disk": {
"type": "integer",
"maximum": 2147483647,
"minimum": 0,
"nullable": true,
"title": "Disk (MB)"
"nullable": true
},
"description": {
"type": "string",
@@ -277220,14 +277309,15 @@
"trunk-4c6p",
"trunk-4c8p",
"trunk-8c4p",
"breakout-1c2p-2c1p",
"breakout-1c4p-4c1p",
"breakout-1c6p-6c1p",
"breakout-2c4p-8c1p-shuffle",
""
],
"type": "string",
"description": "* `single-1c1p` - 1C1P\n* `single-1c2p` - 1C2P\n* `single-1c4p` - 1C4P\n* `single-1c6p` - 1C6P\n* `single-1c8p` - 1C8P\n* `single-1c12p` - 1C12P\n* `single-1c16p` - 1C16P\n* `trunk-2c1p` - 2C1P trunk\n* `trunk-2c2p` - 2C2P trunk\n* `trunk-2c4p` - 2C4P trunk\n* `trunk-2c4p-shuffle` - 2C4P trunk (shuffle)\n* `trunk-2c6p` - 2C6P trunk\n* `trunk-2c8p` - 2C8P trunk\n* `trunk-2c12p` - 2C12P trunk\n* `trunk-4c1p` - 4C1P trunk\n* `trunk-4c2p` - 4C2P trunk\n* `trunk-4c4p` - 4C4P trunk\n* `trunk-4c4p-shuffle` - 4C4P trunk (shuffle)\n* `trunk-4c6p` - 4C6P trunk\n* `trunk-4c8p` - 4C8P trunk\n* `trunk-8c4p` - 8C4P trunk\n* `breakout-1c4p-4c1p` - 1C4P:4C1P breakout\n* `breakout-1c6p-6c1p` - 1C6P:6C1P breakout\n* `breakout-2c4p-8c1p-shuffle` - 2C4P:8C1P breakout (shuffle)",
"x-spec-enum-id": "5e0f85310f0184ea"
"description": "* `single-1c1p` - 1C1P\n* `single-1c2p` - 1C2P\n* `single-1c4p` - 1C4P\n* `single-1c6p` - 1C6P\n* `single-1c8p` - 1C8P\n* `single-1c12p` - 1C12P\n* `single-1c16p` - 1C16P\n* `trunk-2c1p` - 2C1P trunk\n* `trunk-2c2p` - 2C2P trunk\n* `trunk-2c4p` - 2C4P trunk\n* `trunk-2c4p-shuffle` - 2C4P trunk (shuffle)\n* `trunk-2c6p` - 2C6P trunk\n* `trunk-2c8p` - 2C8P trunk\n* `trunk-2c12p` - 2C12P trunk\n* `trunk-4c1p` - 4C1P trunk\n* `trunk-4c2p` - 4C2P trunk\n* `trunk-4c4p` - 4C4P trunk\n* `trunk-4c4p-shuffle` - 4C4P trunk (shuffle)\n* `trunk-4c6p` - 4C6P trunk\n* `trunk-4c8p` - 4C8P trunk\n* `trunk-8c4p` - 8C4P trunk\n* `breakout-1c2p-2c1p` - 1C2P:2C1P breakout\n* `breakout-1c4p-4c1p` - 1C4P:4C1P breakout\n* `breakout-1c6p-6c1p` - 1C6P:6C1P breakout\n* `breakout-2c4p-8c1p-shuffle` - 2C4P:8C1P breakout (shuffle)",
"x-spec-enum-id": "f566e6df6572f5d0"
},
"tenant": {
"oneOf": [
@@ -285520,15 +285610,13 @@
"type": "integer",
"maximum": 2147483647,
"minimum": 0,
"nullable": true,
"title": "Memory (MB)"
"nullable": true
},
"disk": {
"type": "integer",
"maximum": 2147483647,
"minimum": 0,
"nullable": true,
"title": "Disk (MB)"
"nullable": true
},
"description": {
"type": "string",

18
docs/_theme/partials/copyright.html vendored Normal file
View File

@@ -0,0 +1,18 @@
<div class="md-copyright">
{% if config.copyright %}
<div class="md-copyright__highlight">
{{ config.copyright }}
</div>
{% endif %}
{% if not config.extra.generator == false %}
Made with
<a href="https://squidfunk.github.io/mkdocs-material/" target="_blank" rel="noopener">
Material for MkDocs
</a>
{% endif %}
</div>
{% if not config.extra.build_public %}
<div class="md-copyright">
Documentation is being served locally
</div>
{% endif %}

View File

@@ -21,7 +21,6 @@ Some configuration parameters are primarily controlled via NetBox's admin interf
* [`BANNER_BOTTOM`](./miscellaneous.md#banner_bottom)
* [`BANNER_LOGIN`](./miscellaneous.md#banner_login)
* [`BANNER_TOP`](./miscellaneous.md#banner_top)
* [`CHANGELOG_RETAIN_CREATE_LAST_UPDATE`](./miscellaneous.md#changelog_retain_create_last_update)
* [`CHANGELOG_RETENTION`](./miscellaneous.md#changelog_retention)
* [`CUSTOM_VALIDATORS`](./data-validation.md#custom_validators)
* [`DEFAULT_USER_PREFERENCES`](./default-values.md#default_user_preferences)

View File

@@ -73,23 +73,6 @@ This data enables the project maintainers to estimate how many NetBox deployment
---
## CHANGELOG_RETAIN_CREATE_LAST_UPDATE
!!! tip "Dynamic Configuration Parameter"
Default: `False`
When pruning expired changelog entries (per `CHANGELOG_RETENTION`), retain each non-deleted object's original `create`
change record and its most recent `update` change record. If an object has a `delete` change record, its changelog
entries are pruned normally according to `CHANGELOG_RETENTION`.
!!! note
For objects without a `delete` change record, the original `create` record and most recent `update` record are
exempt from pruning. All other changelog records (including intermediate `update` records and all `delete` records)
remain subject to pruning per `CHANGELOG_RETENTION`.
---
## CHANGELOG_RETENTION
!!! tip "Dynamic Configuration Parameter"
@@ -237,6 +220,14 @@ This parameter defines the URL of the repository that will be checked for new Ne
---
## RQ
Default: `{}` (Empty)
This is a wrapper for passing global configuration parameters to [Django RQ](https://github.com/rq/django-rq) to customize its behavior. It is employed within NetBox primarily to alter conditions during testing.
---
## RQ_DEFAULT_TIMEOUT
Default: `300`

View File

@@ -63,7 +63,6 @@ NetBox supports limited custom validation for custom field values. Following are
* Text: Regular expression (optional)
* Integer: Minimum and/or maximum value (optional)
* Selection: Must exactly match one of the prescribed choices
* JSON: Must adhere to the defined validation schema (if any)
### Custom Selection Fields

View File

@@ -384,6 +384,18 @@ A calendar date. Returns a `datetime.date` object.
A complete date & time. Returns a `datetime.datetime` object.
## Uploading Scripts via the API
Script modules can be uploaded to NetBox via the REST API by sending a `multipart/form-data` POST request to `/api/extras/scripts/upload/`. The caller must have the `extras.add_scriptmodule` and `core.add_managedfile` permissions.
```no-highlight
curl -X POST \
-H "Authorization: Token $TOKEN" \
-H "Accept: application/json; indent=4" \
-F "file=@/path/to/myscript.py" \
http://netbox/api/extras/scripts/upload/
```
## Running Custom Scripts
!!! note

View File

@@ -97,7 +97,7 @@ NetBox uses [`pre-commit`](https://pre-commit.com/) to automatically validate co
* Run the `ruff` Python linter
* Run Django's internal system check
* Check for missing database migrations
* Validate any changes to the documentation with `zensical`
* Validate any changes to the documentation with `mkdocs`
* Validate Typescript & Sass styling with `yarn`
* Ensure that any modified static front end assets have been recompiled

View File

@@ -45,7 +45,6 @@ These are considered the "core" application models which are used to model netwo
* [core.DataSource](../models/core/datasource.md)
* [core.Job](../models/core/job.md)
* [dcim.Cable](../models/dcim/cable.md)
* [dcim.CableBundle](../models/dcim/cablebundle.md)
* [dcim.Device](../models/dcim/device.md)
* [dcim.DeviceType](../models/dcim/devicetype.md)
* [dcim.Module](../models/dcim/module.md)
@@ -74,7 +73,6 @@ These are considered the "core" application models which are used to model netwo
* [tenancy.Tenant](../models/tenancy/tenant.md)
* [virtualization.Cluster](../models/virtualization/cluster.md)
* [virtualization.VirtualMachine](../models/virtualization/virtualmachine.md)
* [virtualization.VirtualMachineType](../models/virtualization/virtualmachinetype.md)
* [vpn.IKEPolicy](../models/vpn/ikepolicy.md)
* [vpn.IKEProposal](../models/vpn/ikeproposal.md)
* [vpn.IPSecPolicy](../models/vpn/ipsecpolicy.md)
@@ -94,7 +92,6 @@ Organization models are used to organize and classify primary models.
* [dcim.DeviceRole](../models/dcim/devicerole.md)
* [dcim.Manufacturer](../models/dcim/manufacturer.md)
* [dcim.Platform](../models/dcim/platform.md)
* [dcim.RackGroup](../models/dcim/rackgroup.md)
* [dcim.RackRole](../models/dcim/rackrole.md)
* [ipam.ASNRange](../models/ipam/asnrange.md)
* [ipam.RIR](../models/ipam/rir.md)

View File

@@ -47,7 +47,7 @@ If a new Django release is adopted or other major dependencies (Python, PostgreS
Start the documentation server and navigate to the current version of the installation docs:
```no-highlight
zensical serve
mkdocs serve
```
Follow these instructions to perform a new installation of NetBox in a temporary environment. This process must not be automated: The goal of this step is to catch any errors or omissions in the documentation and ensure that it is kept up to date for each release. Make any necessary changes to the documentation before proceeding with the release.

View File

@@ -5,6 +5,10 @@ img {
margin-right: auto;
}
.md-content img {
background-color: rgba(255, 255, 255, 0.64);
}
/* Tables */
table {
margin-bottom: 24px;

View File

@@ -1,44 +1,26 @@
# Virtualization
Virtual machines, clusters, and standalone hypervisors can be modeled in NetBox alongside physical infrastructure. IP addresses and other resources are assigned to these objects just like physical objects, providing a seamless integration between physical and virtual networks.
Virtual machines and clusters can be modeled in NetBox alongside physical infrastructure. IP addresses and other resources are assigned to these objects just like physical objects, providing a seamless integration between physical and virtual networks.
```mermaid
flowchart TD
ClusterGroup & ClusterType --> Cluster
VirtualMachineType --> VirtualMachine
Device --> VirtualMachine
Cluster --> VirtualMachine
Platform --> VirtualMachine
VirtualMachine --> VMInterface
click Cluster "../../models/virtualization/cluster/"
click ClusterGroup "../../models/virtualization/clustergroup/"
click ClusterType "../../models/virtualization/clustertype/"
click VirtualMachineType "../../models/virtualization/virtualmachinetype/"
click Device "../../models/dcim/device/"
click Platform "../../models/dcim/platform/"
click VirtualMachine "../../models/virtualization/virtualmachine/"
click VMInterface "../../models/virtualization/vminterface/"
click Cluster "../../models/virtualization/cluster/"
click ClusterGroup "../../models/virtualization/clustergroup/"
click ClusterType "../../models/virtualization/clustertype/"
click Platform "../../models/dcim/platform/"
click VirtualMachine "../../models/virtualization/virtualmachine/"
click VMInterface "../../models/virtualization/vminterface/"
```
## Clusters
A cluster is one or more physical host devices on which virtual machines can run.
Each cluster must have a type and operational status, and may be assigned to a group. (Both types and groups are user-defined.) Each cluster may designate one or more devices as hosts, however this is optional.
## Virtual Machine Types
A virtual machine type provides reusable classification for virtual machines and can define create-time defaults for platform, vCPUs, and memory. This is useful when multiple virtual machines share a common sizing or profile while still allowing per-instance overrides after creation.
A cluster is one or more physical host devices on which virtual machines can run. Each cluster must have a type and operational status, and may be assigned to a group. (Both types and groups are user-defined.) Each cluster may designate one or more devices as hosts, however this is optional.
## Virtual Machines
A virtual machine is a virtualized compute instance. These behave in NetBox very similarly to device objects, but without any physical attributes.
For example, a VM may have interfaces assigned to it with IP addresses and VLANs, however its interfaces cannot be connected via cables (because they are virtual). Each VM may define its compute, memory, and storage resources as well. A VM can optionally be assigned a [virtual machine type](../models/virtualization/virtualmachinetype.md) to classify it and provide default values for selected attributes at creation time.
A VM can be placed in one of three ways:
- Assigned to a site alone for logical grouping.
- Assigned to a cluster and optionally pinned to a specific host device within that cluster.
- Assigned directly to a standalone device that does not belong to any cluster.
A virtual machine is a virtualized compute instance. These behave in NetBox very similarly to device objects, but without any physical attributes. For example, a VM may have interfaces assigned to it with IP addresses and VLANs, however its interfaces cannot be connected via cables (because they are virtual). Each VM may also define its compute, memory, and storage resources as well.

View File

@@ -341,7 +341,7 @@ When retrieving devices and virtual machines via the REST API, each will include
## Pagination
API responses which contain a list of many objects will be paginated for efficiency. NetBox employs offset-based pagination by default, which forms a page by skipping the number of objects indicated by the `offset` URL parameter. The root JSON object returned by a list endpoint contains the following attributes:
API responses which contain a list of many objects will be paginated for efficiency. The root JSON object returned by a list endpoint contains the following attributes:
* `count`: The total number of all objects matching the query
* `next`: A hyperlink to the next page of results (if applicable)
@@ -398,49 +398,6 @@ The maximum number of objects that can be returned is limited by the [`MAX_PAGE_
!!! warning
Disabling the page size limit introduces a potential for very resource-intensive requests, since one API request can effectively retrieve an entire table from the database.
### Cursor-Based Pagination
For large datasets, offset-based pagination can become inefficient because the database must scan all rows up to the offset. As an alternative, cursor-based pagination uses the `start` query parameter to filter results by primary key (PK), enabling efficient keyset pagination.
To use cursor-based pagination, pass `start` (the minimum PK value) and `limit` (the page size):
```
http://netbox/api/dcim/devices/?start=0&limit=100
```
This returns objects with an `id` greater than or equal to zero, ordered by PK, limited to 100 results. Below is an example showing an arbitrary `start` value.
```json
{
"count": null,
"next": "http://netbox/api/dcim/devices/?start=356&limit=100",
"previous": null,
"results": [
{
"id": 109,
"name": "dist-router07",
...
},
...
{
"id": 356,
"name": "acc-switch492",
...
}
]
}
```
To iterate through all results, use the `id` of the last object in each response plus one as the `start` value for the next request. Continue until `next` is null.
!!! info
Some important differences from offset-based pagination:
* `start` and `offset` are **mutually exclusive**; specifying both will result in a 400 error.
* Results are always ordered by primary key when using `start`. This is required to ensure deterministic behavior.
* `count` is always `null` in cursor mode, as counting all matching rows would partially negate its performance benefit.
* `previous` is always `null`: cursor-based pagination supports only forward navigation.
## Interacting with Objects
### Retrieving Multiple Objects

View File

@@ -26,20 +26,10 @@ The following data is available as context for Jinja2 templates:
* `event` - The type of event which triggered the webhook: `created`, `updated`, or `deleted`.
* `timestamp` - The time at which the event occurred (in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format).
* `object_type` - The NetBox model which triggered the change in the form `app_label.model_name`.
* `request` - Data about the triggering request (if available).
* `request.id` - The UUID associated with the request
* `request.method` - The HTTP method (e.g. `GET` or `POST`)
* `request.path` - The URL path (ex: `/dcim/sites/123/edit/`)
* `request.user` - The name of the authenticated user who made the request (if available)
* `username` - The name of the user account associated with the change.
* `request_id` - The unique request ID. This may be used to correlate multiple changes associated with a single request.
* `data` - A detailed representation of the object in its current state. This is typically equivalent to the model's representation in NetBox's REST API.
* `snapshots` - Minimal "snapshots" of the object state both before and after the change was made; provided as a dictionary with keys named `prechange` and `postchange`. These are not as extensive as the fully serialized representation, but contain enough information to convey what has changed.
* ⚠️ `request_id` - The unique request ID. This may be used to correlate multiple changes associated with a single request.
* ⚠️ `username` - The name of the user account associated with the change.
!!! warning "Deprecation of legacy keys"
The `request_id` and `username` keys in the webhook payload above are deprecated and should no longer be used. Support for them will be removed in NetBox v4.7.0.
Use `request.user` and `request.id` from the `request` object included in the callback context instead.
### Default Request Body
@@ -66,12 +56,6 @@ If no body template is specified, the request body will be populated with a JSON
"region": null,
...
},
"request": {
"id": "17af32f0-852a-46ca-a7d4-33ecd0c13de6",
"method": "POST",
"path": "/dcim/sites/add/",
"user": "jstretch"
},
"snapshots": {
"prechange": null,
"postchange": {

View File

@@ -1,15 +0,0 @@
# Cable Bundles
A cable bundle is a logical grouping of individual [cables](./cable.md). Bundles can be used to organize cables that share a common purpose, route, or physical grouping (such as a conduit or harness).
Assigning cables to a bundle is optional and does not affect cable tracing or connectivity. Bundles persist independently of their member cables: deleting a cable clears its bundle assignment but does not delete the bundle itself.
## Fields
### Name
A unique name for the cable bundle.
### Description
A brief description of the bundle's purpose or contents.

View File

@@ -23,8 +23,3 @@ The device bay's name. Must be unique to the parent device.
### Label
An alternative physical label identifying the device bay.
### Enabled
Whether this device bay is enabled. Disabled device bays are not available for installation.

View File

@@ -7,18 +7,6 @@ Device types are instantiated as devices installed within sites and/or equipment
!!! note
This parent/child relationship is **not** suitable for modeling chassis-based devices, wherein child members share a common control plane. Instead, line cards and similarly non-autonomous hardware should be modeled as modules or inventory items within a device.
## Automatic Component Renaming
When adding component templates to a device type, the string `{vc_position}` can be used in component template names to reference the
`vc_position` field of the device being provisioned, when that device is a member of a Virtual Chassis.
For example, an interface template named `Gi{vc_position}/0/0` installed on a Virtual Chassis
member with position `2` will be rendered as `Gi2/0/0`.
If the device is not a member of a Virtual Chassis, `{vc_position}` defaults to `0`. A custom
fallback value can be specified using the syntax `{vc_position:X}`, where `X` is the desired default.
For example, `{vc_position:1}` will render as `1` when no Virtual Chassis position is set.
## Fields
### Manufacturer

View File

@@ -1,6 +1,6 @@
# Module Bays
Module bays represent a space or slot within a device in which a field-replaceable [module](./module.md) may be installed. A common example is that of a chassis-based switch such as the Cisco Nexus 9000 or Juniper EX9200. Modules, in turn, hold additional components that become available to the parent device.
Module bays represent a space or slot within a device in which a field-replaceable [module](./module.md) may be installed. A common example is that of a chassis-based switch such as the Cisco Nexus 9000 or Juniper EX9200. Modules in turn hold additional components that become available to the parent device.
!!! note
If you need to model child devices rather than modules, use a [device bay](./devicebay.md) instead.
@@ -29,8 +29,3 @@ An alternative physical label identifying the module bay.
### Position
The numeric position in which this module bay is situated. For example, this would be the number assigned to a slot within a chassis-based switch.
### Enabled
Whether this module bay is enabled. Disabled module bays are not available for installation.

View File

@@ -20,38 +20,8 @@ When adding component templates to a module type, the string `{module}` can be u
For example, you can create a module type with interface templates named `Gi{module}/0/[1-48]`. When a new module of this type is "installed" to a module bay with a position of "3", NetBox will automatically name these interfaces `Gi3/0/[1-48]`.
Similarly, the string `{vc_position}` can be used in component template names to reference the
`vc_position` field of the device being provisioned, when that device is a member of a Virtual Chassis.
For example, an interface template named `Gi{vc_position}/{module}/0` installed on a Virtual Chassis
member with position `2` and module bay position `3` will be rendered as `Gi2/3/0`.
If the device is not a member of a Virtual Chassis, `{vc_position}` defaults to `0`. A custom
fallback value can be specified using the syntax `{vc_position:X}`, where `X` is the desired default.
For example, `{vc_position:1}` will render as `1` when no Virtual Chassis position is set.
Automatic renaming is supported for all modular component types (those listed above).
### Position Inheritance for Nested Modules
When using nested module bays (modules installed inside other modules), the `{module}` placeholder
can also be used in the **position** field of module bay templates to inherit the parent bay's
position. This allows a single module type to produce correctly named components at any nesting
depth, with a user-controlled separator.
For example, a line card module type might define sub-bay positions as `{module}/1`, `{module}/2`,
etc. When the line card is installed in a device bay with position `3`, these sub-bay positions
resolve to `3/1`, `3/2`, etc. An SFP module type with interface template `SFP {module}` installed
in sub-bay `3/2` then produces interface `SFP 3/2`.
The separator between levels is defined by the user in the position field template itself. Using
`{module}-1` produces positions like `3-1`, while `{module}.1` produces `3.1`. This provides
full flexibility without requiring a global separator configuration.
!!! note
If the position field does not contain `{module}`, no inheritance occurs and behavior is
unchanged from previous versions.
## Fields
### Manufacturer

View File

@@ -1,6 +1,6 @@
# Racks
The rack model represents a physical two- or four-post equipment rack in which [devices](./device.md) can be installed. Each rack must be assigned to a [site](./site.md), and may optionally be assigned to a [location](./location.md) within that site. Racks can also be organized by user-defined functional roles or by [rack groups](./rackgroup.md). The name and facility ID of each rack within a location must be unique.
The rack model represents a physical two- or four-post equipment rack in which [devices](./device.md) can be installed. Each rack must be assigned to a [site](./site.md), and may optionally be assigned to a [location](./location.md) within that site. Racks can also be organized by user-defined functional roles. The name and facility ID of each rack within a location must be unique.
Rack height is measured in *rack units* (U); racks are commonly between 42U and 48U tall, but NetBox allows you to define racks of arbitrary height. A toggle is provided to indicate whether rack units are in ascending (from the ground up) or descending order.
@@ -16,10 +16,6 @@ The [site](./site.md) to which the rack is assigned.
The [location](./location.md) within a site where the rack has been installed (optional).
### Rack Group
The [group](./rackgroup.md) used to organize racks by physical placement (optional).
### Name
The rack's name or identifier. Must be unique to the rack's location, if assigned.

View File

@@ -1,15 +0,0 @@
# Rack Groups
Racks can optionally be assigned to rack groups to reflect their physical placement. Rack groups provide a secondary means of categorization alongside [locations](./location.md), which is particularly useful for datacenter operators who need to group racks by row, aisle, or similar physical arrangement while keeping them assigned to the same location, such as a cage or room. Rack groups are flat and do not form a hierarchy.
Rack groups can also be used to scope [VLAN groups](../ipam/vlangroup.md), which can help model L2 domains spanning rows or pairs of racks.
## Fields
### Name
A unique human-friendly name.
### Slug
A unique URL-friendly identifier. (This value can be used for filtering.)

View File

@@ -12,10 +12,6 @@ The [rack](./rack.md) being reserved.
The rack unit or units being reserved. Multiple units can be expressed using commas and/or hyphens. For example, `1,3,5-7` specifies units 1, 3, 5, 6, and 7.
### Total U's
A calculated (read-only) field that reflects the total number of units in the reservation. Can be filtered upon using `unit_count_min` and `unit_count_max` parameters in the UI or API.
### Status
The current status of the reservation. (This is for documentation only: The status of a reservation has no impact on the installation of devices within a reserved rack unit.)

View File

@@ -118,7 +118,3 @@ For numeric custom fields only. The maximum valid value (optional).
### Validation Regex
For string-based custom fields only. A regular expression used to validate the field's value (optional).
### Validation Schema
For JSON custom fields, users have the option of defining a [validation schema](https://json-schema.org). Any value applied to this custom field on a model will be validated against the provided schema, if any.

View File

@@ -81,13 +81,10 @@ The following context variables are available to the text and link templates.
| Variable | Description |
|---------------|------------------------------------------------------|
| `event` | The event type (`create`, `update`, or `delete`) |
| `event` | The event type (`created`, `updated`, or `deleted`) |
| `timestamp` | The time at which the event occurred |
| `object_type` | The type of object impacted (`app_label.model_name`) |
| `username` | The name of the user associated with the change |
| `request_id` | The unique request ID |
| `data` | A complete serialized representation of the object |
| `snapshots` | Pre- and post-change snapshots of the object |
!!! warning "Deprecation of legacy fields"
The `request_id` and `username` fields in the webhook payload above are deprecated and should no longer be used. Support for them will be removed in NetBox v4.7.0. Use `request.user` and `request.id` from the `request` object included in the callback context instead. (Note that `request` is populated in the context only when the webhook is associated with a triggering request.)

View File

@@ -14,10 +14,6 @@ The 16- or 32-bit AS number.
The [Regional Internet Registry](./rir.md) or similar authority responsible for the allocation of this particular ASN.
### Role
The user-defined functional [role](./role.md) assigned to this ASN.
### Sites
The [site(s)](../dcim/site.md) to which this ASN is assigned.

View File

@@ -18,10 +18,6 @@ A unique URL-friendly identifier. (This value can be used for filtering.)
The set of VLAN IDs which are encompassed by the group. By default, this will be the entire range of valid IEEE 802.1Q VLAN IDs (1 to 4094, inclusive). VLANs created within a group must have a VID that falls within one of these ranges. Ranges may not overlap.
### Total VLAN IDs
A read-only integer indicating the total count of VLAN IDs available within the group, calculated from the configured VLAN ID Ranges. For example, a group with ranges `100-199` and `300-399` would have a total of 200 VLAN IDs. This value is automatically computed and updated whenever the VLAN ID ranges are modified.
### Scope
The domain covered by a VLAN group, defined as one of the supported object types. This conveys the context in which a VLAN group applies.

View File

@@ -1,27 +1,18 @@
# Virtual Machines
A virtual machine (VM) represents a virtual compute instance hosted within a cluster or directly on a device. Each VM must be assigned to at least one of: a [site](../dcim/site.md), a [cluster](./cluster.md), or a [device](../dcim/device.md).
A virtual machine (VM) represents a virtual compute instance hosted within a [cluster](./cluster.md). Each VM must be assigned to a [site](../dcim/site.md) and/or cluster, and may optionally be assigned to a particular host [device](../dcim/device.md) within a cluster.
Virtual machines may have virtual [interfaces](./vminterface.md) assigned to them, but do not support any physical component. When a VM has one or more interfaces with IP addresses assigned, a primary IP for the VM can be designated, for both IPv4 and IPv6.
Virtual machines may have virtual [interfaces](./vminterface.md) assigned to them, but do not support any physical component. When a VM has one or more interfaces with IP addresses assigned, a primary IP for the device can be designated, for both IPv4 and IPv6.
## Fields
### Name
The virtual machine's configured name. Must be unique within its scoping context:
- If assigned to a **cluster**: unique within the cluster and tenant.
- If assigned to a **device** (no cluster): unique within the device and tenant.
### Type
The [virtual machine type](./virtualmachinetype.md) assigned to the VM. A type classifies a virtual machine and can provide default values for platform, vCPUs, and memory when the VM is created.
Changes made to a virtual machine type do **not** apply retroactively to existing virtual machines.
The virtual machine's configured name. Must be unique to the assigned cluster and tenant.
### Role
The functional role assigned to the VM.
The functional [role](../dcim/devicerole.md) assigned to the VM.
### Status
@@ -30,28 +21,24 @@ The VM's operational status.
!!! tip
Additional statuses may be defined by setting `VirtualMachine.status` under the [`FIELD_CHOICES`](../../configuration/data-validation.md#field_choices) configuration parameter.
### Start on Boot
### Start on boot
The start on boot setting from the hypervisor.
!!! tip
Additional statuses may be defined by setting `VirtualMachine.start_on_boot` under the [`FIELD_CHOICES`](../../configuration/data-validation.md#field_choices) configuration parameter.
### Site / Cluster / Device
### Site & Cluster
The location or host for this VM. At least one must be specified:
The [site](../dcim/site.md) and/or [cluster](./cluster.md) to which the VM is assigned.
- **Site only**: The VM exists at a site but is not assigned to a specific cluster or device.
- **Cluster only**: The VM belongs to a virtualization cluster. The site is automatically inferred from the cluster's scope.
- **Device only**: The VM runs directly on a physical host device without a cluster (e.g. containers). The site is automatically inferred from the device's site.
- **Cluster + Device**: The VM belongs to a cluster and is pinned to a specific host device within that cluster. The device must be a registered host of the assigned cluster.
### Device
!!! info "New in NetBox v4.6"
Virtual machines can now be assigned directly to a device without requiring a cluster. This is particularly useful for modeling VMs running on standalone hosts outside of a cluster.
The physical host [device](../dcim/device.md) within the assigned site/cluster on which this VM resides.
### Platform
A VM may be associated with a particular [platform](../dcim/platform.md) to indicate its operating system. If a virtual machine type defines a default platform, it will be applied when the VM is created unless an explicit platform is specified.
A VM may be associated with a particular [platform](../dcim/platform.md) to indicate its operating system.
### Primary IPv4 & IPv6 Addresses
@@ -62,11 +49,11 @@ Each VM may designate one primary IPv4 address and/or one primary IPv6 address f
### vCPUs
The number of virtual CPUs provisioned. A VM may be allocated a partial vCPU count (e.g. 1.5 vCPU). If a virtual machine type defines a default vCPU allocation, it will be applied when the VM is created unless an explicit value is specified.
The number of virtual CPUs provisioned. A VM may be allocated a partial vCPU count (e.g. 1.5 vCPU).
### Memory
The amount of running memory provisioned, in megabytes. If a virtual machine type defines a default memory allocation, it will be applied when the VM is created unless an explicit value is specified.
The amount of running memory provisioned, in megabytes.
### Disk
@@ -77,7 +64,4 @@ The amount of disk storage provisioned, in megabytes.
### Serial Number
Optional serial number assigned to this virtual machine.
!!! info
Unlike devices, uniqueness is not enforced for virtual machine serial numbers.
Optional serial number assigned to this virtual machine. Unlike devices, uniqueness is not enforced for virtual machine serial numbers.

View File

@@ -1,27 +0,0 @@
# Virtual Machine Types
A virtual machine type defines a reusable classification and default configuration for [virtual machines](./virtualmachine.md).
A type can optionally provide default values for a VM's [platform](../dcim/platform.md), vCPU allocation, and memory allocation. When a virtual machine is created with an assigned type, any unset values among these fields will inherit their defaults from the type. Changes made to a virtual machine type do **not** apply retroactively to existing virtual machines.
## Fields
### Name
A unique human-friendly name.
### Slug
A unique URL-friendly identifier. (This value can be used for filtering.)
### Default Platform
If defined, virtual machines instantiated with this type will automatically inherit the selected platform when no explicit platform is provided.
### Default vCPUs
The default number of vCPUs to assign when creating a virtual machine from this type.
### Default Memory
The default amount of memory, in megabytes, to assign when creating a virtual machine from this type.

View File

@@ -1,9 +1,12 @@
# UI Components
!!! note "New in NetBox v4.6"
All UI components described here were introduced in NetBox v4.6. Be sure to set the minimum NetBox version to 4.6.0 for your plugin before incorporating any of these resources.
!!! note "New in NetBox v4.5"
All UI components described here were introduced in NetBox v4.5. Be sure to set the minimum NetBox version to 4.5.0 for your plugin before incorporating any of these resources.
To simplify the process of designing your plugin's user interface, and to encourage a consistent look and feel throughout the entire application, NetBox provides a set of components that enable programmatic UI design. These make it possible to declare complex page layouts with little or no custom HTML.
!!! danger "Beta Feature"
UI components are considered a beta feature, and are still under active development. Please be aware that the API for resources on this page is subject to change in future releases.
To simply the process of designing your plugin's user interface, and to encourage a consistent look and feel throughout the entire application, NetBox provides a set of components that enable programmatic UI design. These make it possible to declare complex page layouts with little or no custom HTML.
## Page Layout
@@ -72,12 +75,9 @@ class RecentChangesPanel(Panel):
**super().get_context(context),
'changes': get_changes()[:10],
}
def should_render(self, context):
return len(context['changes']) > 0
```
NetBox also includes a set of panels suited for specific uses, such as displaying object details or embedding a table of related objects. These are listed below.
NetBox also includes a set of panels suite for specific uses, such as display object details or embedding a table of related objects. These are listed below.
::: netbox.ui.panels.Panel
@@ -85,6 +85,26 @@ NetBox also includes a set of panels suited for specific uses, such as displayin
::: netbox.ui.panels.ObjectAttributesPanel
#### Object Attributes
The following classes are available to represent object attributes within an ObjectAttributesPanel. Additionally, plugins can subclass `netbox.ui.attrs.ObjectAttribute` to create custom classes.
| Class | Description |
|--------------------------------------|--------------------------------------------------|
| `netbox.ui.attrs.AddressAttr` | A physical or mailing address. |
| `netbox.ui.attrs.BooleanAttr` | A boolean value |
| `netbox.ui.attrs.ColorAttr` | A color expressed in RGB |
| `netbox.ui.attrs.ChoiceAttr` | A selection from a set of choices |
| `netbox.ui.attrs.GPSCoordinatesAttr` | GPS coordinates (latitude and longitude) |
| `netbox.ui.attrs.ImageAttr` | An attached image (displays the image) |
| `netbox.ui.attrs.NestedObjectAttr` | A related nested object |
| `netbox.ui.attrs.NumericAttr` | An integer or float value |
| `netbox.ui.attrs.RelatedObjectAttr` | A related object |
| `netbox.ui.attrs.TemplatedAttr` | Renders an attribute using a custom template |
| `netbox.ui.attrs.TextAttr` | A string (text) value |
| `netbox.ui.attrs.TimezoneAttr` | A timezone with annotated offset |
| `netbox.ui.attrs.UtilizationAttr` | A numeric value expressed as a utilization graph |
::: netbox.ui.panels.OrganizationalObjectPanel
::: netbox.ui.panels.NestedGroupObjectPanel
@@ -99,13 +119,9 @@ NetBox also includes a set of panels suited for specific uses, such as displayin
::: netbox.ui.panels.TemplatePanel
::: netbox.ui.panels.TextCodePanel
::: netbox.ui.panels.ContextTablePanel
::: netbox.ui.panels.PluginContentPanel
### Panel Actions
## Panel Actions
Each panel may have actions associated with it. These render as links or buttons within the panel header, opposite the panel's title. For example, a common use case is to include an "Add" action on a panel which displays a list of objects. Below is an example of this.
@@ -130,60 +146,3 @@ panels.ObjectsTablePanel(
::: netbox.ui.actions.AddObject
::: netbox.ui.actions.CopyContent
## Object Attributes
The following classes are available to represent object attributes within an ObjectAttributesPanel. Additionally, plugins can subclass `netbox.ui.attrs.ObjectAttribute` to create custom classes.
| Class | Description |
|------------------------------------------|--------------------------------------------------|
| `netbox.ui.attrs.AddressAttr` | A physical or mailing address. |
| `netbox.ui.attrs.BooleanAttr` | A boolean value |
| `netbox.ui.attrs.ChoiceAttr` | A selection from a set of choices |
| `netbox.ui.attrs.ColorAttr` | A color expressed in RGB |
| `netbox.ui.attrs.DateTimeAttr` | A date or datetime value |
| `netbox.ui.attrs.GenericForeignKeyAttr` | A related object via a generic foreign key |
| `netbox.ui.attrs.GPSCoordinatesAttr` | GPS coordinates (latitude and longitude) |
| `netbox.ui.attrs.ImageAttr` | An attached image (displays the image) |
| `netbox.ui.attrs.NestedObjectAttr` | A related nested object (includes ancestors) |
| `netbox.ui.attrs.NumericAttr` | An integer or float value |
| `netbox.ui.attrs.RelatedObjectAttr` | A related object |
| `netbox.ui.attrs.RelatedObjectListAttr` | A list of related objects |
| `netbox.ui.attrs.TemplatedAttr` | Renders an attribute using a custom template |
| `netbox.ui.attrs.TextAttr` | A string (text) value |
| `netbox.ui.attrs.TimezoneAttr` | A timezone with annotated offset |
| `netbox.ui.attrs.UtilizationAttr` | A numeric value expressed as a utilization graph |
::: netbox.ui.attrs.ObjectAttribute
::: netbox.ui.attrs.AddressAttr
::: netbox.ui.attrs.BooleanAttr
::: netbox.ui.attrs.ChoiceAttr
::: netbox.ui.attrs.ColorAttr
::: netbox.ui.attrs.DateTimeAttr
::: netbox.ui.attrs.GenericForeignKeyAttr
::: netbox.ui.attrs.GPSCoordinatesAttr
::: netbox.ui.attrs.ImageAttr
::: netbox.ui.attrs.NestedObjectAttr
::: netbox.ui.attrs.NumericAttr
::: netbox.ui.attrs.RelatedObjectAttr
::: netbox.ui.attrs.RelatedObjectListAttr
::: netbox.ui.attrs.TemplatedAttr
::: netbox.ui.attrs.TextAttr
::: netbox.ui.attrs.TimezoneAttr
::: netbox.ui.attrs.UtilizationAttr

View File

@@ -36,7 +36,6 @@ The resulting webhook payload will look like the following:
"url": "/api/dcim/sites/2/",
...
},
"request": {...},
"snapshots": {...},
"context": {
"foo": 123
@@ -44,11 +43,6 @@ The resulting webhook payload will look like the following:
}
```
!!! warning "Deprecation of legacy keys"
The `request_id` and `username` keys in the webhook payload above are deprecated and should no longer be used. Support for them will be removed in NetBox v4.7.0.
Use `request.user` and `request.id` from the `request` object included in the callback context instead.
!!! note "Consider namespacing webhook data"
The data returned from all webhook callbacks will be compiled into a single `context` dictionary. Any existing keys within this dictionary will be overwritten by subsequent callbacks which include those keys. To avoid collisions with webhook data provided by other plugins, consider namespacing your plugin's data within a nested dictionary as such:

View File

@@ -1,5 +1,31 @@
# NetBox v4.5
## v4.5.7 (2026-04-03)
### Enhancements
* [#21095](https://github.com/netbox-community/netbox/issues/21095) - Adopt IEC unit labels (e.g. GiB) for virtual machine resources
* [#21696](https://github.com/netbox-community/netbox/issues/21696) - Add support for django-rq 4.0 and introduce `RQ` configuration parameter
* [#21701](https://github.com/netbox-community/netbox/issues/21701) - Support uploading custom scripts via the REST API (`/api/extras/scripts/upload/`)
* [#21760](https://github.com/netbox-community/netbox/issues/21760) - Add a 1C2P:2C1P breakout cable profile
### Performance Improvements
* [#21655](https://github.com/netbox-community/netbox/issues/21655) - Optimize queries for object and multi-object type custom fields
### Bug Fixes
* [#20474](https://github.com/netbox-community/netbox/issues/20474) - Fix installation of modules with placeholder values in component names
* [#21498](https://github.com/netbox-community/netbox/issues/21498) - Fix server error triggered by event rules referencing deleted objects
* [#21533](https://github.com/netbox-community/netbox/issues/21533) - Ensure read-only fields are included in REST API responses upon object creation
* [#21535](https://github.com/netbox-community/netbox/issues/21535) - Fix filtering of object-type custom fields when "is empty" is selected
* [#21784](https://github.com/netbox-community/netbox/issues/21784) - Fix `AttributeError` exception when sorting a table as an anonymous user
* [#21808](https://github.com/netbox-community/netbox/issues/21808) - Fix `RelatedObjectDoesNotExist` exception when viewing an interface with a virtual circuit termination
* [#21810](https://github.com/netbox-community/netbox/issues/21810) - Fix `AttributeError` exception when viewing virtual chassis member
* [#21825](https://github.com/netbox-community/netbox/issues/21825) - Fix sorting by broken columns in several object lists
---
## v4.5.6 (2026-03-31)
### Enhancements

View File

@@ -1,4 +1,3 @@
# Note: NetBox has migrated from MkDocs to Zensical
site_name: NetBox Documentation
site_dir: netbox/project-static/docs
site_url: https://docs.netbox.dev/
@@ -190,7 +189,6 @@ nav:
- Job: 'models/core/job.md'
- DCIM:
- Cable: 'models/dcim/cable.md'
- CableBundle: 'models/dcim/cablebundle.md'
- ConsolePort: 'models/dcim/consoleport.md'
- ConsolePortTemplate: 'models/dcim/consoleporttemplate.md'
- ConsoleServerPort: 'models/dcim/consoleserverport.md'
@@ -223,7 +221,6 @@ nav:
- PowerPort: 'models/dcim/powerport.md'
- PowerPortTemplate: 'models/dcim/powerporttemplate.md'
- Rack: 'models/dcim/rack.md'
- RackGroup: 'models/dcim/rackgroup.md'
- RackReservation: 'models/dcim/rackreservation.md'
- RackRole: 'models/dcim/rackrole.md'
- RackType: 'models/dcim/racktype.md'
@@ -288,7 +285,6 @@ nav:
- VMInterface: 'models/virtualization/vminterface.md'
- VirtualDisk: 'models/virtualization/virtualdisk.md'
- VirtualMachine: 'models/virtualization/virtualmachine.md'
- VirtualMachineType: 'models/virtualization/virtualmachinetype.md'
- VPN:
- IKEPolicy: 'models/vpn/ikepolicy.md'
- IKEProposal: 'models/vpn/ikeproposal.md'

View File

@@ -1,35 +0,0 @@
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('circuits', '0056_gfk_indexes'),
('contenttypes', '0002_remove_content_type_name'),
('dcim', '0230_interface_rf_channel_frequency_precision'),
('extras', '0136_customfield_validation_schema'),
('tenancy', '0023_add_mptt_tree_indexes'),
('users', '0015_owner'),
]
operations = [
migrations.AddIndex(
model_name='circuit',
index=models.Index(fields=['provider', 'provider_account', 'cid'], name='circuits_ci_provide_a0c42c_idx'),
),
migrations.AddIndex(
model_name='circuitgroupassignment',
index=models.Index(
fields=['group', 'member_type', 'member_id', 'priority', 'id'], name='circuits_ci_group_i_2f8327_idx'
),
),
migrations.AddIndex(
model_name='virtualcircuit',
index=models.Index(
fields=['provider_network', 'provider_account', 'cid'], name='circuits_vi_provide_989efa_idx'
),
),
migrations.AddIndex(
model_name='virtualcircuittermination',
index=models.Index(fields=['virtual_circuit', 'role', 'id'], name='circuits_vi_virtual_4b5c0c_idx'),
),
]

View File

@@ -144,9 +144,6 @@ class Circuit(ContactsMixin, ImageAttachmentsMixin, DistanceMixin, PrimaryModel)
name='%(app_label)s_%(class)s_unique_provideraccount_cid'
),
)
indexes = (
models.Index(fields=('provider', 'provider_account', 'cid')), # Default ordering
)
verbose_name = _('circuit')
verbose_name_plural = _('circuits')
@@ -224,9 +221,6 @@ class CircuitGroupAssignment(CustomFieldsMixin, ExportTemplatesMixin, TagsMixin,
name='%(app_label)s_%(class)s_unique_member_group'
),
)
indexes = (
models.Index(fields=('group', 'member_type', 'member_id', 'priority', 'id')), # Default ordering
)
verbose_name = _('Circuit group assignment')
verbose_name_plural = _('Circuit group assignments')

View File

@@ -97,9 +97,6 @@ class VirtualCircuit(ContactsMixin, PrimaryModel):
name='%(app_label)s_%(class)s_unique_provideraccount_cid'
),
)
indexes = (
models.Index(fields=('provider_network', 'provider_account', 'cid')), # Default ordering
)
verbose_name = _('virtual circuit')
verbose_name_plural = _('virtual circuits')
@@ -153,9 +150,6 @@ class VirtualCircuitTermination(
class Meta:
ordering = ['virtual_circuit', 'role', 'pk']
indexes = (
models.Index(fields=('virtual_circuit', 'role', 'id')), # Default ordering
)
verbose_name = _('virtual circuit termination')
verbose_name_plural = _('virtual circuit terminations')

View File

@@ -95,6 +95,7 @@ class VirtualCircuitTerminationTable(NetBoxTable):
verbose_name=_('Provider network')
)
provider_account = tables.Column(
accessor=tables.A('virtual_circuit__provider_account'),
linkify=True,
verbose_name=_('Account')
)
@@ -112,7 +113,7 @@ class VirtualCircuitTerminationTable(NetBoxTable):
class Meta(NetBoxTable.Meta):
model = VirtualCircuitTermination
fields = (
'pk', 'id', 'virtual_circuit', 'provider', 'provider_network', 'provider_account', 'role', 'interfaces',
'pk', 'id', 'virtual_circuit', 'provider', 'provider_network', 'provider_account', 'role', 'interface',
'description', 'created', 'last_updated', 'actions',
)
default_columns = (

View File

@@ -1,48 +1,46 @@
from django.test import RequestFactory, TestCase, tag
from circuits.models import CircuitGroupAssignment, CircuitTermination
from circuits.tables import CircuitGroupAssignmentTable, CircuitTerminationTable
from circuits.tables import *
from utilities.testing import TableTestCases
@tag('regression')
class CircuitTerminationTableTest(TestCase):
def test_every_orderable_field_does_not_throw_exception(self):
terminations = CircuitTermination.objects.all()
disallowed = {
'actions',
}
orderable_columns = [
column.name
for column in CircuitTerminationTable(terminations).columns
if column.orderable and column.name not in disallowed
]
fake_request = RequestFactory().get('/')
for col in orderable_columns:
for direction in ('-', ''):
table = CircuitTerminationTable(terminations)
table.order_by = f'{direction}{col}'
table.as_html(fake_request)
class CircuitTypeTableTest(TableTestCases.StandardTableTestCase):
table = CircuitTypeTable
@tag('regression')
class CircuitGroupAssignmentTableTest(TestCase):
def test_every_orderable_field_does_not_throw_exception(self):
assignment = CircuitGroupAssignment.objects.all()
disallowed = {
'actions',
}
class CircuitTableTest(TableTestCases.StandardTableTestCase):
table = CircuitTable
orderable_columns = [
column.name
for column in CircuitGroupAssignmentTable(assignment).columns
if column.orderable and column.name not in disallowed
]
fake_request = RequestFactory().get('/')
for col in orderable_columns:
for direction in ('-', ''):
table = CircuitGroupAssignmentTable(assignment)
table.order_by = f'{direction}{col}'
table.as_html(fake_request)
class CircuitTerminationTableTest(TableTestCases.StandardTableTestCase):
table = CircuitTerminationTable
class CircuitGroupTableTest(TableTestCases.StandardTableTestCase):
table = CircuitGroupTable
class CircuitGroupAssignmentTableTest(TableTestCases.StandardTableTestCase):
table = CircuitGroupAssignmentTable
class ProviderTableTest(TableTestCases.StandardTableTestCase):
table = ProviderTable
class ProviderAccountTableTest(TableTestCases.StandardTableTestCase):
table = ProviderAccountTable
class ProviderNetworkTableTest(TableTestCases.StandardTableTestCase):
table = ProviderNetworkTable
class VirtualCircuitTypeTableTest(TableTestCases.StandardTableTestCase):
table = VirtualCircuitTypeTable
class VirtualCircuitTableTest(TableTestCases.StandardTableTestCase):
table = VirtualCircuitTable
class VirtualCircuitTerminationTableTest(TableTestCases.StandardTableTestCase):
table = VirtualCircuitTerminationTable

View File

@@ -196,6 +196,20 @@ class CircuitTestCase(ViewTestCases.PrimaryObjectViewTestCase):
'comments': 'New comments',
}
def test_circuit_type_display_colored(self):
circuit_type = CircuitType.objects.first()
circuit_type.color = '12ab34'
circuit_type.save()
circuit = Circuit.objects.first()
self.add_permissions('circuits.view_circuit')
response = self.client.get(circuit.get_absolute_url())
self.assertHttpStatus(response, 200)
self.assertContains(response, circuit_type.name)
self.assertContains(response, 'background-color: #12ab34')
@override_settings(EXEMPT_VIEW_PERMISSIONS=['*'], EXEMPT_EXCLUDE_MODELS=[])
def test_bulk_import_objects_with_terminations(self):
site = Site.objects.first()

View File

@@ -13,9 +13,13 @@ class CircuitCircuitTerminationPanel(panels.ObjectPanel):
template_name = 'circuits/panels/circuit_circuit_termination.html'
title = _('Termination')
def __init__(self, side, accessor=None, **kwargs):
super().__init__(accessor=accessor, **kwargs)
self.side = side
def __init__(self, accessor=None, side=None, **kwargs):
super().__init__(**kwargs)
if accessor is not None:
self.accessor = accessor
if side is not None:
self.side = side
def get_context(self, context):
return {
@@ -54,26 +58,6 @@ class CircuitGroupAssignmentsPanel(panels.ObjectsTablePanel):
)
class CircuitTerminationPanel(panels.ObjectAttributesPanel):
title = _('Circuit Termination')
circuit = attrs.RelatedObjectAttr('circuit', linkify=True)
provider = attrs.RelatedObjectAttr('circuit.provider', linkify=True)
termination = attrs.GenericForeignKeyAttr('termination', linkify=True, label=_('Termination point'))
connection = attrs.TemplatedAttr(
'pk',
template_name='circuits/circuit_termination/attrs/connection.html',
label=_('Connection'),
)
speed = attrs.TemplatedAttr(
'port_speed',
template_name='circuits/circuit_termination/attrs/speed.html',
label=_('Speed'),
)
xconnect_id = attrs.TextAttr('xconnect_id', label=_('Cross-Connect'), style='font-monospace')
pp_info = attrs.TextAttr('pp_info', label=_('Patch Panel/Port'))
description = attrs.TextAttr('description')
class CircuitGroupPanel(panels.OrganizationalObjectPanel):
tenant = attrs.RelatedObjectAttr('tenant', linkify=True, grouped_by='group')
@@ -89,7 +73,7 @@ class CircuitPanel(panels.ObjectAttributesPanel):
provider = attrs.RelatedObjectAttr('provider', linkify=True)
provider_account = attrs.RelatedObjectAttr('provider_account', linkify=True)
cid = attrs.TextAttr('cid', label=_('Circuit ID'), style='font-monospace', copy_button=True)
type = attrs.RelatedObjectAttr('type', linkify=True)
type = attrs.RelatedObjectAttr('type', linkify=True, colored=True)
status = attrs.ChoiceAttr('status')
distance = attrs.NumericAttr('distance', unit_accessor='get_distance_unit_display')
tenant = attrs.RelatedObjectAttr('tenant', linkify=True, grouped_by='group')
@@ -132,7 +116,7 @@ class VirtualCircuitPanel(panels.ObjectAttributesPanel):
provider_network = attrs.RelatedObjectAttr('provider_network', linkify=True)
provider_account = attrs.RelatedObjectAttr('provider_account', linkify=True)
cid = attrs.TextAttr('cid', label=_('Circuit ID'), style='font-monospace', copy_button=True)
type = attrs.RelatedObjectAttr('type', linkify=True)
type = attrs.RelatedObjectAttr('type', linkify=True, colored=True)
status = attrs.ChoiceAttr('status')
tenant = attrs.RelatedObjectAttr('tenant', linkify=True, grouped_by='group')
description = attrs.TextAttr('description')

View File

@@ -8,6 +8,7 @@ from netbox.ui import actions, layout
from netbox.ui.panels import (
CommentsPanel,
ObjectsTablePanel,
Panel,
RelatedObjectsPanel,
)
from netbox.views import generic
@@ -52,7 +53,6 @@ class ProviderView(GetRelatedModelsMixin, generic.ObjectView):
ObjectsTablePanel(
model='circuits.ProviderAccount',
filters={'provider_id': lambda ctx: ctx['object'].pk},
exclude_columns=['provider'],
actions=[
actions.AddObject(
'circuits.ProviderAccount', url_params={'provider': lambda ctx: ctx['object'].pk}
@@ -62,7 +62,6 @@ class ProviderView(GetRelatedModelsMixin, generic.ObjectView):
ObjectsTablePanel(
model='circuits.Circuit',
filters={'provider_id': lambda ctx: ctx['object'].pk},
exclude_columns=['provider'],
actions=[
actions.AddObject('circuits.Circuit', url_params={'provider': lambda ctx: ctx['object'].pk}),
],
@@ -162,7 +161,6 @@ class ProviderAccountView(GetRelatedModelsMixin, generic.ObjectView):
ObjectsTablePanel(
model='circuits.Circuit',
filters={'provider_account_id': lambda ctx: ctx['object'].pk},
exclude_columns=['provider_account'],
actions=[
actions.AddObject(
'circuits.Circuit',
@@ -259,7 +257,6 @@ class ProviderNetworkView(GetRelatedModelsMixin, generic.ObjectView):
ObjectsTablePanel(
model='circuits.VirtualCircuit',
filters={'provider_network_id': lambda ctx: ctx['object'].pk},
exclude_columns=['provider_network'],
actions=[
actions.AddObject(
'circuits.VirtualCircuit', url_params={'provider_network': lambda ctx: ctx['object'].pk}
@@ -511,7 +508,10 @@ class CircuitTerminationView(generic.ObjectView):
queryset = CircuitTermination.objects.all()
layout = layout.SimpleLayout(
left_panels=[
panels.CircuitTerminationPanel(),
Panel(
template_name='circuits/panels/circuit_termination.html',
title=_('Circuit Termination'),
)
],
right_panels=[
CustomFieldsPanel(),
@@ -801,7 +801,6 @@ class VirtualCircuitView(generic.ObjectView):
model='circuits.VirtualCircuitTermination',
title=_('Terminations'),
filters={'virtual_circuit_id': lambda ctx: ctx['object'].pk},
exclude_columns=['virtual_circuit'],
actions=[
actions.AddObject(
'circuits.VirtualCircuitTermination',

View File

@@ -2,7 +2,7 @@ from django.http import Http404, HttpResponse
from django.shortcuts import get_object_or_404
from django.utils.translation import gettext_lazy as _
from django_rq.queues import get_redis_connection
from django_rq.settings import QUEUES_LIST
from django_rq.settings import get_queues_list
from django_rq.utils import get_statistics
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, extend_schema
@@ -195,7 +195,7 @@ class BackgroundWorkerViewSet(BaseRQViewSet):
return 'Background Workers'
def get_data(self):
config = QUEUES_LIST[0]
config = get_queues_list()[0]
return Worker.all(get_redis_connection(config['connection_config']))
@extend_schema(
@@ -205,7 +205,7 @@ class BackgroundWorkerViewSet(BaseRQViewSet):
)
def retrieve(self, request, name):
# all the RQ queues should use the same connection
config = QUEUES_LIST[0]
config = get_queues_list()[0]
workers = Worker.all(get_redis_connection(config['connection_config']))
worker = next((item for item in workers if item.name == name), None)
if not worker:
@@ -229,7 +229,7 @@ class BackgroundTaskViewSet(BaseRQViewSet):
return get_rq_jobs()
def get_task_from_id(self, task_id):
config = QUEUES_LIST[0]
config = get_queues_list()[0]
task = RQ_Job.fetch(task_id, connection=get_redis_connection(config['connection_config']))
if not task:
raise Http404

View File

@@ -165,10 +165,9 @@ class ConfigRevisionForm(forms.ModelForm, metaclass=ConfigFormMetaclass):
FieldSet('PAGINATE_COUNT', 'MAX_PAGE_SIZE', name=_('Pagination')),
FieldSet('CUSTOM_VALIDATORS', 'PROTECTION_RULES', name=_('Validation')),
FieldSet('DEFAULT_USER_PREFERENCES', name=_('User Preferences')),
FieldSet('CHANGELOG_RETENTION', 'CHANGELOG_RETAIN_CREATE_LAST_UPDATE', name=_('Change Log')),
FieldSet(
'MAINTENANCE_MODE', 'COPILOT_ENABLED', 'GRAPHQL_ENABLED', 'JOB_RETENTION', 'MAPS_URL',
name=_('Miscellaneous'),
'MAINTENANCE_MODE', 'COPILOT_ENABLED', 'GRAPHQL_ENABLED', 'CHANGELOG_RETENTION', 'JOB_RETENTION',
'MAPS_URL', name=_('Miscellaneous'),
),
FieldSet('comment', name=_('Config Revision'))
)

View File

@@ -5,7 +5,6 @@ from importlib import import_module
import requests
from django.conf import settings
from django.core.cache import cache
from django.db.models import Exists, OuterRef, Subquery
from django.utils import timezone
from packaging import version
@@ -15,7 +14,7 @@ from netbox.jobs import JobRunner, system_job
from netbox.search.backends import search_backend
from utilities.proxy import resolve_proxies
from .choices import DataSourceStatusChoices, JobIntervalChoices, ObjectChangeActionChoices
from .choices import DataSourceStatusChoices, JobIntervalChoices
from .models import DataSource
@@ -127,51 +126,19 @@ class SystemHousekeepingJob(JobRunner):
"""
Delete any ObjectChange records older than the configured changelog retention time (if any).
"""
self.logger.info('Pruning old changelog entries...')
self.logger.info("Pruning old changelog entries...")
config = Config()
if not config.CHANGELOG_RETENTION:
self.logger.info('No retention period specified; skipping.')
self.logger.info("No retention period specified; skipping.")
return
cutoff = timezone.now() - timedelta(days=config.CHANGELOG_RETENTION)
self.logger.debug(f'Changelog retention period: {config.CHANGELOG_RETENTION} days ({cutoff:%Y-%m-%d %H:%M:%S})')
self.logger.debug(
f"Changelog retention period: {config.CHANGELOG_RETENTION} days ({cutoff:%Y-%m-%d %H:%M:%S})"
)
expired_qs = ObjectChange.objects.filter(time__lt=cutoff)
# When enabled, retain each object's original create record and most recent update record while pruning expired
# changelog entries. This applies only to objects without a delete record.
if config.CHANGELOG_RETAIN_CREATE_LAST_UPDATE:
self.logger.debug('Retaining changelog create records and last update records (excluding deleted objects)')
deleted_exists = ObjectChange.objects.filter(
action=ObjectChangeActionChoices.ACTION_DELETE,
changed_object_type_id=OuterRef('changed_object_type_id'),
changed_object_id=OuterRef('changed_object_id'),
)
# Keep create records only where no delete exists for that object
create_pks_to_keep = (
ObjectChange.objects.filter(action=ObjectChangeActionChoices.ACTION_CREATE)
.annotate(has_delete=Exists(deleted_exists))
.filter(has_delete=False)
.values('pk')
)
# Keep the most recent update per object only where no delete exists for the object
latest_update_pks_to_keep = (
ObjectChange.objects.filter(action=ObjectChangeActionChoices.ACTION_UPDATE)
.annotate(has_delete=Exists(deleted_exists))
.filter(has_delete=False)
.order_by('changed_object_type_id', 'changed_object_id', '-time', '-pk')
.distinct('changed_object_type_id', 'changed_object_id')
.values('pk')
)
expired_qs = expired_qs.exclude(pk__in=Subquery(create_pks_to_keep))
expired_qs = expired_qs.exclude(pk__in=Subquery(latest_update_pks_to_keep))
count = expired_qs.delete()[0]
self.logger.info(f'Deleted {count} expired changelog records')
count = ObjectChange.objects.filter(time__lt=cutoff).delete()[0]
self.logger.info(f"Deleted {count} expired changelog records")
def delete_expired_jobs(self):
"""

View File

@@ -1,21 +0,0 @@
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('core', '0021_job_queue_name'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.AddIndex(
model_name='configrevision',
index=models.Index(fields=['-created'], name='core_config_created_ef9552_idx'),
),
migrations.AddIndex(
model_name='job',
index=models.Index(fields=['-created'], name='core_job_created_efa7cb_idx'),
),
]

View File

@@ -11,7 +11,7 @@ from mptt.models import MPTTModel
from core.choices import ObjectChangeActionChoices
from core.querysets import ObjectChangeQuerySet
from netbox.models.features import ChangeLoggingMixin, has_feature
from utilities.data import deep_compare_dict
from utilities.data import shallow_compare_dict
__all__ = (
'ObjectChange',
@@ -199,18 +199,18 @@ class ObjectChange(models.Model):
# Determine which attributes have changed
if self.action == ObjectChangeActionChoices.ACTION_CREATE:
changed_attrs = sorted(postchange_data.keys())
return {
'pre': {k: prechange_data.get(k) for k in changed_attrs},
'post': {k: postchange_data.get(k) for k in changed_attrs},
}
if self.action == ObjectChangeActionChoices.ACTION_DELETE:
elif self.action == ObjectChangeActionChoices.ACTION_DELETE:
changed_attrs = sorted(prechange_data.keys())
return {
'pre': {k: prechange_data.get(k) for k in changed_attrs},
'post': {k: postchange_data.get(k) for k in changed_attrs},
}
diff_added, diff_removed = deep_compare_dict(prechange_data, postchange_data)
else:
# TODO: Support deep (recursive) comparison
changed_data = shallow_compare_dict(prechange_data, postchange_data)
changed_attrs = sorted(changed_data.keys())
return {
'pre': dict(sorted(diff_removed.items())),
'post': dict(sorted(diff_added.items())),
'pre': {
k: prechange_data.get(k) for k in changed_attrs
},
'post': {
k: postchange_data.get(k) for k in changed_attrs
},
}

View File

@@ -37,9 +37,6 @@ class ConfigRevision(models.Model):
class Meta:
ordering = ['-created']
indexes = (
models.Index(fields=('-created',)), # Default ordering
)
verbose_name = _('config revision')
verbose_name_plural = _('config revisions')
constraints = [

View File

@@ -133,7 +133,6 @@ class Job(models.Model):
class Meta:
ordering = ['-created']
indexes = (
models.Index(fields=('-created',)), # Default ordering
models.Index(fields=('object_type', 'object_id')),
)
verbose_name = _('job')

View File

@@ -19,6 +19,7 @@ REVISION_BUTTONS = """
class ConfigRevisionTable(NetBoxTable):
is_active = columns.BooleanColumn(
verbose_name=_('Is Active'),
accessor='active',
false_mark=None
)
actions = columns.ActionsColumn(

View File

@@ -1,6 +1,4 @@
import django_tables2 as tables
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from core.constants import JOB_LOG_ENTRY_LEVELS
@@ -84,9 +82,3 @@ class JobLogEntryTable(BaseTable):
class Meta(BaseTable.Meta):
empty_text = _('No log entries')
fields = ('timestamp', 'level', 'message')
def render_message(self, record, value):
if record.get('level') == 'error' and '\n' in value:
value = conditional_escape(value)
return mark_safe(f'<pre class="p-0">{value}</pre>')
return value

View File

@@ -1,16 +1,9 @@
import logging
import uuid
from datetime import timedelta
from unittest.mock import patch
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase, override_settings
from django.test import override_settings
from django.urls import reverse
from django.utils import timezone
from rest_framework import status
from core.choices import ObjectChangeActionChoices
from core.jobs import SystemHousekeepingJob
from core.models import ObjectChange, ObjectType
from dcim.choices import InterfaceTypeChoices, ModuleStatusChoices, SiteStatusChoices
from dcim.models import (
@@ -701,99 +694,3 @@ class ChangeLogAPITest(APITestCase):
self.assertEqual(changes[3].changed_object_type, ContentType.objects.get_for_model(Module))
self.assertEqual(changes[3].changed_object_id, module.pk)
self.assertEqual(changes[3].action, ObjectChangeActionChoices.ACTION_DELETE)
class ChangelogPruneRetentionTest(TestCase):
"""Test suite for Changelog pruning retention settings."""
@staticmethod
def _make_oc(*, ct, obj_id, action, ts):
oc = ObjectChange.objects.create(
changed_object_type=ct,
changed_object_id=obj_id,
action=action,
user_name='test',
request_id=uuid.uuid4(),
object_repr=f'Object {obj_id}',
)
ObjectChange.objects.filter(pk=oc.pk).update(time=ts)
return oc.pk
@staticmethod
def _run_prune(*, retention_days, retain_create_last_update):
job = SystemHousekeepingJob.__new__(SystemHousekeepingJob)
job.logger = logging.getLogger('netbox.tests.changelog_prune')
with patch('core.jobs.Config') as MockConfig:
cfg = MockConfig.return_value
cfg.CHANGELOG_RETENTION = retention_days
cfg.CHANGELOG_RETAIN_CREATE_LAST_UPDATE = retain_create_last_update
job.prune_changelog()
def test_prune_retain_create_last_update_excludes_deleted_objects(self):
ct = ContentType.objects.get_for_model(Site)
retention_days = 90
now = timezone.now()
cutoff = now - timedelta(days=retention_days)
expired_old = cutoff - timedelta(days=10)
expired_newer = cutoff - timedelta(days=1)
not_expired = cutoff + timedelta(days=1)
# A) Not deleted: should keep CREATE + latest UPDATE, prune intermediate UPDATEs
a_create = self._make_oc(ct=ct, obj_id=1, action=ObjectChangeActionChoices.ACTION_CREATE, ts=expired_old)
a_update1 = self._make_oc(ct=ct, obj_id=1, action=ObjectChangeActionChoices.ACTION_UPDATE, ts=expired_old)
a_update2 = self._make_oc(ct=ct, obj_id=1, action=ObjectChangeActionChoices.ACTION_UPDATE, ts=expired_newer)
# B) Deleted (all expired): should keep NOTHING
b_create = self._make_oc(ct=ct, obj_id=2, action=ObjectChangeActionChoices.ACTION_CREATE, ts=expired_old)
b_update = self._make_oc(ct=ct, obj_id=2, action=ObjectChangeActionChoices.ACTION_UPDATE, ts=expired_newer)
b_delete = self._make_oc(ct=ct, obj_id=2, action=ObjectChangeActionChoices.ACTION_DELETE, ts=expired_newer)
# C) Deleted but delete is not expired: create/update expired should be pruned; delete remains
c_create = self._make_oc(ct=ct, obj_id=3, action=ObjectChangeActionChoices.ACTION_CREATE, ts=expired_old)
c_update = self._make_oc(ct=ct, obj_id=3, action=ObjectChangeActionChoices.ACTION_UPDATE, ts=expired_newer)
c_delete = self._make_oc(ct=ct, obj_id=3, action=ObjectChangeActionChoices.ACTION_DELETE, ts=not_expired)
self._run_prune(retention_days=retention_days, retain_create_last_update=True)
remaining = set(ObjectChange.objects.values_list('pk', flat=True))
# A) Not deleted -> create + latest update remain
self.assertIn(a_create, remaining)
self.assertIn(a_update2, remaining)
self.assertNotIn(a_update1, remaining)
# B) Deleted (all expired) -> nothing remains
self.assertNotIn(b_create, remaining)
self.assertNotIn(b_update, remaining)
self.assertNotIn(b_delete, remaining)
# C) Deleted, delete not expired -> delete remains, but create/update are pruned
self.assertNotIn(c_create, remaining)
self.assertNotIn(c_update, remaining)
self.assertIn(c_delete, remaining)
def test_prune_disabled_deletes_all_expired(self):
ct = ContentType.objects.get_for_model(Site)
retention_days = 90
now = timezone.now()
cutoff = now - timedelta(days=retention_days)
expired = cutoff - timedelta(days=1)
not_expired = cutoff + timedelta(days=1)
# expired create/update should be deleted when feature disabled
x_create = self._make_oc(ct=ct, obj_id=10, action=ObjectChangeActionChoices.ACTION_CREATE, ts=expired)
x_update = self._make_oc(ct=ct, obj_id=10, action=ObjectChangeActionChoices.ACTION_UPDATE, ts=expired)
# non-expired delete should remain regardless
y_delete = self._make_oc(ct=ct, obj_id=11, action=ObjectChangeActionChoices.ACTION_DELETE, ts=not_expired)
self._run_prune(retention_days=retention_days, retain_create_last_update=False)
remaining = set(ObjectChange.objects.values_list('pk', flat=True))
self.assertNotIn(x_create, remaining)
self.assertNotIn(x_update, remaining)
self.assertIn(y_delete, remaining)

View File

@@ -0,0 +1,26 @@
from core.models import ObjectChange
from core.tables import *
from utilities.testing import TableTestCases
class DataSourceTableTest(TableTestCases.StandardTableTestCase):
table = DataSourceTable
class DataFileTableTest(TableTestCases.StandardTableTestCase):
table = DataFileTable
class JobTableTest(TableTestCases.StandardTableTestCase):
table = JobTable
class ObjectChangeTableTest(TableTestCases.StandardTableTestCase):
table = ObjectChangeTable
queryset_sources = [
('ObjectChangeListView', ObjectChange.objects.valid_models()),
]
class ConfigRevisionTableTest(TableTestCases.StandardTableTestCase):
table = ConfigRevisionTable

View File

@@ -6,7 +6,7 @@ from datetime import datetime
from django.urls import reverse
from django.utils import timezone
from django_rq import get_queue
from django_rq.settings import QUEUES_MAP
from django_rq.settings import get_queues_map
from django_rq.workers import get_worker
from rq.job import Job as RQ_Job
from rq.job import JobStatus
@@ -189,7 +189,7 @@ class BackgroundTaskTestCase(TestCase):
def test_background_tasks_list_default(self):
queue = get_queue('default')
queue.enqueue(self.dummy_job_default)
queue_index = QUEUES_MAP['default']
queue_index = get_queues_map()['default']
response = self.client.get(reverse('core:background_task_list', args=[queue_index, 'queued']))
self.assertEqual(response.status_code, 200)
@@ -198,7 +198,7 @@ class BackgroundTaskTestCase(TestCase):
def test_background_tasks_list_high(self):
queue = get_queue('high')
queue.enqueue(self.dummy_job_high)
queue_index = QUEUES_MAP['high']
queue_index = get_queues_map()['high']
response = self.client.get(reverse('core:background_task_list', args=[queue_index, 'queued']))
self.assertEqual(response.status_code, 200)
@@ -207,7 +207,7 @@ class BackgroundTaskTestCase(TestCase):
def test_background_tasks_list_finished(self):
queue = get_queue('default')
job = queue.enqueue(self.dummy_job_default)
queue_index = QUEUES_MAP['default']
queue_index = get_queues_map()['default']
registry = FinishedJobRegistry(queue.name, queue.connection)
registry.add(job, 2)
@@ -218,7 +218,7 @@ class BackgroundTaskTestCase(TestCase):
def test_background_tasks_list_failed(self):
queue = get_queue('default')
job = queue.enqueue(self.dummy_job_default)
queue_index = QUEUES_MAP['default']
queue_index = get_queues_map()['default']
registry = FailedJobRegistry(queue.name, queue.connection)
registry.add(job, 2)
@@ -229,7 +229,7 @@ class BackgroundTaskTestCase(TestCase):
def test_background_tasks_scheduled(self):
queue = get_queue('default')
queue.enqueue_at(datetime.now(), self.dummy_job_default)
queue_index = QUEUES_MAP['default']
queue_index = get_queues_map()['default']
response = self.client.get(reverse('core:background_task_list', args=[queue_index, 'scheduled']))
self.assertEqual(response.status_code, 200)
@@ -238,7 +238,7 @@ class BackgroundTaskTestCase(TestCase):
def test_background_tasks_list_deferred(self):
queue = get_queue('default')
job = queue.enqueue(self.dummy_job_default)
queue_index = QUEUES_MAP['default']
queue_index = get_queues_map()['default']
registry = DeferredJobRegistry(queue.name, queue.connection)
registry.add(job, 2)
@@ -335,7 +335,7 @@ class BackgroundTaskTestCase(TestCase):
worker2 = get_worker('high')
worker2.register_birth()
queue_index = QUEUES_MAP['default']
queue_index = get_queues_map()['default']
response = self.client.get(reverse('core:worker_list', args=[queue_index]))
self.assertEqual(response.status_code, 200)
self.assertIn(str(worker1.name), str(response.content))

View File

@@ -1,7 +1,7 @@
from django.http import Http404
from django.utils.translation import gettext_lazy as _
from django_rq.queues import get_queue, get_queue_by_index, get_redis_connection
from django_rq.settings import QUEUES_LIST, QUEUES_MAP
from django_rq.settings import get_queues_list, get_queues_map
from django_rq.utils import get_jobs, stop_jobs
from rq import requeue_job
from rq.exceptions import NoSuchJobError
@@ -31,7 +31,7 @@ def get_rq_jobs():
"""
jobs = set()
for queue in QUEUES_LIST:
for queue in get_queues_list():
queue = get_queue(queue['name'])
jobs.update(queue.get_jobs())
@@ -78,13 +78,13 @@ def delete_rq_job(job_id):
"""
Delete the specified RQ job.
"""
config = QUEUES_LIST[0]
config = get_queues_list()[0]
try:
job = RQ_Job.fetch(job_id, connection=get_redis_connection(config['connection_config']),)
except NoSuchJobError:
raise Http404(_("Job {job_id} not found").format(job_id=job_id))
queue_index = QUEUES_MAP[job.origin]
queue_index = get_queues_map()[job.origin]
queue = get_queue_by_index(queue_index)
# Remove job id from queue and delete the actual job
@@ -96,13 +96,13 @@ def requeue_rq_job(job_id):
"""
Requeue the specified RQ job.
"""
config = QUEUES_LIST[0]
config = get_queues_list()[0]
try:
job = RQ_Job.fetch(job_id, connection=get_redis_connection(config['connection_config']),)
except NoSuchJobError:
raise Http404(_("Job {id} not found.").format(id=job_id))
queue_index = QUEUES_MAP[job.origin]
queue_index = get_queues_map()[job.origin]
queue = get_queue_by_index(queue_index)
requeue_job(job_id, connection=queue.connection, serializer=queue.serializer)
@@ -112,13 +112,13 @@ def enqueue_rq_job(job_id):
"""
Enqueue the specified RQ job.
"""
config = QUEUES_LIST[0]
config = get_queues_list()[0]
try:
job = RQ_Job.fetch(job_id, connection=get_redis_connection(config['connection_config']),)
except NoSuchJobError:
raise Http404(_("Job {id} not found.").format(id=job_id))
queue_index = QUEUES_MAP[job.origin]
queue_index = get_queues_map()[job.origin]
queue = get_queue_by_index(queue_index)
try:
@@ -144,13 +144,13 @@ def stop_rq_job(job_id):
"""
Stop the specified RQ job.
"""
config = QUEUES_LIST[0]
config = get_queues_list()[0]
try:
job = RQ_Job.fetch(job_id, connection=get_redis_connection(config['connection_config']),)
except NoSuchJobError:
raise Http404(_("Job {job_id} not found").format(job_id=job_id))
queue_index = QUEUES_MAP[job.origin]
queue_index = get_queues_map()[job.origin]
queue = get_queue_by_index(queue_index)
return stop_jobs(queue, job_id)[0]

View File

@@ -14,7 +14,7 @@ from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.views.generic import View
from django_rq.queues import get_connection, get_queue_by_index, get_redis_connection
from django_rq.settings import QUEUES_LIST, QUEUES_MAP
from django_rq.settings import get_queues_list, get_queues_map
from django_rq.utils import get_statistics
from rq.exceptions import NoSuchJobError
from rq.job import Job as RQ_Job
@@ -41,7 +41,7 @@ from netbox.views import generic
from netbox.views.generic.base import BaseObjectView
from netbox.views.generic.mixins import TableMixin
from utilities.apps import get_installed_apps
from utilities.data import deep_compare_dict
from utilities.data import shallow_compare_dict
from utilities.forms import ConfirmationForm
from utilities.htmx import htmx_partial
from utilities.json import ConfigJSONEncoder
@@ -94,7 +94,6 @@ class DataSourceView(GetRelatedModelsMixin, generic.ObjectView):
ObjectsTablePanel(
model='core.DataFile',
filters={'source_id': lambda ctx: ctx['object'].pk},
exclude_columns=['source'],
),
],
)
@@ -193,14 +192,8 @@ class DataFileView(generic.ObjectView):
layout.Column(
panels.DataFilePanel(),
panels.DataFileContentPanel(),
PluginContentPanel('left_page'),
),
),
layout.Row(
layout.Column(
PluginContentPanel('full_width_page'),
)
),
)
@@ -356,14 +349,17 @@ class ObjectChangeView(generic.ObjectView):
prechange_data = instance.prechange_data_clean
if prechange_data and instance.postchange_data:
diff_added, diff_removed = deep_compare_dict(
prechange_data,
instance.postchange_data_clean,
diff_added = shallow_compare_dict(
prechange_data or dict(),
instance.postchange_data_clean or dict(),
exclude=['last_updated'],
)
diff_removed = {
x: prechange_data.get(x) for x in diff_added
} if prechange_data else {}
else:
diff_added = {}
diff_removed = {}
diff_added = None
diff_removed = None
return {
'diff_added': diff_added,
@@ -528,13 +524,13 @@ class BackgroundTaskView(BaseRQView):
def get(self, request, job_id):
# all the RQ queues should use the same connection
config = QUEUES_LIST[0]
config = get_queues_list()[0]
try:
job = RQ_Job.fetch(job_id, connection=get_redis_connection(config['connection_config']),)
except NoSuchJobError:
raise Http404(_("Job {job_id} not found").format(job_id=job_id))
queue_index = QUEUES_MAP[job.origin]
queue_index = get_queues_map()[job.origin]
queue = get_queue_by_index(queue_index)
try:
@@ -644,7 +640,7 @@ class WorkerView(BaseRQView):
def get(self, request, key):
# all the RQ queues should use the same connection
config = QUEUES_LIST[0]
config = get_queues_list()[0]
worker = Worker.find_by_key('rq:worker:' + key, connection=get_redis_connection(config['connection_config']))
# Convert microseconds to milliseconds
worker.total_working_time = worker.total_working_time / 1000

View File

@@ -38,7 +38,15 @@ class ConnectedEndpointsSerializer(serializers.ModelSerializer):
@extend_schema_field(serializers.BooleanField)
def get_connected_endpoints_reachable(self, obj):
return obj._path and obj._path.is_complete and obj._path.is_active
"""
Return whether the connected endpoints are reachable via a complete, active cable path.
"""
# Use the public `path` accessor rather than dereferencing `_path`
# directly. `path` already handles the stale in-memory relation case
# that can occur while CablePath rows are rebuilt during cable edits.
if path := obj.path:
return path.is_complete and path.is_active
return False
class PortSerializer(serializers.ModelSerializer):

View File

@@ -3,7 +3,7 @@ from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
from dcim.choices import *
from dcim.models import Cable, CableBundle, CablePath, CableTermination
from dcim.models import Cable, CablePath, CableTermination
from netbox.api.fields import ChoiceField, ContentTypeField
from netbox.api.gfk_fields import GFKSerializerField
from netbox.api.serializers import (
@@ -16,7 +16,6 @@ from tenancy.api.serializers_.tenants import TenantSerializer
from utilities.api import get_serializer_for_model
__all__ = (
'CableBundleSerializer',
'CablePathSerializer',
'CableSerializer',
'CableTerminationSerializer',
@@ -25,18 +24,6 @@ __all__ = (
)
class CableBundleSerializer(PrimaryModelSerializer):
cable_count = serializers.IntegerField(read_only=True, default=0)
class Meta:
model = CableBundle
fields = [
'id', 'url', 'display_url', 'display', 'name', 'description', 'owner', 'comments', 'tags',
'custom_fields', 'created', 'last_updated', 'cable_count',
]
brief_fields = ('id', 'url', 'display', 'name', 'description')
class CableSerializer(PrimaryModelSerializer):
a_terminations = GenericObjectSerializer(many=True, required=False)
b_terminations = GenericObjectSerializer(many=True, required=False)
@@ -44,13 +31,12 @@ class CableSerializer(PrimaryModelSerializer):
profile = ChoiceField(choices=CableProfileChoices, required=False)
tenant = TenantSerializer(nested=True, required=False, allow_null=True)
length_unit = ChoiceField(choices=CableLengthUnitChoices, allow_blank=True, required=False, allow_null=True)
bundle = CableBundleSerializer(nested=True, required=False, allow_null=True, default=None)
class Meta:
model = Cable
fields = [
'id', 'url', 'display_url', 'display', 'type', 'a_terminations', 'b_terminations', 'status', 'profile',
'tenant', 'bundle', 'label', 'color', 'length', 'length_unit', 'description', 'owner', 'comments', 'tags',
'tenant', 'label', 'color', 'length', 'length_unit', 'description', 'owner', 'comments', 'tags',
'custom_fields', 'created', 'last_updated',
]
brief_fields = ('id', 'url', 'display', 'label', 'description')

View File

@@ -423,29 +423,27 @@ class ModuleBaySerializer(OwnerMixin, NetBoxModelSerializer):
required=False,
allow_null=True
)
_occupied = serializers.BooleanField(required=False, read_only=True)
class Meta:
model = ModuleBay
fields = [
'id', 'url', 'display_url', 'display', 'device', 'module', 'name', 'label', 'position', 'enabled',
'description', 'installed_module', 'owner', 'tags', 'custom_fields', 'created', 'last_updated', '_occupied',
'id', 'url', 'display_url', 'display', 'device', 'module', 'name', 'installed_module', 'label', 'position',
'description', 'owner', 'tags', 'custom_fields', 'created', 'last_updated',
]
brief_fields = ('id', 'url', 'display', 'installed_module', 'name', 'enabled', 'description', '_occupied')
brief_fields = ('id', 'url', 'display', 'installed_module', 'name', 'description')
class DeviceBaySerializer(OwnerMixin, NetBoxModelSerializer):
device = DeviceSerializer(nested=True)
installed_device = DeviceSerializer(nested=True, required=False, allow_null=True)
_occupied = serializers.BooleanField(required=False, read_only=True)
class Meta:
model = DeviceBay
fields = [
'id', 'url', 'display_url', 'display', 'device', 'name', 'label', 'enabled', 'description',
'installed_device', 'owner', 'tags', 'custom_fields', 'created', 'last_updated', '_occupied',
'id', 'url', 'display_url', 'display', 'device', 'name', 'label', 'description', 'installed_device',
'owner', 'tags', 'custom_fields', 'created', 'last_updated',
]
brief_fields = ('id', 'url', 'display', 'device', 'name', 'enabled', 'description', '_occupied',)
brief_fields = ('id', 'url', 'display', 'device', 'name', 'description')
class InventoryItemSerializer(OwnerMixin, NetBoxModelSerializer):

View File

@@ -151,80 +151,48 @@ class ModuleSerializer(PrimaryModelSerializer):
module_bay = NestedModuleBaySerializer()
module_type = ModuleTypeSerializer(nested=True)
status = ChoiceField(choices=ModuleStatusChoices, required=False)
replicate_components = serializers.BooleanField(
required=False,
default=True,
write_only=True,
label=_('Replicate components'),
help_text=_('Automatically populate components associated with this module type (default: true)')
)
adopt_components = serializers.BooleanField(
required=False,
default=False,
write_only=True,
label=_('Adopt components'),
help_text=_('Adopt already existing components')
)
class Meta:
model = Module
fields = [
'id', 'url', 'display_url', 'display', 'device', 'module_bay', 'module_type', 'status', 'serial',
'asset_tag', 'description', 'owner', 'comments', 'tags', 'custom_fields', 'created', 'last_updated',
'replicate_components', 'adopt_components',
]
brief_fields = ('id', 'url', 'display', 'device', 'module_bay', 'module_type', 'description')
def validate(self, data):
# When used as a nested serializer (e.g. as the `module` field on device component
# serializers), `data` is already a resolved Module instance — skip our custom logic.
if self.nested:
return super().validate(data)
# Pop write-only transient fields before ValidatedModelSerializer tries to
# construct a Module instance for full_clean(); restore them afterwards.
replicate_components = data.pop('replicate_components', True)
adopt_components = data.pop('adopt_components', False)
data = super().validate(data)
# For updates these fields are not meaningful; omit them from validated_data so that
# ModelSerializer.update() does not set unexpected attributes on the instance.
if self.instance:
if self.nested:
return data
# Always pass the flags to create() so it can set the correct private attributes.
data['replicate_components'] = replicate_components
data['adopt_components'] = adopt_components
# Skip conflict checks when no component operations are requested.
if not replicate_components and not adopt_components:
# Skip validation for existing modules (updates)
if self.instance is not None:
return data
device = data.get('device')
module_type = data.get('module_type')
module_bay = data.get('module_bay')
module_type = data.get('module_type')
device = data.get('device')
# Required-field validation fires separately; skip here if any are missing.
if not all([device, module_type, module_bay]):
if not all((module_bay, module_type, device)):
return data
positions = get_module_bay_positions(module_bay)
for templates_attr, component_attr in [
('consoleporttemplates', 'consoleports'),
('consoleserverporttemplates', 'consoleserverports'),
('interfacetemplates', 'interfaces'),
('powerporttemplates', 'powerports'),
('poweroutlettemplates', 'poweroutlets'),
('rearporttemplates', 'rearports'),
('frontporttemplates', 'frontports'),
for templates, component_attribute in [
("consoleporttemplates", "consoleports"),
("consoleserverporttemplates", "consoleserverports"),
("interfacetemplates", "interfaces"),
("powerporttemplates", "powerports"),
("poweroutlettemplates", "poweroutlets"),
("rearporttemplates", "rearports"),
("frontporttemplates", "frontports"),
]:
installed_components = {
component.name: component
for component in getattr(device, component_attr).all()
component.name: component for component in getattr(device, component_attribute).all()
}
for template in getattr(module_type, templates_attr).all():
for template in getattr(module_type, templates).all():
resolved_name = template.name
if MODULE_TOKEN in template.name:
if not module_bay.position:
@@ -236,17 +204,7 @@ class ModuleSerializer(PrimaryModelSerializer):
except ValueError as e:
raise serializers.ValidationError(str(e))
existing_item = installed_components.get(resolved_name)
if adopt_components and existing_item and existing_item.module:
raise serializers.ValidationError(
_("Cannot adopt {model} {name} as it already belongs to a module").format(
model=template.component_model.__name__,
name=resolved_name
)
)
if not adopt_components and resolved_name in installed_components:
if resolved_name in installed_components:
raise serializers.ValidationError(
_("A {model} named {name} already exists").format(
model=template.component_model.__name__,
@@ -256,27 +214,6 @@ class ModuleSerializer(PrimaryModelSerializer):
return data
def create(self, validated_data):
replicate_components = validated_data.pop('replicate_components', True)
adopt_components = validated_data.pop('adopt_components', False)
# Tags are handled after save; pop them here to pass to _save_tags()
tags = validated_data.pop('tags', None)
# _adopt_components and _disable_replication must be set on the instance before
# save() is called, so we cannot delegate to super().create() here.
instance = self.Meta.model(**validated_data)
if adopt_components:
instance._adopt_components = True
if not replicate_components:
instance._disable_replication = True
instance.save()
if tags is not None:
self._save_tags(instance, tags)
return instance
class MACAddressSerializer(PrimaryModelSerializer):
assigned_object_type = ContentTypeField(

View File

@@ -317,10 +317,10 @@ class ModuleBayTemplateSerializer(ComponentTemplateSerializer):
class Meta:
model = ModuleBayTemplate
fields = [
'id', 'url', 'display', 'device_type', 'module_type', 'name', 'label', 'position', 'enabled', 'description',
'id', 'url', 'display', 'device_type', 'module_type', 'name', 'label', 'position', 'description',
'created', 'last_updated',
]
brief_fields = ('id', 'url', 'display', 'name', 'enabled', 'description')
brief_fields = ('id', 'url', 'display', 'name', 'description')
class DeviceBayTemplateSerializer(ComponentTemplateSerializer):
@@ -331,10 +331,10 @@ class DeviceBayTemplateSerializer(ComponentTemplateSerializer):
class Meta:
model = DeviceBayTemplate
fields = [
'id', 'url', 'display', 'device_type', 'name', 'label', 'enabled', 'description',
'id', 'url', 'display', 'device_type', 'name', 'label', 'description',
'created', 'last_updated'
]
brief_fields = ('id', 'url', 'display', 'name', 'enabled', 'description')
brief_fields = ('id', 'url', 'display', 'name', 'description')
class InventoryItemTemplateSerializer(ComponentTemplateSerializer):

View File

@@ -3,7 +3,7 @@ from rest_framework import serializers
from dcim.choices import *
from dcim.constants import *
from dcim.models import Rack, RackGroup, RackReservation, RackRole, RackType
from dcim.models import Rack, RackReservation, RackRole, RackType
from netbox.api.fields import ChoiceField, RelatedObjectCountField
from netbox.api.serializers import OrganizationalModelSerializer, PrimaryModelSerializer
from netbox.choices import *
@@ -16,7 +16,6 @@ from .sites import LocationSerializer, SiteSerializer
__all__ = (
'RackElevationDetailFilterSerializer',
'RackGroupSerializer',
'RackReservationSerializer',
'RackRoleSerializer',
'RackSerializer',
@@ -24,20 +23,6 @@ __all__ = (
)
class RackGroupSerializer(OrganizationalModelSerializer):
# Related object counts
rack_count = RelatedObjectCountField('racks')
class Meta:
model = RackGroup
fields = [
'id', 'url', 'display_url', 'display', 'name', 'slug', 'description', 'owner', 'comments', 'tags',
'custom_fields', 'created', 'last_updated', 'rack_count',
]
brief_fields = ('id', 'url', 'display', 'name', 'slug', 'description', 'rack_count')
class RackRoleSerializer(OrganizationalModelSerializer):
# Related object counts
@@ -102,11 +87,6 @@ class RackSerializer(RackBaseSerializer):
allow_null=True,
default=None
)
group = RackGroupSerializer(
nested=True,
required=False,
allow_null=True
)
tenant = TenantSerializer(
nested=True,
required=False,
@@ -147,11 +127,11 @@ class RackSerializer(RackBaseSerializer):
class Meta:
model = Rack
fields = [
'id', 'url', 'display_url', 'display', 'name', 'facility_id', 'site', 'location', 'group', 'tenant',
'status', 'role', 'serial', 'asset_tag', 'rack_type', 'form_factor', 'width', 'u_height', 'starting_unit',
'weight', 'max_weight', 'weight_unit', 'desc_units', 'outer_width', 'outer_height', 'outer_depth',
'outer_unit', 'mounting_depth', 'airflow', 'description', 'owner', 'comments', 'tags', 'custom_fields',
'created', 'last_updated', 'device_count', 'powerfeed_count',
'id', 'url', 'display_url', 'display', 'name', 'facility_id', 'site', 'location', 'tenant', 'status',
'role', 'serial', 'asset_tag', 'rack_type', 'form_factor', 'width', 'u_height', 'starting_unit', 'weight',
'max_weight', 'weight_unit', 'desc_units', 'outer_width', 'outer_height', 'outer_depth', 'outer_unit',
'mounting_depth', 'airflow', 'description', 'owner', 'comments', 'tags', 'custom_fields', 'created',
'last_updated', 'device_count', 'powerfeed_count',
]
brief_fields = ('id', 'url', 'display', 'name', 'description', 'device_count')
@@ -173,16 +153,11 @@ class RackReservationSerializer(PrimaryModelSerializer):
allow_null=True,
)
unit_count = serializers.SerializerMethodField()
def get_unit_count(self, obj):
return len(obj.units)
class Meta:
model = RackReservation
fields = [
'id', 'url', 'display_url', 'display', 'rack', 'units', 'unit_count', 'status', 'created', 'last_updated',
'user', 'tenant', 'description', 'owner', 'comments', 'tags', 'custom_fields',
'id', 'url', 'display_url', 'display', 'rack', 'units', 'status', 'created', 'last_updated', 'user',
'tenant', 'description', 'owner', 'comments', 'tags', 'custom_fields',
]
brief_fields = ('id', 'url', 'display', 'status', 'user', 'description', 'units')

View File

@@ -12,7 +12,6 @@ router.register('sites', views.SiteViewSet)
# Racks
router.register('locations', views.LocationViewSet)
router.register('rack-groups', views.RackGroupViewSet)
router.register('rack-types', views.RackTypeViewSet)
router.register('rack-roles', views.RackRoleViewSet)
router.register('racks', views.RackViewSet)
@@ -64,7 +63,6 @@ router.register('mac-addresses', views.MACAddressViewSet)
# Cables
router.register('cables', views.CableViewSet)
router.register('cable-terminations', views.CableTerminationViewSet)
router.register('cable-bundles', views.CableBundleViewSet)
# Virtual chassis
router.register('virtual-chassis', views.VirtualChassisViewSet)

View File

@@ -19,7 +19,6 @@ from netbox.api.pagination import StripCountAnnotationsPaginator
from netbox.api.viewsets import MPTTLockedMixin, NetBoxModelViewSet, NetBoxReadOnlyModelViewSet
from netbox.api.viewsets.mixins import SequentialBulkCreatesMixin
from utilities.api import get_serializer_for_model
from utilities.query import count_related
from utilities.query_functions import CollateAsChar
from virtualization.models import VirtualMachine
@@ -155,17 +154,6 @@ class LocationViewSet(MPTTLockedMixin, NetBoxModelViewSet):
filterset_class = filtersets.LocationFilterSet
#
# Rack groups
#
class RackGroupViewSet(NetBoxModelViewSet):
queryset = RackGroup.objects.all()
serializer_class = serializers.RackGroupSerializer
filterset_class = filtersets.RackGroupFilterSet
#
# Rack roles
#
@@ -586,14 +574,6 @@ class CableTerminationViewSet(NetBoxReadOnlyModelViewSet):
filterset_class = filtersets.CableTerminationFilterSet
class CableBundleViewSet(NetBoxModelViewSet):
queryset = CableBundle.objects.annotate(
cable_count=count_related(Cable, 'bundle')
)
serializer_class = serializers.CableBundleSerializer
filterset_class = filtersets.CableBundleFilterSet
#
# Virtual chassis
#

View File

@@ -254,6 +254,21 @@ class Trunk8C4PCableProfile(BaseCableProfile):
b_connectors = a_connectors
class Breakout1C2Px2C1PCableProfile(BaseCableProfile):
a_connectors = {
1: 2,
}
b_connectors = {
1: 1,
2: 1,
}
_mapping = {
(1, 1): (1, 1),
(1, 2): (2, 1),
(2, 1): (1, 2),
}
class Breakout1C4Px4C1PCableProfile(BaseCableProfile):
a_connectors = {
1: 4,

View File

@@ -1776,6 +1776,7 @@ class CableProfileChoices(ChoiceSet):
TRUNK_4C8P = 'trunk-4c8p'
TRUNK_8C4P = 'trunk-8c4p'
# Breakouts
BREAKOUT_1C2P_2C1P = 'breakout-1c2p-2c1p'
BREAKOUT_1C4P_4C1P = 'breakout-1c4p-4c1p'
BREAKOUT_1C6P_6C1P = 'breakout-1c6p-6c1p'
BREAKOUT_2C4P_8C1P_SHUFFLE = 'breakout-2c4p-8c1p-shuffle'
@@ -1815,6 +1816,7 @@ class CableProfileChoices(ChoiceSet):
(
_('Breakout'),
(
(BREAKOUT_1C2P_2C1P, _('1C2P:2C1P breakout')),
(BREAKOUT_1C4P_4C1P, _('1C4P:4C1P breakout')),
(BREAKOUT_1C6P_6C1P, _('1C6P:6C1P breakout')),
(BREAKOUT_2C4P_8C1P_SHUFFLE, _('2C4P:8C1P breakout (shuffle)')),

View File

@@ -1,5 +1,3 @@
import re
from django.db.models import Q
from .choices import InterfaceTypeChoices
@@ -81,7 +79,6 @@ NONCONNECTABLE_IFACE_TYPES = VIRTUAL_IFACE_TYPES + WIRELESS_IFACE_TYPES
#
MODULE_TOKEN = '{module}'
VC_POSITION_RE = re.compile(r'\{vc_position(?::([^}]*))?\}')
MODULAR_COMPONENT_TEMPLATE_MODELS = Q(
app_label='dcim',

View File

@@ -1,7 +1,6 @@
import django_filters
import netaddr
from django.contrib.contenttypes.models import ContentType
from django.db.models import Func, IntegerField
from django.utils.translation import gettext as _
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema_field
@@ -27,6 +26,7 @@ from tenancy.models import *
from users.filterset_mixins import OwnerFilterMixin
from users.models import User
from utilities.filters import (
MultiValueBigNumberFilter,
MultiValueCharFilter,
MultiValueContentTypeFilter,
MultiValueMACAddressFilter,
@@ -46,7 +46,6 @@ from .constants import *
from .models import *
__all__ = (
'CableBundleFilterSet',
'CableFilterSet',
'CableTerminationFilterSet',
'CabledObjectFilterSet',
@@ -87,7 +86,6 @@ __all__ = (
'PowerPortFilterSet',
'PowerPortTemplateFilterSet',
'RackFilterSet',
'RackGroupFilterSet',
'RackReservationFilterSet',
'RackRoleFilterSet',
'RackTypeFilterSet',
@@ -315,14 +313,6 @@ class LocationFilterSet(TenancyFilterSet, ContactModelFilterSet, NestedGroupMode
return queryset
@register_filterset
class RackGroupFilterSet(OrganizationalModelFilterSet):
class Meta:
model = RackGroup
fields = ('id', 'name', 'slug', 'description')
@register_filterset
class RackRoleFilterSet(OrganizationalModelFilterSet):
@@ -427,18 +417,6 @@ class RackFilterSet(PrimaryModelFilterSet, TenancyFilterSet, ContactModelFilterS
to_field_name='slug',
label=_('Location (slug)'),
)
group_id = django_filters.ModelMultipleChoiceFilter(
queryset=RackGroup.objects.all(),
distinct=False,
label=_('Group (ID)'),
)
group = django_filters.ModelMultipleChoiceFilter(
field_name='group__slug',
queryset=RackGroup.objects.all(),
distinct=False,
to_field_name='slug',
label=_('Group (slug)'),
)
manufacturer_id = django_filters.ModelMultipleChoiceFilter(
field_name='rack_type__manufacturer',
queryset=Manufacturer.objects.all(),
@@ -573,19 +551,6 @@ class RackReservationFilterSet(PrimaryModelFilterSet, TenancyFilterSet):
to_field_name='slug',
label=_('Location (slug)'),
)
group_id = django_filters.ModelMultipleChoiceFilter(
queryset=RackGroup.objects.all(),
field_name='rack__group',
distinct=False,
label=_('Group (ID)'),
)
group = django_filters.ModelMultipleChoiceFilter(
field_name='rack__group__slug',
queryset=RackGroup.objects.all(),
distinct=False,
to_field_name='slug',
label=_('Group (slug)'),
)
status = django_filters.MultipleChoiceFilter(
choices=RackReservationStatusChoices,
distinct=False,
@@ -607,30 +572,11 @@ class RackReservationFilterSet(PrimaryModelFilterSet, TenancyFilterSet):
field_name='units',
lookup_expr='contains'
)
unit_count_min = django_filters.NumberFilter(
field_name='unit_count',
lookup_expr='gte',
label=_('Minimum unit count'),
)
unit_count_max = django_filters.NumberFilter(
field_name='unit_count',
lookup_expr='lte',
label=_('Maximum unit count'),
)
class Meta:
model = RackReservation
fields = ('id', 'created', 'description')
def filter_queryset(self, queryset):
# Annotate unit_count here so unit_count_min/unit_count_max filters can reference it.
# When called from the list view the queryset is already annotated; Django silently
# overwrites a duplicate annotation with the same expression, so this is safe.
queryset = queryset.annotate(
unit_count=Func('units', function='CARDINALITY', output_field=IntegerField())
)
return super().filter_queryset(queryset)
def search(self, queryset, name, value):
if not value.strip():
return queryset
@@ -1049,7 +995,7 @@ class ModuleBayTemplateFilterSet(ChangeLoggedModelFilterSet, ModularDeviceTypeCo
class Meta:
model = ModuleBayTemplate
fields = ('id', 'name', 'label', 'position', 'enabled', 'description')
fields = ('id', 'name', 'label', 'position', 'description')
@register_filterset
@@ -1057,7 +1003,7 @@ class DeviceBayTemplateFilterSet(ChangeLoggedModelFilterSet, DeviceTypeComponent
class Meta:
model = DeviceBayTemplate
fields = ('id', 'name', 'label', 'enabled', 'description')
fields = ('id', 'name', 'label', 'description')
@register_filterset
@@ -2230,7 +2176,7 @@ class InterfaceFilterSet(
distinct=False,
label=_('LAG interface (ID)'),
)
speed = MultiValueNumberFilter()
speed = MultiValueBigNumberFilter(min_value=0)
duplex = django_filters.MultipleChoiceFilter(
choices=InterfaceDuplexChoices,
distinct=False,
@@ -2414,7 +2360,7 @@ class ModuleBayFilterSet(ModularDeviceComponentFilterSet):
class Meta:
model = ModuleBay
fields = ('id', 'name', 'label', 'position', 'enabled', 'description')
fields = ('id', 'name', 'label', 'position', 'description')
@register_filterset
@@ -2434,7 +2380,7 @@ class DeviceBayFilterSet(DeviceComponentFilterSet):
class Meta:
model = DeviceBay
fields = ('id', 'name', 'label', 'enabled', 'description')
fields = ('id', 'name', 'label', 'description')
@register_filterset
@@ -2587,23 +2533,6 @@ class VirtualChassisFilterSet(PrimaryModelFilterSet):
return queryset.filter(qs_filter).distinct()
@register_filterset
class CableBundleFilterSet(PrimaryModelFilterSet):
class Meta:
model = CableBundle
fields = ('id', 'name', 'description')
def search(self, queryset, name, value):
if not value.strip():
return queryset
return queryset.filter(
Q(name__icontains=value) |
Q(description__icontains=value) |
Q(comments__icontains=value)
)
@register_filterset
class CableFilterSet(TenancyFilterSet, PrimaryModelFilterSet):
termination_a_type = MultiValueContentTypeFilter(
@@ -2624,16 +2553,6 @@ class CableFilterSet(TenancyFilterSet, PrimaryModelFilterSet):
method='_unterminated',
label=_('Unterminated'),
)
bundle_id = django_filters.ModelMultipleChoiceFilter(
queryset=CableBundle.objects.all(),
label=_('Cable bundle (ID)'),
)
bundle = django_filters.ModelMultipleChoiceFilter(
field_name='bundle__name',
queryset=CableBundle.objects.all(),
to_field_name='name',
label=_('Cable bundle (name)'),
)
type = django_filters.MultipleChoiceFilter(
choices=CableTypeChoices,
distinct=False,

View File

@@ -3,10 +3,9 @@ from django.utils.translation import gettext_lazy as _
from dcim.models import *
from extras.models import Tag
from netbox.forms.mixins import ChangelogMessageMixin, CustomFieldsMixin
from netbox.forms.mixins import CustomFieldsMixin
from utilities.forms import form_from_model
from utilities.forms.fields import DynamicModelMultipleChoiceField, ExpandableNameField
from utilities.forms.mixins import BackgroundJobMixin
from .object_create import ComponentCreateForm
@@ -28,7 +27,7 @@ __all__ = (
# Device components
#
class DeviceBulkAddComponentForm(BackgroundJobMixin, ChangelogMessageMixin, CustomFieldsMixin, ComponentCreateForm):
class DeviceBulkAddComponentForm(CustomFieldsMixin, ComponentCreateForm):
pk = forms.ModelMultipleChoiceField(
queryset=Device.objects.all(),
widget=forms.MultipleHiddenInput()
@@ -109,13 +108,10 @@ class RearPortBulkCreateForm(
field_order = ('name', 'label', 'type', 'positions', 'mark_connected', 'description', 'tags')
class ModuleBayBulkCreateForm(
form_from_model(ModuleBay, ['enabled']),
DeviceBulkAddComponentForm
):
class ModuleBayBulkCreateForm(DeviceBulkAddComponentForm):
model = ModuleBay
field_order = ('name', 'label', 'position', 'enabled', 'description', 'tags')
replication_fields = ('name', 'label', 'position', 'enabled')
field_order = ('name', 'label', 'position', 'description', 'tags')
replication_fields = ('name', 'label', 'position')
position = ExpandableNameField(
label=_('Position'),
required=False,
@@ -123,12 +119,9 @@ class ModuleBayBulkCreateForm(
)
class DeviceBayBulkCreateForm(
form_from_model(DeviceBay, ['enabled']),
DeviceBulkAddComponentForm
):
class DeviceBayBulkCreateForm(DeviceBulkAddComponentForm):
model = DeviceBay
field_order = ('name', 'label', 'enabled', 'description', 'tags')
field_order = ('name', 'label', 'description', 'tags')
class InventoryItemBulkCreateForm(

View File

@@ -20,7 +20,13 @@ from netbox.forms.mixins import ChangelogMessageMixin, OwnerMixin
from tenancy.models import Tenant
from users.models import User
from utilities.forms import BulkEditForm, add_blank_choice, form_from_model
from utilities.forms.fields import ColorField, DynamicModelChoiceField, DynamicModelMultipleChoiceField, JSONField
from utilities.forms.fields import (
ColorField,
DynamicModelChoiceField,
DynamicModelMultipleChoiceField,
JSONField,
PositiveBigIntegerField,
)
from utilities.forms.rendering import FieldSet, InlineFields, TabbedGroups
from utilities.forms.widgets import BulkEditNullBooleanSelect, NumberWithOptions
from virtualization.models import Cluster
@@ -29,7 +35,6 @@ from wireless.models import WirelessLAN, WirelessLANGroup
__all__ = (
'CableBulkEditForm',
'CableBundleBulkEditForm',
'ConsolePortBulkEditForm',
'ConsolePortTemplateBulkEditForm',
'ConsoleServerPortBulkEditForm',
@@ -62,7 +67,6 @@ __all__ = (
'PowerPortBulkEditForm',
'PowerPortTemplateBulkEditForm',
'RackBulkEditForm',
'RackGroupBulkEditForm',
'RackReservationBulkEditForm',
'RackRoleBulkEditForm',
'RackTypeBulkEditForm',
@@ -203,14 +207,6 @@ class LocationBulkEditForm(NestedGroupModelBulkEditForm):
nullable_fields = ('parent', 'tenant', 'facility', 'description', 'comments')
class RackGroupBulkEditForm(OrganizationalModelBulkEditForm):
model = RackGroup
fieldsets = (
FieldSet('description'),
)
nullable_fields = ('description', 'comments')
class RackRoleBulkEditForm(OrganizationalModelBulkEditForm):
color = ColorField(
label=_('Color'),
@@ -346,11 +342,6 @@ class RackBulkEditForm(PrimaryModelBulkEditForm):
'site_id': '$site'
}
)
group = DynamicModelChoiceField(
label=_('Group'),
queryset=RackGroup.objects.all(),
required=False
)
tenant = DynamicModelChoiceField(
label=_('Tenant'),
queryset=Tenant.objects.all(),
@@ -450,16 +441,14 @@ class RackBulkEditForm(PrimaryModelBulkEditForm):
model = Rack
fieldsets = (
FieldSet(
'status', 'group', 'role', 'tenant', 'serial', 'asset_tag', 'rack_type', 'description', name=_('Rack')
),
FieldSet('status', 'role', 'tenant', 'serial', 'asset_tag', 'rack_type', 'description', name=_('Rack')),
FieldSet('region', 'site_group', 'site', 'location', name=_('Location')),
FieldSet('outer_width', 'outer_height', 'outer_depth', 'outer_unit', name=_('Outer Dimensions')),
FieldSet('form_factor', 'width', 'u_height', 'desc_units', 'airflow', 'mounting_depth', name=_('Hardware')),
FieldSet('weight', 'max_weight', 'weight_unit', name=_('Weight')),
)
nullable_fields = (
'location', 'group', 'tenant', 'role', 'serial', 'asset_tag', 'outer_width', 'outer_height', 'outer_depth',
'location', 'tenant', 'role', 'serial', 'asset_tag', 'outer_width', 'outer_height', 'outer_depth',
'outer_unit', 'weight', 'max_weight', 'weight_unit', 'description', 'comments',
)
@@ -787,24 +776,6 @@ class ModuleBulkEditForm(PrimaryModelBulkEditForm):
nullable_fields = ('serial', 'description', 'comments')
class CableBundleBulkEditForm(PrimaryModelBulkEditForm):
pk = forms.ModelMultipleChoiceField(
queryset=CableBundle.objects.all(),
widget=forms.MultipleHiddenInput
)
description = forms.CharField(
label=_('Description'),
max_length=200,
required=False,
)
model = CableBundle
fieldsets = (
FieldSet('description',),
)
nullable_fields = ('description', 'comments')
class CableBulkEditForm(PrimaryModelBulkEditForm):
type = forms.ChoiceField(
label=_('Type'),
@@ -829,11 +800,6 @@ class CableBulkEditForm(PrimaryModelBulkEditForm):
queryset=Tenant.objects.all(),
required=False
)
bundle = DynamicModelChoiceField(
label=_('Bundle'),
queryset=CableBundle.objects.all(),
required=False,
)
label = forms.CharField(
label=_('Label'),
max_length=100,
@@ -857,11 +823,11 @@ class CableBulkEditForm(PrimaryModelBulkEditForm):
model = Cable
fieldsets = (
FieldSet('type', 'status', 'profile', 'tenant', 'bundle', 'label', 'description'),
FieldSet('type', 'status', 'profile', 'tenant', 'label', 'description'),
FieldSet('color', 'length', 'length_unit', name=_('Attributes')),
)
nullable_fields = (
'type', 'status', 'profile', 'tenant', 'bundle', 'label', 'color', 'length', 'description', 'comments',
'type', 'status', 'profile', 'tenant', 'label', 'color', 'length', 'description', 'comments',
)
@@ -1245,11 +1211,6 @@ class ModuleBayTemplateBulkEditForm(ComponentTemplateBulkEditForm):
label=_('Description'),
required=False
)
enabled = forms.NullBooleanField(
label=_('Enabled'),
required=False,
widget=BulkEditNullBooleanSelect,
)
nullable_fields = ('label', 'position', 'description')
@@ -1268,11 +1229,6 @@ class DeviceBayTemplateBulkEditForm(ComponentTemplateBulkEditForm):
label=_('Description'),
required=False
)
enabled = forms.NullBooleanField(
label=_('Enabled'),
required=False,
widget=BulkEditNullBooleanSelect,
)
nullable_fields = ('label', 'description')
@@ -1470,7 +1426,7 @@ class InterfaceBulkEditForm(
'device_id': '$device',
}
)
speed = forms.IntegerField(
speed = PositiveBigIntegerField(
label=_('Speed'),
required=False,
widget=NumberWithOptions(
@@ -1697,23 +1653,23 @@ class RearPortBulkEditForm(
class ModuleBayBulkEditForm(
form_from_model(ModuleBay, ['label', 'position', 'enabled', 'description']),
form_from_model(ModuleBay, ['label', 'position', 'description']),
NetBoxModelBulkEditForm
):
model = ModuleBay
fieldsets = (
FieldSet('label', 'position', 'enabled', 'description'),
FieldSet('label', 'position', 'description'),
)
nullable_fields = ('label', 'position', 'description')
class DeviceBayBulkEditForm(
form_from_model(DeviceBay, ['label', 'enabled', 'description']),
form_from_model(DeviceBay, ['label', 'description']),
NetBoxModelBulkEditForm
):
model = DeviceBay
fieldsets = (
FieldSet('label', 'enabled', 'description'),
FieldSet('label', 'description'),
)
nullable_fields = ('label', 'description')

View File

@@ -34,7 +34,6 @@ from wireless.choices import WirelessRoleChoices
from .common import ModuleCommonForm
__all__ = (
'CableBundleImportForm',
'CableImportForm',
'ConsolePortImportForm',
'ConsoleServerPortImportForm',
@@ -58,7 +57,6 @@ __all__ = (
'PowerOutletImportForm',
'PowerPanelImportForm',
'PowerPortImportForm',
'RackGroupImportForm',
'RackImportForm',
'RackReservationImportForm',
'RackRoleImportForm',
@@ -189,13 +187,6 @@ class LocationImportForm(NestedGroupModelImportForm):
self.fields['parent'].queryset = self.fields['parent'].queryset.filter(**params)
class RackGroupImportForm(OrganizationalModelImportForm):
class Meta:
model = RackGroup
fields = ('name', 'slug', 'description', 'owner', 'comments', 'tags')
class RackRoleImportForm(OrganizationalModelImportForm):
class Meta:
@@ -270,13 +261,6 @@ class RackImportForm(PrimaryModelImportForm):
to_field_name='name',
help_text=_('Name of assigned tenant')
)
group = CSVModelChoiceField(
label=_('Rack group'),
queryset=RackGroup.objects.all(),
required=False,
to_field_name='name',
help_text=_('Name of assigned group')
)
status = CSVChoiceField(
label=_('Status'),
choices=RackStatusChoices,
@@ -334,10 +318,10 @@ class RackImportForm(PrimaryModelImportForm):
class Meta:
model = Rack
fields = (
'site', 'location', 'group', 'name', 'facility_id', 'tenant', 'status', 'role', 'rack_type', 'form_factor',
'serial', 'asset_tag', 'width', 'u_height', 'desc_units', 'outer_width', 'outer_height', 'outer_depth',
'outer_unit', 'mounting_depth', 'airflow', 'weight', 'max_weight', 'weight_unit', 'description', 'owner',
'comments', 'tags',
'site', 'location', 'name', 'facility_id', 'tenant', 'status', 'role', 'rack_type', 'form_factor', 'serial',
'asset_tag', 'width', 'u_height', 'desc_units', 'outer_width', 'outer_height', 'outer_depth', 'outer_unit',
'mounting_depth', 'airflow', 'weight', 'max_weight', 'weight_unit', 'description', 'owner', 'comments',
'tags',
)
def __init__(self, data=None, *args, **kwargs):
@@ -1154,13 +1138,7 @@ class ModuleBayImportForm(OwnerCSVMixin, NetBoxModelImportForm):
class Meta:
model = ModuleBay
fields = ('device', 'name', 'label', 'position', 'enabled', 'description', 'owner', 'tags')
def clean_enabled(self):
# Make sure enabled is True when it's not included in the uploaded data
if 'enabled' not in self.data:
return True
return self.cleaned_data['enabled']
fields = ('device', 'name', 'label', 'position', 'description', 'owner', 'tags')
class DeviceBayImportForm(OwnerCSVMixin, NetBoxModelImportForm):
@@ -1182,7 +1160,7 @@ class DeviceBayImportForm(OwnerCSVMixin, NetBoxModelImportForm):
class Meta:
model = DeviceBay
fields = ('device', 'name', 'label', 'enabled', 'installed_device', 'description', 'owner', 'tags')
fields = ('device', 'name', 'label', 'installed_device', 'description', 'owner', 'tags')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -1210,12 +1188,6 @@ class DeviceBayImportForm(OwnerCSVMixin, NetBoxModelImportForm):
else:
self.fields['installed_device'].queryset = Device.objects.none()
def clean_enabled(self):
# Make sure enabled is True when it's not included in the uploaded data
if 'enabled' not in self.data:
return True
return self.cleaned_data['enabled']
class InventoryItemImportForm(OwnerCSVMixin, NetBoxModelImportForm):
device = CSVModelChoiceField(
@@ -1425,12 +1397,6 @@ class MACAddressImportForm(PrimaryModelImportForm):
# Cables
#
class CableBundleImportForm(PrimaryModelImportForm):
class Meta:
model = CableBundle
fields = ('name', 'description', 'owner', 'comments', 'tags')
class CableImportForm(PrimaryModelImportForm):
# Termination A
side_a_site = CSVModelChoiceField(
@@ -1508,13 +1474,6 @@ class CableImportForm(PrimaryModelImportForm):
to_field_name='name',
help_text=_('Assigned tenant')
)
bundle = CSVModelChoiceField(
label=_('Bundle'),
queryset=CableBundle.objects.all(),
required=False,
to_field_name='name',
help_text=_('Cable bundle name'),
)
length_unit = CSVChoiceField(
label=_('Length unit'),
choices=CableLengthUnitChoices,
@@ -1532,7 +1491,7 @@ class CableImportForm(PrimaryModelImportForm):
model = Cable
fields = [
'side_a_site', 'side_a_device', 'side_a_type', 'side_a_name', 'side_b_site', 'side_b_device', 'side_b_type',
'side_b_name', 'type', 'status', 'profile', 'tenant', 'bundle', 'label', 'color', 'length', 'length_unit',
'side_b_name', 'type', 'status', 'profile', 'tenant', 'label', 'color', 'length', 'length_unit',
'description', 'owner', 'comments', 'tags',
]

View File

@@ -113,6 +113,7 @@ class ModuleCommonForm(forms.Form):
raise forms.ValidationError(
_("Cannot install module with placeholder values in a module bay with no position defined.")
)
try:
resolved_name = resolve_module_placeholder(template.name, positions)
except ValueError as e:

View File

@@ -19,7 +19,7 @@ from tenancy.forms import ContactModelFilterForm, TenancyFilterForm
from tenancy.models import Tenant
from users.models import User
from utilities.forms import BOOLEAN_WITH_BLANK_CHOICES, FilterForm, add_blank_choice
from utilities.forms.fields import ColorField, DynamicModelMultipleChoiceField, TagFilterField
from utilities.forms.fields import ColorField, DynamicModelMultipleChoiceField, PositiveBigIntegerField, TagFilterField
from utilities.forms.rendering import FieldSet
from utilities.forms.widgets import NumberWithOptions
from virtualization.models import Cluster, ClusterGroup, VirtualMachine
@@ -27,7 +27,6 @@ from vpn.models import L2VPN
from wireless.choices import *
__all__ = (
'CableBundleFilterForm',
'CableFilterForm',
'ConsoleConnectionFilterForm',
'ConsolePortFilterForm',
@@ -65,7 +64,6 @@ __all__ = (
'PowerPortTemplateFilterForm',
'RackElevationFilterForm',
'RackFilterForm',
'RackGroupFilterForm',
'RackReservationFilterForm',
'RackRoleFilterForm',
'RackTypeFilterForm',
@@ -278,15 +276,6 @@ class LocationFilterForm(TenancyFilterForm, ContactModelFilterForm, NestedGroupM
tag = TagFilterField(model)
class RackGroupFilterForm(OrganizationalModelFilterSetForm):
model = RackGroup
fieldsets = (
FieldSet('q', 'filter_id', 'tag'),
FieldSet('owner_group_id', 'owner_id', name=_('Ownership')),
)
tag = TagFilterField(model)
class RackRoleFilterForm(OrganizationalModelFilterSetForm):
model = RackRole
fieldsets = (
@@ -366,7 +355,7 @@ class RackFilterForm(TenancyFilterForm, ContactModelFilterForm, RackBaseFilterFo
model = Rack
fieldsets = (
FieldSet('q', 'filter_id', 'tag'),
FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', 'group_id', name=_('Location')),
FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', name=_('Location')),
FieldSet('status', 'role_id', 'manufacturer_id', 'rack_type_id', 'serial', 'asset_tag', name=_('Rack')),
FieldSet('form_factor', 'width', 'u_height', 'airflow', name=_('Hardware')),
FieldSet('starting_unit', 'desc_units', name=_('Numbering')),
@@ -403,12 +392,6 @@ class RackFilterForm(TenancyFilterForm, ContactModelFilterForm, RackBaseFilterFo
},
label=_('Location')
)
group_id = DynamicModelMultipleChoiceField(
queryset=RackGroup.objects.all(),
required=False,
null_option='None',
label=_('Rack group')
)
status = forms.MultipleChoiceField(
label=_('Status'),
choices=RackStatusChoices,
@@ -452,7 +435,7 @@ class RackFilterForm(TenancyFilterForm, ContactModelFilterForm, RackBaseFilterFo
class RackElevationFilterForm(RackFilterForm):
fieldsets = (
FieldSet('q', 'filter_id', 'tag'),
FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', 'group_id', 'id', name=_('Location')),
FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', 'id', name=_('Location')),
FieldSet('status', 'role_id', name=_('Function')),
FieldSet('type', 'width', 'serial', 'asset_tag', name=_('Hardware')),
FieldSet('weight', 'max_weight', 'weight_unit', name=_('Weight')),
@@ -475,8 +458,8 @@ class RackReservationFilterForm(TenancyFilterForm, PrimaryModelFilterSetForm):
model = RackReservation
fieldsets = (
FieldSet('q', 'filter_id', 'tag'),
FieldSet('status', 'user_id', 'unit_count_min', 'unit_count_max', name=_('Reservation')),
FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', 'group_id', 'rack_id', name=_('Rack')),
FieldSet('status', 'user_id', name=_('Reservation')),
FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', 'rack_id', name=_('Rack')),
FieldSet('tenant_group_id', 'tenant_id', name=_('Tenant')),
FieldSet('owner_group_id', 'owner_id', name=_('Ownership')),
)
@@ -508,17 +491,10 @@ class RackReservationFilterForm(TenancyFilterForm, PrimaryModelFilterSetForm):
label=_('Location'),
null_option='None'
)
group_id = DynamicModelMultipleChoiceField(
queryset=RackGroup.objects.all(),
required=False,
null_option='None',
label=_('Rack group')
)
rack_id = DynamicModelMultipleChoiceField(
queryset=Rack.objects.all(),
required=False,
query_params={
'group_id': '$group_id',
'site_id': '$site_id',
'location_id': '$location_id',
},
@@ -534,14 +510,6 @@ class RackReservationFilterForm(TenancyFilterForm, PrimaryModelFilterSetForm):
required=False,
label=_('User')
)
unit_count_min = forms.IntegerField(
required=False,
label=_("Minimum U's")
)
unit_count_max = forms.IntegerField(
required=False,
label=_("Maximum U's")
)
tag = TagFilterField(model)
@@ -1181,24 +1149,12 @@ class VirtualChassisFilterForm(TenancyFilterForm, PrimaryModelFilterSetForm):
tag = TagFilterField(model)
class CableBundleFilterForm(PrimaryModelFilterSetForm):
model = CableBundle
fieldsets = (
FieldSet('q', 'filter_id', 'tag'),
FieldSet('name', name=_('Attributes')),
)
tag = TagFilterField(model)
class CableFilterForm(TenancyFilterForm, PrimaryModelFilterSetForm):
model = Cable
fieldsets = (
FieldSet('q', 'filter_id', 'tag'),
FieldSet('site_id', 'location_id', 'rack_id', 'device_id', name=_('Location')),
FieldSet(
'type', 'status', 'profile', 'color', 'length', 'length_unit', 'unterminated', 'bundle_id',
name=_('Attributes'),
),
FieldSet('type', 'status', 'profile', 'color', 'length', 'length_unit', 'unterminated', name=_('Attributes')),
FieldSet('tenant_group_id', 'tenant_id', name=_('Tenant')),
FieldSet('owner_group_id', 'owner_id', name=_('Ownership')),
)
@@ -1280,11 +1236,6 @@ class CableFilterForm(TenancyFilterForm, PrimaryModelFilterSetForm):
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
bundle_id = DynamicModelMultipleChoiceField(
queryset=CableBundle.objects.all(),
required=False,
label=_('Bundle'),
)
tag = TagFilterField(model)
@@ -1652,7 +1603,7 @@ class InterfaceFilterForm(PathEndpointFilterForm, DeviceComponentFilterForm):
choices=InterfaceTypeChoices,
required=False
)
speed = forms.IntegerField(
speed = PositiveBigIntegerField(
label=_('Speed'),
required=False,
widget=NumberWithOptions(
@@ -1878,7 +1829,7 @@ class ModuleBayFilterForm(DeviceComponentFilterForm):
model = ModuleBay
fieldsets = (
FieldSet('q', 'filter_id', 'tag'),
FieldSet('name', 'label', 'position', 'enabled', name=_('Attributes')),
FieldSet('name', 'label', 'position', name=_('Attributes')),
FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', 'rack_id', name=_('Location')),
FieldSet(
'tenant_id', 'device_type_id', 'device_role_id', 'device_id', 'device_status', 'virtual_chassis_id',
@@ -1886,41 +1837,31 @@ class ModuleBayFilterForm(DeviceComponentFilterForm):
),
FieldSet('owner_group_id', 'owner_id', name=_('Ownership')),
)
tag = TagFilterField(model)
position = forms.CharField(
label=_('Position'),
required=False
)
enabled = forms.NullBooleanField(
label=_('Enabled'),
required=False,
widget=forms.Select(choices=BOOLEAN_WITH_BLANK_CHOICES),
)
tag = TagFilterField(model)
class ModuleBayTemplateFilterForm(ModularDeviceComponentTemplateFilterForm):
model = ModuleBayTemplate
fieldsets = (
FieldSet('q', 'filter_id', 'tag'),
FieldSet('name', 'label', 'position', 'enabled', name=_('Attributes')),
FieldSet('name', 'label', 'position', name=_('Attributes')),
FieldSet('device_type_id', 'module_type_id', name=_('Device')),
)
position = forms.CharField(
label=_('Position'),
required=False,
)
enabled = forms.NullBooleanField(
label=_('Enabled'),
required=False,
widget=forms.Select(choices=BOOLEAN_WITH_BLANK_CHOICES),
)
class DeviceBayFilterForm(DeviceComponentFilterForm):
model = DeviceBay
fieldsets = (
FieldSet('q', 'filter_id', 'tag'),
FieldSet('name', 'label', 'enabled', name=_('Attributes')),
FieldSet('name', 'label', name=_('Attributes')),
FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', 'rack_id', name=_('Location')),
FieldSet(
'tenant_id', 'device_type_id', 'device_role_id', 'device_id', 'device_status', 'virtual_chassis_id',
@@ -1928,11 +1869,6 @@ class DeviceBayFilterForm(DeviceComponentFilterForm):
),
FieldSet('owner_group_id', 'owner_id', name=_('Ownership')),
)
enabled = forms.NullBooleanField(
label=_('Enabled'),
required=False,
widget=forms.Select(choices=BOOLEAN_WITH_BLANK_CHOICES),
)
tag = TagFilterField(model)
@@ -1940,14 +1876,9 @@ class DeviceBayTemplateFilterForm(DeviceComponentTemplateFilterForm):
model = DeviceBayTemplate
fieldsets = (
FieldSet('q', 'filter_id', 'tag'),
FieldSet('name', 'label', 'enabled', name=_('Attributes')),
FieldSet('name', 'label', name=_('Attributes')),
FieldSet('device_type_id', name=_('Device')),
)
enabled = forms.NullBooleanField(
label=_('Enabled'),
required=False,
widget=forms.Select(choices=BOOLEAN_WITH_BLANK_CHOICES),
)
class InventoryItemFilterForm(DeviceComponentFilterForm):

View File

@@ -39,7 +39,6 @@ from wireless.models import WirelessLAN, WirelessLANGroup
from .common import InterfaceCommonForm, ModuleCommonForm
__all__ = (
'CableBundleForm',
'CableForm',
'ConsolePortForm',
'ConsolePortTemplateForm',
@@ -75,7 +74,6 @@ __all__ = (
'PowerPortForm',
'PowerPortTemplateForm',
'RackForm',
'RackGroupForm',
'RackReservationForm',
'RackRoleForm',
'RackTypeForm',
@@ -234,18 +232,6 @@ class LocationForm(TenancyForm, NestedGroupModelForm):
)
class RackGroupForm(OrganizationalModelForm):
fieldsets = (
FieldSet('name', 'slug', 'description', 'tags', name=_('Rack Group')),
)
class Meta:
model = RackGroup
fields = [
'name', 'slug', 'description', 'owner', 'comments', 'tags',
]
class RackRoleForm(OrganizationalModelForm):
fieldsets = (
FieldSet('name', 'slug', 'color', 'description', 'tags', name=_('Rack Role')),
@@ -303,11 +289,6 @@ class RackForm(TenancyForm, PrimaryModelForm):
'site_id': '$site'
}
)
group = DynamicModelChoiceField(
label=_('Rack Group'),
queryset=RackGroup.objects.all(),
required=False
)
role = DynamicModelChoiceField(
label=_('Role'),
queryset=RackRole.objects.all(),
@@ -323,7 +304,7 @@ class RackForm(TenancyForm, PrimaryModelForm):
fieldsets = (
FieldSet(
'site', 'location', 'group', 'name', 'status', 'role', 'rack_type', 'description', 'airflow', 'tags',
'site', 'location', 'name', 'status', 'role', 'rack_type', 'description', 'airflow', 'tags',
name=_('Rack')
),
FieldSet('facility_id', 'serial', 'asset_tag', name=_('Inventory Control')),
@@ -333,7 +314,7 @@ class RackForm(TenancyForm, PrimaryModelForm):
class Meta:
model = Rack
fields = [
'site', 'location', 'group', 'name', 'facility_id', 'tenant_group', 'tenant', 'status', 'role', 'serial',
'site', 'location', 'name', 'facility_id', 'tenant_group', 'tenant', 'status', 'role', 'serial',
'asset_tag', 'rack_type', 'form_factor', 'width', 'u_height', 'starting_unit', 'desc_units', 'outer_width',
'outer_height', 'outer_depth', 'outer_unit', 'mounting_depth', 'airflow', 'weight', 'max_weight',
'weight_unit', 'description', 'owner', 'comments', 'tags',
@@ -803,7 +784,7 @@ class ModuleForm(ModuleCommonForm, PrimaryModelForm):
'device_id': '$device',
},
context={
'disabled': '_occupied',
'disabled': 'installed_module',
},
)
module_type = DynamicModelChoiceField(
@@ -857,17 +838,6 @@ def get_termination_type_choices():
])
class CableBundleForm(PrimaryModelForm):
fieldsets = (
FieldSet('name', 'description', 'tags', name=_('Cable Bundle')),
)
class Meta:
model = CableBundle
fields = ['name', 'description', 'owner', 'comments', 'tags']
class CableForm(TenancyForm, PrimaryModelForm):
a_terminations_type = forms.ChoiceField(
choices=get_termination_type_choices,
@@ -881,17 +851,12 @@ class CableForm(TenancyForm, PrimaryModelForm):
widget=HTMXSelect(),
label=_('Type')
)
bundle = DynamicModelChoiceField(
queryset=CableBundle.objects.all(),
required=False,
label=_('Bundle'),
)
class Meta:
model = Cable
fields = [
'a_terminations_type', 'b_terminations_type', 'type', 'status', 'profile', 'tenant_group', 'tenant',
'bundle', 'label', 'color', 'length', 'length_unit', 'description', 'owner', 'comments', 'tags',
'label', 'color', 'length', 'length_unit', 'description', 'owner', 'comments', 'tags',
]
@@ -1098,9 +1063,7 @@ class ModularComponentTemplateForm(ComponentTemplateForm):
self.fields['name'].help_text = _(
"Alphanumeric ranges are supported for bulk creation. Mixed cases and types within a single range are not "
"supported (example: <code>[ge,xe]-0/0/[0-9]</code>). The token <code>{module}</code>, if present, will be "
"automatically replaced with the position value when creating a new module. "
"The token <code>{vc_position}</code> will be replaced with the device's Virtual Chassis position "
"(use <code>{vc_position:1}</code> to specify a fallback (default is 0))"
"automatically replaced with the position value when creating a new module."
)
@@ -1261,26 +1224,26 @@ class ModuleBayTemplateForm(ModularComponentTemplateForm):
FieldSet('device_type', name=_('Device Type')),
FieldSet('module_type', name=_('Module Type')),
),
'name', 'label', 'position', 'enabled', 'description',
'name', 'label', 'position', 'description',
),
)
class Meta:
model = ModuleBayTemplate
fields = [
'device_type', 'module_type', 'name', 'label', 'position', 'enabled', 'description',
'device_type', 'module_type', 'name', 'label', 'position', 'description',
]
class DeviceBayTemplateForm(ComponentTemplateForm):
fieldsets = (
FieldSet('device_type', 'name', 'label', 'enabled', 'description'),
FieldSet('device_type', 'name', 'label', 'description'),
)
class Meta:
model = DeviceBayTemplate
fields = [
'device_type', 'name', 'label', 'enabled', 'description',
'device_type', 'name', 'label', 'description',
]
@@ -1726,25 +1689,25 @@ class RearPortForm(ModularDeviceComponentForm):
class ModuleBayForm(ModularDeviceComponentForm):
fieldsets = (
FieldSet('device', 'module', 'name', 'label', 'position', 'enabled', 'description', 'tags',),
FieldSet('device', 'module', 'name', 'label', 'position', 'description', 'tags',),
)
class Meta:
model = ModuleBay
fields = [
'device', 'module', 'name', 'label', 'position', 'enabled', 'description', 'owner', 'tags',
'device', 'module', 'name', 'label', 'position', 'description', 'owner', 'tags',
]
class DeviceBayForm(DeviceComponentForm):
fieldsets = (
FieldSet('device', 'name', 'label', 'enabled', 'description', 'tags',),
FieldSet('device', 'name', 'label', 'description', 'tags',),
)
class Meta:
model = DeviceBay
fields = [
'device', 'name', 'label', 'enabled', 'description', 'owner', 'tags',
'device', 'name', 'label', 'description', 'owner', 'tags',
]

View File

@@ -47,7 +47,13 @@ if TYPE_CHECKING:
VRFFilter,
)
from netbox.graphql.enums import ColorEnum
from netbox.graphql.filter_lookups import FloatLookup, IntegerArrayLookup, IntegerLookup, TreeNodeFilter
from netbox.graphql.filter_lookups import (
BigIntegerLookup,
FloatLookup,
IntegerArrayLookup,
IntegerLookup,
TreeNodeFilter,
)
from users.graphql.filters import UserFilter
from virtualization.graphql.filters import ClusterFilter
from vpn.graphql.filters import L2VPNFilter, TunnelTerminationFilter
@@ -57,7 +63,6 @@ if TYPE_CHECKING:
from .enums import *
__all__ = (
'CableBundleFilter',
'CableFilter',
'CableTerminationFilter',
'ConsolePortFilter',
@@ -94,7 +99,6 @@ __all__ = (
'PowerPortFilter',
'PowerPortTemplateFilter',
'RackFilter',
'RackGroupFilter',
'RackReservationFilter',
'RackRoleFilter',
'RackTypeFilter',
@@ -108,11 +112,6 @@ __all__ = (
)
@strawberry_django.filter_type(models.CableBundle, lookups=True)
class CableBundleFilter(PrimaryModelFilter):
name: StrFilterLookup[str] | None = strawberry_django.filter_field()
@strawberry_django.filter_type(models.Cable, lookups=True)
class CableFilter(TenancyFilterMixin, PrimaryModelFilter):
type: BaseFilterLookup[Annotated['CableTypeEnum', strawberry.lazy('dcim.graphql.enums')]] | None = (
@@ -318,7 +317,6 @@ class DeviceFilter(
@strawberry_django.filter_type(models.DeviceBay, lookups=True)
class DeviceBayFilter(ComponentModelFilterMixin, NetBoxModelFilter):
enabled: FilterLookup[bool] | None = strawberry_django.filter_field()
installed_device: Annotated['DeviceFilter', strawberry.lazy('dcim.graphql.filters')] | None = (
strawberry_django.filter_field()
)
@@ -327,7 +325,7 @@ class DeviceBayFilter(ComponentModelFilterMixin, NetBoxModelFilter):
@strawberry_django.filter_type(models.DeviceBayTemplate, lookups=True)
class DeviceBayTemplateFilter(ComponentTemplateFilterMixin, ChangeLoggedModelFilter):
enabled: FilterLookup[bool] | None = strawberry_django.filter_field()
pass
@strawberry_django.filter_type(models.InventoryItemTemplate, lookups=True)
@@ -527,7 +525,7 @@ class InterfaceFilter(
strawberry_django.filter_field()
)
mgmt_only: FilterLookup[bool] | None = strawberry_django.filter_field()
speed: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = (
speed: Annotated['BigIntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = (
strawberry_django.filter_field()
)
duplex: BaseFilterLookup[Annotated['InterfaceDuplexEnum', strawberry.lazy('dcim.graphql.enums')]] | None = (
@@ -743,13 +741,11 @@ class ModuleBayFilter(ModularComponentFilterMixin, NetBoxModelFilter):
)
parent_id: ID | None = strawberry_django.filter_field()
position: StrFilterLookup[str] | None = strawberry_django.filter_field()
enabled: FilterLookup[bool] | None = strawberry_django.filter_field()
@strawberry_django.filter_type(models.ModuleBayTemplate, lookups=True)
class ModuleBayTemplateFilter(ModularComponentTemplateFilterMixin, ChangeLoggedModelFilter):
position: StrFilterLookup[str] | None = strawberry_django.filter_field()
enabled: FilterLookup[bool] | None = strawberry_django.filter_field()
@strawberry_django.filter_type(models.ModuleTypeProfile, lookups=True)
@@ -966,10 +962,6 @@ class RackFilter(
location_id: Annotated['TreeNodeFilter', strawberry.lazy('netbox.graphql.filter_lookups')] | None = (
strawberry_django.filter_field()
)
group: Annotated['RackGroupFilter', strawberry.lazy('dcim.graphql.filters')] | None = (
strawberry_django.filter_field()
)
group_id: ID | None = strawberry_django.filter_field()
status: BaseFilterLookup[Annotated['RackStatusEnum', strawberry.lazy('dcim.graphql.enums')]] | None = (
strawberry_django.filter_field()
)
@@ -985,11 +977,6 @@ class RackFilter(
)
@strawberry_django.filter_type(models.RackGroup, lookups=True)
class RackGroupFilter(OrganizationalModelFilter):
pass
@strawberry_django.filter_type(models.RackReservation, lookups=True)
class RackReservationFilter(TenancyFilterMixin, PrimaryModelFilter):
rack: Annotated['RackFilter', strawberry.lazy('dcim.graphql.filters')] | None = strawberry_django.filter_field()
@@ -997,7 +984,6 @@ class RackReservationFilter(TenancyFilterMixin, PrimaryModelFilter):
units: Annotated['IntegerArrayLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = (
strawberry_django.filter_field()
)
unit_count: ComparisonFilterLookup[int] | None = strawberry_django.filter_field()
user: Annotated['UserFilter', strawberry.lazy('users.graphql.filters')] | None = strawberry_django.filter_field()
user_id: ID | None = strawberry_django.filter_field()
description: StrFilterLookup[str] | None = strawberry_django.filter_field()

View File

@@ -9,9 +9,6 @@ class DCIMQuery:
cable: CableType = strawberry_django.field()
cable_list: list[CableType] = strawberry_django.field()
cable_bundle: CableBundleType = strawberry_django.field()
cable_bundle_list: list[CableBundleType] = strawberry_django.field()
console_port: ConsolePortType = strawberry_django.field()
console_port_list: list[ConsolePortType] = strawberry_django.field()
@@ -105,9 +102,6 @@ class DCIMQuery:
power_port_template: PowerPortTemplateType = strawberry_django.field()
power_port_template_list: list[PowerPortTemplateType] = strawberry_django.field()
rack_group: RackGroupType = strawberry_django.field()
rack_group_list: list[RackGroupType] = strawberry_django.field()
rack_type: RackTypeType = strawberry_django.field()
rack_type_list: list[RackTypeType] = strawberry_django.field()

View File

@@ -2,7 +2,6 @@ from typing import TYPE_CHECKING, Annotated
import strawberry
import strawberry_django
from django.db.models import Func, IntegerField
from core.graphql.mixins import ChangelogMixin
from dcim import models
@@ -40,7 +39,6 @@ if TYPE_CHECKING:
from wireless.graphql.types import WirelessLANType, WirelessLinkType
__all__ = (
'CableBundleType',
'CableType',
'ComponentType',
'ConsolePortTemplateType',
@@ -75,7 +73,6 @@ __all__ = (
'PowerPanelType',
'PowerPortTemplateType',
'PowerPortType',
'RackGroupType',
'RackReservationType',
'RackRoleType',
'RackType',
@@ -129,16 +126,6 @@ class ModularComponentTemplateType(ComponentTemplateType):
#
@strawberry_django.type(
models.CableBundle,
fields='__all__',
filters=CableBundleFilter,
pagination=True
)
class CableBundleType(PrimaryObjectType):
cables: list[Annotated['CableType', strawberry.lazy('dcim.graphql.types')]]
@strawberry_django.type(
models.CableTermination,
exclude=['termination_type', 'termination_id', '_device', '_rack', '_location', '_site'],
@@ -170,7 +157,6 @@ class CableTerminationType(NetBoxObjectType):
class CableType(PrimaryObjectType):
color: str
tenant: Annotated['TenantType', strawberry.lazy('tenancy.graphql.types')] | None
bundle: Annotated['CableBundleType', strawberry.lazy('dcim.graphql.types')] | None
terminations: list[CableTerminationType]
@@ -447,6 +433,7 @@ class MACAddressType(PrimaryObjectType):
)
class InterfaceType(IPAddressesMixin, ModularComponentType, CabledObjectMixin, PathEndpointMixin):
_name: str
speed: BigInt | None
wwn: str | None
parent: Annotated["InterfaceType", strawberry.lazy('dcim.graphql.types')] | None
bridge: Annotated["InterfaceType", strawberry.lazy('dcim.graphql.types')] | None
@@ -750,17 +737,6 @@ class PowerPortTemplateType(ModularComponentTemplateType):
poweroutlet_templates: list[Annotated["PowerOutletTemplateType", strawberry.lazy('dcim.graphql.types')]]
@strawberry_django.type(
models.RackGroup,
fields='__all__',
filters=RackGroupFilter,
pagination=True
)
class RackGroupType(OrganizationalObjectType):
racks: list[Annotated["RackType", strawberry.lazy('dcim.graphql.types')]]
@strawberry_django.type(
models.RackType,
fields='__all__',
@@ -781,7 +757,6 @@ class RackTypeType(ImageAttachmentsMixin, PrimaryObjectType):
class RackType(VLANGroupsMixin, ImageAttachmentsMixin, ContactsMixin, PrimaryObjectType):
site: Annotated["SiteType", strawberry.lazy('dcim.graphql.types')]
location: Annotated["LocationType", strawberry.lazy('dcim.graphql.types')] | None
group: Annotated["RackGroupType", strawberry.lazy('dcim.graphql.types')] | None
tenant: Annotated["TenantType", strawberry.lazy('tenancy.graphql.types')] | None
role: Annotated["RackRoleType", strawberry.lazy('dcim.graphql.types')] | None
@@ -804,17 +779,6 @@ class RackReservationType(PrimaryObjectType):
tenant: Annotated["TenantType", strawberry.lazy('tenancy.graphql.types')] | None
user: Annotated["UserType", strawberry.lazy('users.graphql.types')]
@classmethod
def get_queryset(cls, queryset, info, **kwargs):
queryset = super().get_queryset(queryset, info, **kwargs)
return queryset.annotate(
unit_count=Func('units', function='CARDINALITY', output_field=IntegerField())
)
@strawberry.field
def unit_count(self) -> int:
return len(self.units)
@strawberry_django.type(
models.RackRole,

View File

@@ -22,21 +22,17 @@ def load_initial_data(apps, schema_editor):
'power_supply',
'expansion_card'
)
profile_objects = []
for name in initial_profiles:
file_path = DATA_FILES_PATH / f'{name}.json'
with file_path.open('r') as f:
data = json.load(f)
try:
profile = ModuleTypeProfile(**data)
profile_objects.append(profile)
ModuleTypeProfile.objects.using(db_alias).create(**data)
except Exception as e:
print(f"Error loading data from {file_path}")
raise e
ModuleTypeProfile.objects.using(db_alias).bulk_create(profile_objects)
class Migration(migrations.Migration):

View File

@@ -0,0 +1,15 @@
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dcim', '0226_modulebay_rebuild_tree'),
]
operations = [
migrations.AlterField(
model_name='interface',
name='speed',
field=models.PositiveBigIntegerField(blank=True, null=True),
),
]

View File

@@ -1,57 +0,0 @@
import django.db.models.deletion
import taggit.managers
from django.db import migrations, models
import netbox.models.deletion
import utilities.json
class Migration(migrations.Migration):
dependencies = [
('dcim', '0226_modulebay_rebuild_tree'),
('extras', '0134_owner'),
('users', '0015_owner'),
]
operations = [
migrations.CreateModel(
name='RackGroup',
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, unique=True)),
('slug', models.SlugField(max_length=100, unique=True)),
('description', models.CharField(blank=True, max_length=200)),
('comments', models.TextField(blank=True)),
(
'owner',
models.ForeignKey(
blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner'
),
),
('tags', taggit.managers.TaggableManager(through='extras.TaggedItem', to='extras.Tag')),
],
options={
'verbose_name': 'rack group',
'verbose_name_plural': 'rack groups',
'ordering': ('name',),
},
bases=(netbox.models.deletion.DeleteMixin, models.Model),
),
migrations.AddField(
model_name='rack',
name='group',
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.PROTECT,
related_name='racks',
to='dcim.rackgroup',
),
),
]

View File

@@ -1,54 +0,0 @@
import django.db.models.deletion
import taggit.managers
from django.db import migrations, models
import netbox.models.deletion
import utilities.json
class Migration(migrations.Migration):
dependencies = [
('dcim', '0227_rack_group'),
('extras', '0134_owner'),
('users', '0015_owner'),
]
operations = [
migrations.CreateModel(
name='CableBundle',
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)
),
('description', models.CharField(blank=True, max_length=200)),
('comments', models.TextField(blank=True)),
('name', models.CharField(max_length=100, unique=True)),
('owner', models.ForeignKey(
blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner')
),
('tags', taggit.managers.TaggableManager(through='extras.TaggedItem', to='extras.Tag')),
],
options={
'verbose_name': 'cable bundle',
'verbose_name_plural': 'cable bundles',
'ordering': ('name',),
},
bases=(netbox.models.deletion.DeleteMixin, models.Model),
),
migrations.AddField(
model_name='cable',
name='bundle',
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name='cables',
to='dcim.cablebundle',
verbose_name='bundle',
),
),
]

View File

@@ -1,30 +0,0 @@
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dcim', '0228_cable_bundle'),
]
operations = [
migrations.AddField(
model_name='devicebay',
name='enabled',
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name='devicebaytemplate',
name='enabled',
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name='modulebay',
name='enabled',
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name='modulebaytemplate',
name='enabled',
field=models.BooleanField(default=True),
),
]

View File

@@ -1,23 +0,0 @@
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dcim', '0229_devicebay_modulebay_enabled'),
]
operations = [
migrations.AlterField(
model_name='interface',
name='rf_channel_frequency',
field=models.DecimalField(
blank=True,
decimal_places=3,
help_text='Populated by selected channel (if set)',
max_digits=8,
null=True,
verbose_name='channel frequency (MHz)',
),
),
]

View File

@@ -1,78 +0,0 @@
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('dcim', '0230_interface_rf_channel_frequency_precision'),
('extras', '0136_customfield_validation_schema'),
('ipam', '0088_rename_vlangroup_total_vlan_ids'),
('tenancy', '0023_add_mptt_tree_indexes'),
('users', '0015_owner'),
('virtualization', '0054_virtualmachinetype'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.AddIndex(
model_name='consoleporttemplate',
index=models.Index(fields=['device_type', 'module_type', 'name'], name='dcim_consol_device__101ed5_idx'),
),
migrations.AddIndex(
model_name='consoleserverporttemplate',
index=models.Index(fields=['device_type', 'module_type', 'name'], name='dcim_consol_device__a901e6_idx'),
),
migrations.AddIndex(
model_name='device',
index=models.Index(fields=['name', 'id'], name='dcim_device_name_c27913_idx'),
),
migrations.AddIndex(
model_name='frontporttemplate',
index=models.Index(fields=['device_type', 'module_type', 'name'], name='dcim_frontp_device__ec2ffb_idx'),
),
migrations.AddIndex(
model_name='interfacetemplate',
index=models.Index(fields=['device_type', 'module_type', 'name'], name='dcim_interf_device__601012_idx'),
),
migrations.AddIndex(
model_name='macaddress',
index=models.Index(fields=['mac_address', 'id'], name='dcim_macadd_mac_add_f2662a_idx'),
),
migrations.AddIndex(
model_name='modulebaytemplate',
index=models.Index(fields=['device_type', 'module_type', 'name'], name='dcim_module_device__9eabad_idx'),
),
migrations.AddIndex(
model_name='moduletype',
index=models.Index(fields=['profile', 'manufacturer', 'model'], name='dcim_module_profile_868277_idx'),
),
migrations.AddIndex(
model_name='poweroutlettemplate',
index=models.Index(fields=['device_type', 'module_type', 'name'], name='dcim_powero_device__b83a8f_idx'),
),
migrations.AddIndex(
model_name='powerporttemplate',
index=models.Index(fields=['device_type', 'module_type', 'name'], name='dcim_powerp_device__6c25da_idx'),
),
migrations.AddIndex(
model_name='rack',
index=models.Index(fields=['site', 'location', 'name', 'id'], name='dcim_rack_site_id_715040_idx'),
),
migrations.AddIndex(
model_name='rackreservation',
index=models.Index(fields=['created', 'id'], name='dcim_rackre_created_84f02e_idx'),
),
migrations.AddIndex(
model_name='rearporttemplate',
index=models.Index(fields=['device_type', 'module_type', 'name'], name='dcim_rearpo_device__27f194_idx'),
),
migrations.AddIndex(
model_name='virtualchassis',
index=models.Index(fields=['name'], name='dcim_virtua_name_2dc5cd_idx'),
),
migrations.AddIndex(
model_name='virtualdevicecontext',
index=models.Index(fields=['name'], name='dcim_virtua_name_079d4d_idx'),
),
]

View File

@@ -8,7 +8,6 @@ from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.dispatch import Signal
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from core.models import ObjectType
@@ -30,7 +29,6 @@ from .device_components import FrontPort, PathEndpoint, PortMapping, RearPort
__all__ = (
'Cable',
'CableBundle',
'CablePath',
'CableTermination',
)
@@ -40,32 +38,6 @@ logger = logging.getLogger(f'netbox.{__name__}')
trace_paths = Signal()
#
# Cable bundles
#
class CableBundle(PrimaryModel):
"""
A logical grouping of individual cables.
"""
name = models.CharField(
verbose_name=_('name'),
max_length=100,
unique=True,
)
class Meta:
ordering = ('name',)
verbose_name = _('cable bundle')
verbose_name_plural = _('cable bundles')
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('dcim:cablebundle', args=[self.pk])
#
# Cables
#
@@ -130,16 +102,8 @@ class Cable(PrimaryModel):
blank=True,
null=True
)
bundle = models.ForeignKey(
to='dcim.CableBundle',
on_delete=models.SET_NULL,
related_name='cables',
blank=True,
null=True,
verbose_name=_('bundle'),
)
clone_fields = ('tenant', 'type', 'profile', 'bundle')
clone_fields = ('tenant', 'type', 'profile')
class Meta:
ordering = ('pk',)
@@ -196,6 +160,7 @@ class Cable(PrimaryModel):
CableProfileChoices.TRUNK_4C6P: cable_profiles.Trunk4C6PCableProfile,
CableProfileChoices.TRUNK_4C8P: cable_profiles.Trunk4C8PCableProfile,
CableProfileChoices.TRUNK_8C4P: cable_profiles.Trunk8C4PCableProfile,
CableProfileChoices.BREAKOUT_1C2P_2C1P: cable_profiles.Breakout1C2Px2C1PCableProfile,
CableProfileChoices.BREAKOUT_1C4P_4C1P: cable_profiles.Breakout1C4Px4C1PCableProfile,
CableProfileChoices.BREAKOUT_1C6P_6C1P: cable_profiles.Breakout1C6Px6C1PCableProfile,
CableProfileChoices.BREAKOUT_2C4P_8C1P_SHUFFLE: cable_profiles.Breakout2C4Px8C1PShuffleCableProfile,

View File

@@ -144,9 +144,6 @@ class ModularComponentTemplateModel(ComponentTemplateModel):
name='%(app_label)s_%(class)s_unique_module_type_name'
),
)
indexes = (
models.Index(fields=('device_type', 'module_type', 'name')), # Default ordering
)
def to_objectchange(self, action):
objectchange = super().to_objectchange(action)
@@ -169,47 +166,15 @@ class ModularComponentTemplateModel(ComponentTemplateModel):
_("A component template must be associated with either a device type or a module type.")
)
@staticmethod
def _resolve_vc_position(value: str, device) -> str:
"""
Resolves {vc_position} and {vc_position:X} tokens.
def resolve_name(self, module):
if MODULE_TOKEN not in self.name or not module:
return self.name
return resolve_module_placeholder(self.name, get_module_bay_positions(module.module_bay))
If the device has a vc_position, replaces the token with that value.
Otherwise uses the explicit fallback X if given, else '0'.
"""
def replacer(match):
explicit_fallback = match.group(1)
if (
device is not None
and device.virtual_chassis is not None
and device.vc_position is not None
):
return str(device.vc_position)
return explicit_fallback if explicit_fallback is not None else '0'
return VC_POSITION_RE.sub(replacer, value)
def _resolve_all_placeholders(self, value, module=None, device=None):
has_module = MODULE_TOKEN in value
has_vc = VC_POSITION_RE.search(value) is not None
if not has_module and not has_vc:
return value
if has_module and module:
positions = get_module_bay_positions(module.module_bay)
value = resolve_module_placeholder(value, positions)
if has_vc:
resolved_device = (module.device if module else None) or device
value = self._resolve_vc_position(value, resolved_device)
return value
def resolve_name(self, module=None, device=None):
return self._resolve_all_placeholders(self.name, module, device)
def resolve_label(self, module=None, device=None):
return self._resolve_all_placeholders(self.label, module, device)
def resolve_position(self, module=None, device=None):
return self._resolve_all_placeholders(self.position, module, device)
def resolve_label(self, module):
if MODULE_TOKEN not in self.label or not module:
return self.label
return resolve_module_placeholder(self.label, get_module_bay_positions(module.module_bay))
class ConsolePortTemplate(ModularComponentTemplateModel):
@@ -232,8 +197,8 @@ class ConsolePortTemplate(ModularComponentTemplateModel):
def instantiate(self, **kwargs):
return self.component_model(
name=self.resolve_name(kwargs.get('module'), kwargs.get('device')),
label=self.resolve_label(kwargs.get('module'), kwargs.get('device')),
name=self.resolve_name(kwargs.get('module')),
label=self.resolve_label(kwargs.get('module')),
type=self.type,
**kwargs
)
@@ -267,8 +232,8 @@ class ConsoleServerPortTemplate(ModularComponentTemplateModel):
def instantiate(self, **kwargs):
return self.component_model(
name=self.resolve_name(kwargs.get('module'), kwargs.get('device')),
label=self.resolve_label(kwargs.get('module'), kwargs.get('device')),
name=self.resolve_name(kwargs.get('module')),
label=self.resolve_label(kwargs.get('module')),
type=self.type,
**kwargs
)
@@ -317,8 +282,8 @@ class PowerPortTemplate(ModularComponentTemplateModel):
def instantiate(self, **kwargs):
return self.component_model(
name=self.resolve_name(kwargs.get('module'), kwargs.get('device')),
label=self.resolve_label(kwargs.get('module'), kwargs.get('device')),
name=self.resolve_name(kwargs.get('module')),
label=self.resolve_label(kwargs.get('module')),
type=self.type,
maximum_draw=self.maximum_draw,
allocated_draw=self.allocated_draw,
@@ -405,13 +370,13 @@ class PowerOutletTemplate(ModularComponentTemplateModel):
def instantiate(self, **kwargs):
if self.power_port:
power_port_name = self.power_port.resolve_name(kwargs.get('module'), kwargs.get('device'))
power_port_name = self.power_port.resolve_name(kwargs.get('module'))
power_port = PowerPort.objects.get(name=power_port_name, **kwargs)
else:
power_port = None
return self.component_model(
name=self.resolve_name(kwargs.get('module'), kwargs.get('device')),
label=self.resolve_label(kwargs.get('module'), kwargs.get('device')),
name=self.resolve_name(kwargs.get('module')),
label=self.resolve_label(kwargs.get('module')),
type=self.type,
color=self.color,
power_port=power_port,
@@ -511,8 +476,8 @@ class InterfaceTemplate(InterfaceValidationMixin, ModularComponentTemplateModel)
def instantiate(self, **kwargs):
return self.component_model(
name=self.resolve_name(kwargs.get('module'), kwargs.get('device')),
label=self.resolve_label(kwargs.get('module'), kwargs.get('device')),
name=self.resolve_name(kwargs.get('module')),
label=self.resolve_label(kwargs.get('module')),
type=self.type,
enabled=self.enabled,
mgmt_only=self.mgmt_only,
@@ -638,8 +603,8 @@ class FrontPortTemplate(ModularComponentTemplateModel):
def instantiate(self, **kwargs):
return self.component_model(
name=self.resolve_name(kwargs.get('module'), kwargs.get('device')),
label=self.resolve_label(kwargs.get('module'), kwargs.get('device')),
name=self.resolve_name(kwargs.get('module')),
label=self.resolve_label(kwargs.get('module')),
type=self.type,
color=self.color,
positions=self.positions,
@@ -702,8 +667,8 @@ class RearPortTemplate(ModularComponentTemplateModel):
def instantiate(self, **kwargs):
return self.component_model(
name=self.resolve_name(kwargs.get('module'), kwargs.get('device')),
label=self.resolve_label(kwargs.get('module'), kwargs.get('device')),
name=self.resolve_name(kwargs.get('module')),
label=self.resolve_label(kwargs.get('module')),
type=self.type,
color=self.color,
positions=self.positions,
@@ -732,10 +697,6 @@ class ModuleBayTemplate(ModularComponentTemplateModel):
blank=True,
help_text=_('Identifier to reference when renaming installed components')
)
enabled = models.BooleanField(
verbose_name=_('enabled'),
default=True,
)
component_model = ModuleBay
@@ -743,12 +704,16 @@ class ModuleBayTemplate(ModularComponentTemplateModel):
verbose_name = _('module bay template')
verbose_name_plural = _('module bay templates')
def resolve_position(self, module):
if MODULE_TOKEN not in self.position or not module:
return self.position
return resolve_module_placeholder(self.position, get_module_bay_positions(module.module_bay))
def instantiate(self, **kwargs):
return self.component_model(
name=self.resolve_name(kwargs.get('module'), kwargs.get('device')),
label=self.resolve_label(kwargs.get('module'), kwargs.get('device')),
position=self.resolve_position(kwargs.get('module'), kwargs.get('device')),
enabled=self.enabled,
name=self.resolve_name(kwargs.get('module')),
label=self.resolve_label(kwargs.get('module')),
position=self.resolve_position(kwargs.get('module')),
**kwargs
)
instantiate.do_not_call_in_templates = True
@@ -758,7 +723,6 @@ class ModuleBayTemplate(ModularComponentTemplateModel):
'name': self.name,
'label': self.label,
'position': self.position,
'enabled': self.enabled,
'description': self.description,
}
@@ -767,11 +731,6 @@ class DeviceBayTemplate(ComponentTemplateModel):
"""
A template for a DeviceBay to be created for a new parent Device.
"""
enabled = models.BooleanField(
verbose_name=_('enabled'),
default=True,
)
component_model = DeviceBay
class Meta(ComponentTemplateModel.Meta):
@@ -782,8 +741,7 @@ class DeviceBayTemplate(ComponentTemplateModel):
return self.component_model(
device=device,
name=self.name,
label=self.label,
enabled=self.enabled,
label=self.label
)
instantiate.do_not_call_in_templates = True
@@ -799,7 +757,6 @@ class DeviceBayTemplate(ComponentTemplateModel):
return {
'name': self.name,
'label': self.label,
'enabled': self.enabled,
'description': self.description,
}

View File

@@ -2,7 +2,7 @@ from functools import cached_property
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.postgres.fields import ArrayField
from django.core.exceptions import ValidationError
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.db.models import Sum
@@ -307,11 +307,12 @@ class PathEndpoint(models.Model):
`connected_endpoints()` is a convenience method for returning the destination of the associated CablePath, if any.
"""
_path = models.ForeignKey(
to='dcim.CablePath',
on_delete=models.SET_NULL,
null=True,
blank=True
blank=True,
)
class Meta:
@@ -323,11 +324,14 @@ class PathEndpoint(models.Model):
# Construct the complete path (including e.g. bridged interfaces)
while origin is not None:
if origin._path is None:
# Go through the public accessor rather than dereferencing `_path`
# directly. During cable edits, CablePath rows can be deleted and
# recreated while this endpoint instance is still in memory.
cable_path = origin.path
if cable_path is None:
break
path.extend(origin._path.path_objects)
path.extend(cable_path.path_objects)
# If the path ends at a non-connected pass-through port, pad out the link and far-end terminations
if len(path) % 3 == 1:
@@ -336,8 +340,8 @@ class PathEndpoint(models.Model):
elif len(path) % 3 == 2:
path.insert(-1, [])
# Check for a bridged relationship to continue the trace
destinations = origin._path.destinations
# Check for a bridged relationship to continue the trace.
destinations = cable_path.destinations
if len(destinations) == 1:
origin = getattr(destinations[0], 'bridge', None)
else:
@@ -348,14 +352,42 @@ class PathEndpoint(models.Model):
@property
def path(self):
return self._path
"""
Return this endpoint's current CablePath, if any.
`_path` is a denormalized reference that is updated from CablePath
save/delete handlers, including queryset.update() calls on origin
endpoints. That means an already-instantiated endpoint can briefly hold
a stale in-memory `_path` relation while the database already points to
a different CablePath (or to no path at all).
If the cached relation points to a CablePath that has just been
deleted, refresh only the `_path` field from the database and retry.
This keeps the fix cheap and narrowly scoped to the denormalized FK.
"""
if self._path_id is None:
return None
try:
return self._path
except ObjectDoesNotExist:
# Refresh only the denormalized FK instead of the whole model.
# The expected problem here is in-memory staleness during path
# rebuilds, not persistent database corruption.
self.refresh_from_db(fields=['_path'])
return self._path if self._path_id else None
@cached_property
def connected_endpoints(self):
"""
Caching accessor for the attached CablePath's destination (if any)
Caching accessor for the attached CablePath's destinations (if any).
Always route through `path` so stale in-memory `_path` references are
repaired before we cache the result for the lifetime of this instance.
"""
return self._path.destinations if self._path else []
if cable_path := self.path:
return cable_path.destinations
return []
#
@@ -774,7 +806,7 @@ class Interface(
verbose_name=_('management only'),
help_text=_('This interface is used only for out-of-band management')
)
speed = models.PositiveIntegerField(
speed = models.PositiveBigIntegerField(
blank=True,
null=True,
verbose_name=_('speed (Kbps)')
@@ -807,8 +839,8 @@ class Interface(
verbose_name=_('wireless channel')
)
rf_channel_frequency = models.DecimalField(
max_digits=8,
decimal_places=3,
max_digits=7,
decimal_places=2,
blank=True,
null=True,
verbose_name=_('channel frequency (MHz)'),
@@ -1257,14 +1289,10 @@ class ModuleBay(ModularComponentModel, TrackingModelMixin, MPTTModel):
blank=True,
help_text=_('Identifier to reference when renaming installed components')
)
enabled = models.BooleanField(
verbose_name=_('enabled'),
default=True,
)
objects = TreeManager()
clone_fields = ('device', 'enabled')
clone_fields = ('device',)
class Meta(ModularComponentModel.Meta):
# Empty tuple triggers Django migration detection for MPTT indexes
@@ -1303,13 +1331,6 @@ class ModuleBay(ModularComponentModel, TrackingModelMixin, MPTTModel):
self.parent = None
super().save(*args, **kwargs)
@property
def _occupied(self):
"""
Indicates whether the module bay is occupied by a module.
"""
return bool(not self.enabled or hasattr(self, 'installed_module'))
class DeviceBay(ComponentModel, TrackingModelMixin):
"""
@@ -1322,12 +1343,8 @@ class DeviceBay(ComponentModel, TrackingModelMixin):
blank=True,
null=True
)
enabled = models.BooleanField(
verbose_name=_('enabled'),
default=True,
)
clone_fields = ('device', 'enabled')
clone_fields = ('device',)
class Meta(ComponentModel.Meta):
verbose_name = _('device bay')
@@ -1342,16 +1359,6 @@ class DeviceBay(ComponentModel, TrackingModelMixin):
device_type=self.device.device_type
))
# Prevent installing a device into a disabled bay
if self.installed_device and not self.enabled:
current_installed_device_id = (
DeviceBay.objects.filter(pk=self.pk).values_list('installed_device_id', flat=True).first()
)
if self.pk is None or current_installed_device_id != self.installed_device_id:
raise ValidationError({
'installed_device': _("Cannot install a device in a disabled device bay.")
})
# Cannot install a device into itself, obviously
if self.installed_device and getattr(self, 'device', None) == self.installed_device:
raise ValidationError(_("Cannot install a device into itself."))
@@ -1366,13 +1373,6 @@ class DeviceBay(ComponentModel, TrackingModelMixin):
).format(bay=current_bay)
})
@property
def _occupied(self):
"""
Indicates whether the device bay is occupied by a child device.
"""
return bool(not self.enabled or self.installed_device_id)
#
# Inventory items

View File

@@ -26,7 +26,6 @@ from netbox.config import ConfigItem
from netbox.models import NestedGroupModel, OrganizationalModel, PrimaryModel
from netbox.models.features import ContactsMixin, ImageAttachmentsMixin
from netbox.models.mixins import WeightMixin
from utilities.exceptions import AbortRequest
from utilities.fields import ColorField, CounterCacheField
from utilities.prefetch import get_prefetchable_fields
from utilities.tracking import TrackingModelMixin
@@ -737,9 +736,6 @@ class Device(
class Meta:
ordering = ('name', 'pk') # Name may be null
indexes = (
models.Index(fields=('name', 'id')), # Default ordering
)
constraints = (
models.UniqueConstraint(
Lower('name'), 'site', 'tenant',
@@ -952,20 +948,6 @@ class Device(
).format(virtual_chassis=self.vc_master_for)
})
def _check_duplicate_component_names(self, components):
"""
Check for duplicate component names after resolving {vc_position} placeholders.
Raises AbortRequest if duplicates are found.
"""
names = [c.name for c in components]
duplicates = {n for n in names if names.count(n) > 1}
if duplicates:
raise AbortRequest(
_("Component name conflict after resolving {{vc_position}}: {names}").format(
names=', '.join(duplicates)
)
)
def _instantiate_components(self, queryset, bulk_create=True):
"""
Instantiate components for the device from the specified component templates.
@@ -980,10 +962,6 @@ class Device(
components = [obj.instantiate(device=self) for obj in queryset]
if not components:
return
# Check for duplicate names after resolution {vc_position}
self._check_duplicate_component_names(components)
# Set default values for any applicable custom fields
if cf_defaults := CustomField.objects.get_defaults_for_model(model):
for component in components:
@@ -1008,14 +986,8 @@ class Device(
update_fields=None
)
else:
components = [obj.instantiate(device=self) for obj in queryset]
if not components:
return
# Check for duplicate names after resolution {vc_position}
self._check_duplicate_component_names(components)
for component in components:
for obj in queryset:
component = obj.instantiate(device=self)
# Set default values for any applicable custom fields
if cf_defaults := CustomField.objects.get_defaults_for_model(model):
component.custom_field_data = cf_defaults
@@ -1187,9 +1159,6 @@ class VirtualChassis(PrimaryModel):
class Meta:
ordering = ['name']
indexes = (
models.Index(fields=('name',)), # Default ordering
)
verbose_name = _('virtual chassis')
verbose_name_plural = _('virtual chassis')
@@ -1296,9 +1265,6 @@ class VirtualDeviceContext(PrimaryModel):
name='%(app_label)s_%(class)s_device_name'
),
)
indexes = (
models.Index(fields=('name',)), # Default ordering
)
verbose_name = _('virtual device context')
verbose_name_plural = _('virtual device contexts')
@@ -1365,7 +1331,6 @@ class MACAddress(PrimaryModel):
class Meta:
ordering = ('mac_address', 'pk')
indexes = (
models.Index(fields=('mac_address', 'id')), # Default ordering
models.Index(fields=('assigned_object_type', 'assigned_object_id')),
)
verbose_name = _('MAC address')

View File

@@ -113,9 +113,6 @@ class ModuleType(ImageAttachmentsMixin, PrimaryModel, WeightMixin):
name='%(app_label)s_%(class)s_unique_manufacturer_model'
),
)
indexes = (
models.Index(fields=('profile', 'manufacturer', 'model')), # Default ordering
)
verbose_name = _('module type')
verbose_name_plural = _('module types')
@@ -261,14 +258,6 @@ class Module(TrackingModelMixin, PrimaryModel, ConfigContextModel):
)
)
# Prevent module from being installed in a disabled bay
if hasattr(self, 'module_bay') and self.module_bay and not self.module_bay.enabled:
current_module_bay_id = Module.objects.filter(pk=self.pk).values_list('module_bay_id', flat=True).first()
if self.pk is None or current_module_bay_id != self.module_bay_id:
raise ValidationError({
'module_bay': _("Cannot install a module in a disabled module bay.")
})
# Check for recursion
module = self
module_bays = []

View File

@@ -29,30 +29,14 @@ from .power import PowerFeed
__all__ = (
'Rack',
'RackGroup',
'RackReservation',
'RackRole',
'RackType',
)
#
# Rack Organization
#
class RackGroup(OrganizationalModel):
"""
Racks can be grouped by physical placement within a Location.
"""
class Meta:
ordering = ('name',)
verbose_name = _('rack group')
verbose_name_plural = _('rack groups')
#
# Rack Base
# Rack Types
#
class RackBase(WeightMixin, PrimaryModel):
@@ -139,10 +123,6 @@ class RackBase(WeightMixin, PrimaryModel):
abstract = True
#
# Rack Types
#
class RackType(ImageAttachmentsMixin, RackBase):
"""
Devices are housed within Racks. Each rack has a defined height measured in rack units, and a front and rear face.
@@ -310,14 +290,6 @@ class Rack(ContactsMixin, ImageAttachmentsMixin, TrackingModelMixin, RackBase):
blank=True,
null=True
)
group = models.ForeignKey(
to='dcim.RackGroup',
on_delete=models.PROTECT,
related_name='racks',
blank=True,
null=True,
help_text=_('physical grouping')
)
tenant = models.ForeignKey(
to='tenancy.Tenant',
on_delete=models.PROTECT,
@@ -390,9 +362,6 @@ class Rack(ContactsMixin, ImageAttachmentsMixin, TrackingModelMixin, RackBase):
name='%(app_label)s_%(class)s_unique_location_facility_id'
),
)
indexes = (
models.Index(fields=('site', 'location', 'name', 'id')), # Default ordering
)
verbose_name = _('rack')
verbose_name_plural = _('racks')
@@ -741,9 +710,6 @@ class RackReservation(PrimaryModel):
class Meta:
ordering = ['created', 'pk']
indexes = (
models.Index(fields=('created', 'id')), # Default ordering
)
verbose_name = _('rack reservation')
verbose_name_plural = _('rack reservations')

View File

@@ -3,17 +3,6 @@ from netbox.search import SearchIndex, register_search
from . import models
@register_search
class CableBundleIndex(SearchIndex):
model = models.CableBundle
fields = (
('name', 100),
('description', 500),
('comments', 5000),
)
display_attrs = ('description',)
@register_search
class CableIndex(SearchIndex):
model = models.Cable
@@ -326,18 +315,6 @@ class RackReservationIndex(SearchIndex):
display_attrs = ('rack', 'tenant', 'user', 'description')
@register_search
class RackGroupIndex(SearchIndex):
model = models.RackGroup
fields = (
('name', 100),
('slug', 110),
('description', 500),
('comments', 5000),
)
display_attrs = ('description',)
@register_search
class RackRoleIndex(SearchIndex):
model = models.RackRole

View File

@@ -4,14 +4,13 @@ from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from django_tables2.utils import Accessor
from dcim.models import Cable, CableBundle
from dcim.models import Cable
from netbox.tables import PrimaryModelTable, columns
from tenancy.tables import TenancyColumnsMixin
from .template_code import CABLE_LENGTH
__all__ = (
'CableBundleTable',
'CableTable',
)
@@ -120,10 +119,6 @@ class CableTable(TenancyColumnsMixin, PrimaryModelTable):
verbose_name=_('Color Name'),
orderable=False
)
bundle = tables.Column(
verbose_name=_('Bundle'),
linkify=True,
)
tags = columns.TagColumn(
url_name='dcim:cable_list'
)
@@ -133,30 +128,8 @@ class CableTable(TenancyColumnsMixin, PrimaryModelTable):
fields = (
'pk', 'id', 'label', 'a_terminations', 'b_terminations', 'device_a', 'device_b', 'rack_a', 'rack_b',
'location_a', 'location_b', 'site_a', 'site_b', 'status', 'profile', 'type', 'tenant', 'tenant_group',
'color', 'color_name', 'bundle', 'length', 'description', 'comments', 'tags', 'created', 'last_updated',
'color', 'color_name', 'length', 'description', 'comments', 'tags', 'created', 'last_updated',
)
default_columns = (
'pk', 'id', 'label', 'a_terminations', 'b_terminations', 'status', 'type',
)
class CableBundleTable(PrimaryModelTable):
name = tables.Column(
verbose_name=_('Name'),
linkify=True,
)
cable_count = tables.Column(
verbose_name=_('Cables'),
)
tags = columns.TagColumn(
url_name='dcim:cablebundle_list'
)
class Meta(PrimaryModelTable.Meta):
model = CableBundle
fields = (
'pk', 'id', 'name', 'cable_count', 'description', 'tags', 'created', 'last_updated',
)
default_columns = (
'pk', 'id', 'name', 'cable_count', 'description',
)

View File

@@ -382,6 +382,17 @@ class PathEndpointTable(CableTerminationTable):
orderable=False
)
def value_connection(self, value):
if value:
connections = []
for termination in value:
if hasattr(termination, 'parent_object'):
connections.append(f'{termination.parent_object} > {termination}')
else:
connections.append(str(termination))
return ', '.join(connections)
return None
class ConsolePortTable(ModularDeviceComponentTable, PathEndpointTable):
device = tables.Column(
@@ -683,6 +694,15 @@ class InterfaceTable(BaseInterfaceTable, ModularDeviceComponentTable, PathEndpoi
orderable=False
)
def value_connection(self, record, value):
if record.is_virtual and hasattr(record, 'virtual_circuit_termination') and record.virtual_circuit_termination:
connections = [
f"{t.interface.parent_object} > {t.interface} via {t.parent_object}"
for t in record.connected_endpoints
]
return ', '.join(connections)
return super().value_connection(value)
class Meta(DeviceComponentTable.Meta):
model = models.Interface
fields = (
@@ -888,9 +908,6 @@ class DeviceBayTable(DeviceComponentTable):
'args': [Accessor('device_id')],
}
)
enabled = columns.BooleanColumn(
verbose_name=_('Enabled'),
)
status = tables.TemplateColumn(
verbose_name=_('Status'),
template_code=DEVICEBAY_STATUS,
@@ -928,12 +945,12 @@ class DeviceBayTable(DeviceComponentTable):
class Meta(DeviceComponentTable.Meta):
model = models.DeviceBay
fields = (
'pk', 'id', 'name', 'device', 'label', 'enabled', 'status', 'description', 'installed_device',
'installed_role', 'installed_device_type', 'installed_description', 'installed_serial',
'installed_asset_tag', 'tags', 'created', 'last_updated',
'pk', 'id', 'name', 'device', 'label', 'status', 'description', 'installed_device', 'installed_role',
'installed_device_type', 'installed_description', 'installed_serial', 'installed_asset_tag', 'tags',
'created', 'last_updated',
)
default_columns = ('pk', 'name', 'device', 'label', 'enabled', 'status', 'installed_device', 'description')
default_columns = ('pk', 'name', 'device', 'label', 'status', 'installed_device', 'description')
class DeviceDeviceBayTable(DeviceBayTable):
@@ -943,9 +960,6 @@ class DeviceDeviceBayTable(DeviceBayTable):
'"></i> <a href="{{ record.get_absolute_url }}">{{ value }}</a>',
attrs={'td': {'class': 'text-nowrap'}}
)
enabled = columns.BooleanColumn(
verbose_name=_('Enabled'),
)
actions = columns.ActionsColumn(
extra_buttons=DEVICEBAY_BUTTONS
)
@@ -953,9 +967,9 @@ class DeviceDeviceBayTable(DeviceBayTable):
class Meta(DeviceComponentTable.Meta):
model = models.DeviceBay
fields = (
'pk', 'id', 'name', 'label', 'enabled', 'status', 'installed_device', 'description', 'tags', 'actions',
'pk', 'id', 'name', 'label', 'status', 'installed_device', 'description', 'tags', 'actions',
)
default_columns = ('pk', 'name', 'label', 'enabled', 'status', 'installed_device', 'description')
default_columns = ('pk', 'name', 'label', 'status', 'installed_device', 'description')
class ModuleBayTable(ModularDeviceComponentTable):
@@ -966,9 +980,6 @@ class ModuleBayTable(ModularDeviceComponentTable):
'args': [Accessor('device_id')],
}
)
enabled = columns.BooleanColumn(
verbose_name=_('Enabled'),
)
parent = tables.Column(
linkify=True,
verbose_name=_('Parent'),
@@ -997,11 +1008,11 @@ class ModuleBayTable(ModularDeviceComponentTable):
class Meta(ModularDeviceComponentTable.Meta):
model = models.ModuleBay
fields = (
'pk', 'id', 'name', 'device', 'enabled', 'parent', 'label', 'position', 'installed_module', 'module_status',
'pk', 'id', 'name', 'device', 'parent', 'label', 'position', 'installed_module', 'module_status',
'module_serial', 'module_asset_tag', 'description', 'tags',
)
default_columns = (
'pk', 'name', 'device', 'enabled', 'parent', 'label', 'installed_module', 'module_status', 'description',
'pk', 'name', 'device', 'parent', 'label', 'installed_module', 'module_status', 'description',
)
def render_parent_bay(self, value):
@@ -1016,9 +1027,6 @@ class DeviceModuleBayTable(ModuleBayTable):
verbose_name=_('Name'),
linkify=True,
)
enabled = columns.BooleanColumn(
verbose_name=_('Enabled'),
)
actions = columns.ActionsColumn(
extra_buttons=MODULEBAY_BUTTONS
)
@@ -1026,10 +1034,10 @@ class DeviceModuleBayTable(ModuleBayTable):
class Meta(ModuleBayTable.Meta):
model = models.ModuleBay
fields = (
'pk', 'id', 'parent', 'name', 'label', 'enabled', 'position', 'installed_module', 'module_status',
'module_serial', 'module_asset_tag', 'description', 'tags', 'actions',
'pk', 'id', 'parent', 'name', 'label', 'position', 'installed_module', 'module_status', 'module_serial',
'module_asset_tag', 'description', 'tags', 'actions',
)
default_columns = ('pk', 'name', 'label', 'enabled', 'installed_module', 'module_status', 'description')
default_columns = ('pk', 'name', 'label', 'installed_module', 'module_status', 'description')
class InventoryItemTable(DeviceComponentTable):
@@ -1161,7 +1169,7 @@ class VirtualDeviceContextTable(TenancyColumnsMixin, PrimaryModelTable):
)
device = tables.Column(
verbose_name=_('Device'),
order_by=('device___name',),
order_by=('device__name',),
linkify=True
)
status = columns.ChoiceFieldColumn(

View File

@@ -289,30 +289,24 @@ class RearPortTemplateTable(ComponentTemplateTable):
class ModuleBayTemplateTable(ComponentTemplateTable):
enabled = columns.BooleanColumn(
verbose_name=_('Enabled'),
)
actions = columns.ActionsColumn(
actions=('edit', 'delete')
)
class Meta(ComponentTemplateTable.Meta):
model = models.ModuleBayTemplate
fields = ('pk', 'name', 'label', 'position', 'enabled', 'description', 'actions')
fields = ('pk', 'name', 'label', 'position', 'description', 'actions')
empty_text = "None"
class DeviceBayTemplateTable(ComponentTemplateTable):
enabled = columns.BooleanColumn(
verbose_name=_('Enabled'),
)
actions = columns.ActionsColumn(
actions=('edit', 'delete')
)
class Meta(ComponentTemplateTable.Meta):
model = models.DeviceBayTemplate
fields = ('pk', 'name', 'label', 'enabled', 'description', 'actions')
fields = ('pk', 'name', 'label', 'description', 'actions')
empty_text = "None"

View File

@@ -56,7 +56,9 @@ class ModuleTypeTable(PrimaryModelTable):
template_code=WEIGHT,
order_by=('_abs_weight', 'weight_unit')
)
attributes = columns.DictColumn()
attributes = columns.DictColumn(
orderable=False,
)
module_count = columns.LinkedCountColumn(
viewname='dcim:module_list',
url_params={'module_type_id': 'pk'},

View File

@@ -2,14 +2,13 @@ import django_tables2 as tables
from django.utils.translation import gettext_lazy as _
from django_tables2.utils import Accessor
from dcim.models import Rack, RackGroup, RackReservation, RackRole, RackType
from dcim.models import Rack, RackReservation, RackRole, RackType
from netbox.tables import OrganizationalModelTable, PrimaryModelTable, columns
from tenancy.tables import ContactsColumnMixin, TenancyColumnsMixin
from .template_code import OUTER_UNIT, WEIGHT
__all__ = (
'RackGroupTable',
'RackReservationTable',
'RackRoleTable',
'RackTable',
@@ -17,29 +16,6 @@ __all__ = (
)
class RackGroupTable(OrganizationalModelTable):
name = tables.Column(
verbose_name=_('Name'),
linkify=True,
)
rack_count = columns.LinkedCountColumn(
viewname='dcim:rack_list',
url_params={'group_id': 'pk'},
verbose_name=_('Racks'),
)
tags = columns.TagColumn(
url_name='dcim:rackgroup_list',
)
class Meta(OrganizationalModelTable.Meta):
model = RackGroup
fields = (
'pk', 'id', 'name', 'rack_count', 'description', 'slug', 'comments', 'tags', 'actions', 'created',
'last_updated',
)
default_columns = ('pk', 'name', 'rack_count', 'description')
class RackRoleTable(OrganizationalModelTable):
name = tables.Column(
verbose_name=_('Name'),
@@ -135,10 +111,6 @@ class RackTable(TenancyColumnsMixin, ContactsColumnMixin, PrimaryModelTable):
verbose_name=_('Site'),
linkify=True
)
group = tables.Column(
verbose_name=_('Group'),
linkify=True,
)
status = columns.ChoiceFieldColumn(
verbose_name=_('Status'),
)
@@ -200,15 +172,15 @@ class RackTable(TenancyColumnsMixin, ContactsColumnMixin, PrimaryModelTable):
class Meta(PrimaryModelTable.Meta):
model = Rack
fields = (
'pk', 'id', 'name', 'site', 'location', 'group', 'status', 'facility_id', 'tenant', 'tenant_group', 'role',
'pk', 'id', 'name', 'site', 'location', 'status', 'facility_id', 'tenant', 'tenant_group', 'role',
'rack_type', 'serial', 'asset_tag', 'form_factor', 'u_height', 'starting_unit', 'width', 'outer_width',
'outer_height', 'outer_depth', 'mounting_depth', 'airflow', 'weight', 'max_weight', 'comments',
'device_count', 'get_utilization', 'get_power_utilization', 'description', 'contacts',
'tags', 'created', 'last_updated',
)
default_columns = (
'pk', 'name', 'site', 'location', 'group', 'status', 'facility_id', 'tenant', 'role', 'rack_type',
'u_height', 'device_count', 'get_utilization',
'pk', 'name', 'site', 'location', 'status', 'facility_id', 'tenant', 'role', 'rack_type', 'u_height',
'device_count', 'get_utilization',
)
@@ -228,11 +200,6 @@ class RackReservationTable(TenancyColumnsMixin, PrimaryModelTable):
accessor=Accessor('rack__location'),
linkify=True
)
group = tables.Column(
verbose_name=_('Group'),
accessor=Accessor('rack__group'),
linkify=True
)
rack = tables.Column(
verbose_name=_('Rack'),
linkify=True
@@ -241,9 +208,6 @@ class RackReservationTable(TenancyColumnsMixin, PrimaryModelTable):
orderable=False,
verbose_name=_('Units')
)
unit_count = tables.Column(
verbose_name=_("Total U's")
)
status = columns.ChoiceFieldColumn(
verbose_name=_('Status'),
)
@@ -254,9 +218,7 @@ class RackReservationTable(TenancyColumnsMixin, PrimaryModelTable):
class Meta(PrimaryModelTable.Meta):
model = RackReservation
fields = (
'pk', 'id', 'reservation', 'site', 'location', 'group', 'rack', 'unit_list', 'unit_count', 'status',
'user', 'tenant', 'tenant_group', 'description', 'comments', 'tags', 'actions', 'created', 'last_updated',
)
default_columns = (
'pk', 'reservation', 'site', 'rack', 'unit_list', 'unit_count', 'status', 'user', 'description',
'pk', 'id', 'reservation', 'site', 'location', 'rack', 'unit_list', 'status', 'user', 'tenant',
'tenant_group', 'description', 'comments', 'tags', 'actions', 'created', 'last_updated',
)
default_columns = ('pk', 'reservation', 'site', 'rack', 'unit_list', 'status', 'user', 'description')

Some files were not shown because too many files have changed in this diff Show More