Compare commits

...

295 Commits

Author SHA1 Message Date
Jeremy Stretch
d2e74e9d50 Release v4.2.8 2025-04-22 15:44:02 -04:00
bctiemann
02571130b2 Merge pull request #19259 from netbox-community/18961-vc-create-ignore-vc-members
Fixes #18961: Virtual chassis form should exclude members of other VCs when adding members
2025-04-22 14:36:12 -04:00
Jeremy Stretch
46a3ce2559 Fixes #19268: Restore editing conflict protection for several object forms (#19271) 2025-04-22 11:07:03 -07:00
Jeremy Stretch
1850c21714 Fixes #19265: Strip linebreaks from URLs for logging 2025-04-22 12:48:57 -04:00
Jeremy Stretch
13ddd5fd20 Fixes #19230: Allow label reuse when creating multiple components from a pattern (#19261) 2025-04-22 08:55:31 -07:00
Jeremy Stretch
60cdf89cad Fixes #19166: Fix bulk import support for base_choices (#19257) 2025-04-22 08:29:00 -07:00
Jeremy Stretch
77bfc40579 Closes #17136: Add read-only database support to the upgrade script (#19247) 2025-04-22 07:42:54 -07:00
Jeremy Stretch
2f8936d493 Fixes #18961: Virtual chassis form should exclude members of other VCs when adding members 2025-04-22 10:24:43 -04:00
bctiemann
e0b6a31504 Merge pull request #19256 from netbox-community/18959-cable-trace-terminations-ordering
Fixes #18959: Preserve ordering of terminations in cable traces
2025-04-22 10:08:13 -04:00
Jeremy Stretch
8567aa96e4 Remove obsolete comment 2025-04-22 09:42:17 -04:00
Jeremy Stretch
459c4bfd9d Fixes #18959: Preserve ordering of terminations in cable traces 2025-04-22 09:21:14 -04:00
Jeremy Stretch
918470a2bb Closes #19208: Ignore beta releases when fetching latest release tag 2025-04-22 08:18:23 -04:00
Arthur
c73cc0a36a 18500 fix check for cloning mixin 2025-04-22 08:14:32 -04:00
Renato Almeida de Oliveira Zaroubin
6b9b66aecb make INTERFACE_FHRPGROUPS use FHRPGROUPS _str_ representation 2025-04-22 08:06:24 -04:00
github-actions
b6d10ae6d8 Update source translation strings 2025-04-22 05:02:08 +00:00
Renato Almeida de Oliveira
7420c25687 Fixes: #18881 Site Groups are missing VLAN and VM related objects (#18932) 2025-04-21 09:11:01 -07:00
github-actions
248c94bd35 Update source translation strings 2025-04-16 05:02:15 +00:00
bctiemann
96cf8d14dc Merge pull request #19194 from netbox-community/17908-cable-trace-buttons
Closes #17908: Add trace buttons to terminations under cable view
2025-04-15 18:13:59 -04:00
bctiemann
2356a3c125 Merge pull request #19162 from alehaa/19040-copy-rendered-config
Fixes #19040: Add button to copy rendered config to clipboard
2025-04-15 18:00:47 -04:00
bctiemann
0d81007fdf Merge pull request #19178 from netbox-community/19139-tx-force-pull
Closes #19139: Use --force when invoking tx pull
2025-04-15 17:59:58 -04:00
atownson
c108c738ae Fixes #18669 - Populate custom field default values (#19115) 2025-04-15 13:26:03 -07:00
Martin Hauser
cac41cd093 Fixes #19196: Add Filtering by VLAN Translation Policy to Interface Filter Forms (#19199)
* feat(dcim): Add VLAN Translation Policy to Filter Form

Introduces support for VLAN Translation Policies in the Interface
Filter Form.

* feat(virtualization): Add VLAN Translation Policy to Filter Form

Introduces support for VLAN Translation Policies in the Interface
Filter Form.
2025-04-15 16:24:45 -04:00
Jeremy Stretch
27b26ec49c Fixes #19195: Language cookie should respect SESSION_COOKIE_SECURE value (#19197) 2025-04-15 13:03:33 -07:00
Jeremy Stretch
7c2776d721 Closes #19201: Include TS source with sourcemap (#19202) 2025-04-15 14:42:40 -05:00
Martin Hauser
1f93471659 Fixes #18978 - Allow filtering of Interfaces in the GUI by 802.1Q Mode (#19183)
* feat(dcim): Add VLAN mode filter to CommonInterface

Introduces a new FilterSet for VLAN mode in CommonInterfaceFilterSet.
This allows filtering interfaces based on their VLAN mode using defined
choices.

* feat(dcim): Add VLAN mode filter to Interface FilterForm

Add a field to InterfaceFilterSet to filter interfaces by 802.1Q VLAN
mode.

* feat(virtualization): Add VLAN mode filter to VMInterface

Add a field to VMInterfaceFilterSet to filter interfaces by 802.1Q VLAN
mode.

* fix(dcim): Correct mode filter parameter type in tests

Updates the `mode` filter parameter to accept a list instead of a single
value in `test_filtersets.py`. Ensures proper count assertion for
accurate test behavior.

* feat(virtualization): Add tests for VLAN mode filtering

Introduces tests to validate filtering by `mode` for VMInterface.
Ensures correct filtering for 802.1Q VLAN mode.

* refactor(virtualization): Reorganize FieldSets in FilterSets

Splits the 'Attributes' FieldSet into two distinct FieldSets for better
clarity: 'Attributes' and 'Addressing'. This improves form organization
and makes it more intuitive for users.
2025-04-15 13:47:51 -04:00
Jeremy Stretch
d3768feb31 Closes #17908: Add trace buttons to terminations under cable view 2025-04-15 11:41:00 -04:00
Jeremy Stretch
70cc7c7563 Fixes #19169: Remove horizontal padding from highlighted text (#19181) 2025-04-15 07:13:58 -07:00
Jeremy Stretch
8b091fb219 Fixes #19189: BaseScript.load_yaml() should use SafeLoader (#19190) 2025-04-15 08:58:13 -05:00
Martin Hauser
44cb1a9139 Fixes #19056 – Add Device filtering by Location slug (#19180)
* feat(dcim): Add filter by location slug for Device

Introduces a TreeNodeMultipleChoiceFilter for filtering locations by
slug. Enhances filtering flexibility in the Device model by supporting
both ID and slug lookups.

Fixes #19056

* feat(dcim): Add Device filtering by location slug in tests

Extend test cases to include filtering by location slug. Ensures the
FilterSet works correctly with slug-based queries for locations.

Fixes #19056
2025-04-15 08:22:59 -04:00
Martin Hauser
bb9b0b8f8a Fixes #18879 - Add prefix filtering by assigned VLAN Group (#19182)
* feat(ipam): Add VLAN group filters to IPAM FilterSet

Introduces filters for VLAN groups using both ID and slug fields.

* feat(ipam): Add VLAN group filter in IPAM FilterForm

Introduces a `vlan_group_id` filter to IPAM forms for filtering based on
VLAN groups.

* feat(ipam): Add VLAN group filtering to tests

Introduces tests for VLAN group filtering in FilterSets. This ensures
correct validation and behavior when filtering by VLAN group.
2025-04-15 07:59:32 -04:00
github-actions
785ad505ba Update source translation strings 2025-04-15 05:02:10 +00:00
Jeremy Stretch
8aacef60a3 Closes #19175: Remove outdated NetBox installation video (#19177) 2025-04-14 15:14:59 -05:00
Jeremy Stretch
d8fc052bbe Closes #19139: Use --force when invoking tx pull 2025-04-14 15:55:08 -04:00
Renato Almeida de Oliveira Zaroubin
1f79411878 Add GetRelatedModelsMixin to ClusterView 2025-04-14 15:39:49 -04:00
bctiemann
94d19e8f15 Remove #18095 from v4.2.5 release notes (#19165) 2025-04-14 07:26:37 -07:00
Alexander Haase
f337ef1134 Add button to copy rendered config 2025-04-13 18:02:21 +02:00
Jeremy Stretch
6ed41f6680 Fixes #18955: Include the "clear" button only for non-required dropdown fields (#18971)
* Include the 'clear' button only for non-required fields

* Apply the 'required' attribute for mandatory <select> fields

* Recompile static assets
2025-04-11 08:20:24 -04:00
github-actions
28e62d21a9 Update source translation strings 2025-04-11 05:02:06 +00:00
Jeremy Stretch
03f3f5c957 Release v4.2.7 2025-04-10 16:07:24 -04:00
Jeremy Stretch
fe7fb94e44 Revert "Fixes: #18783 Add a tag_id filter for all models which support taggin…"
This reverts commit 9a1d9365cd.
2025-04-10 15:42:26 -04:00
github-actions
82b9e4ca26 Update source translation strings 2025-04-10 05:02:11 +00:00
Jeremy Stretch
457fb977a7 Fixes #19122: Fix styling of the server error (500) page (#19126) 2025-04-09 14:57:25 -07:00
Jeremy Stretch
13c20957a6 Closes #18652: Run housekeeping GitHub actions only on the main repository (#19125) 2025-04-09 16:28:00 -05:00
Jason Novinger
30208549ba Fixes #19092: scope type selection lost when editing multiple/all objects (#19102) 2025-04-09 14:55:41 -04:00
atownson
bf286df670 Fixes #19030 - Update z-index of floating buttons (#19118)
* Increase z-index of form floating buttons

* Update netbox.css
2025-04-08 16:02:08 -05:00
Jeremy Stretch
2be257db48 Closes #19112: Configure ruff to target Python 3.10 (#19113) 2025-04-08 09:46:31 -05:00
bctiemann
2207ea1a32 Merge pull request #19046 from pheus/docs/18733-add-version-requirements-matrix
Fixes #18733: Add Dependency Version Matrix for NetBox Versions to the Upgrade Documentation
2025-04-07 14:01:54 -04:00
Martin Hauser
10e1ae8292 docs(release): Update Dependency Requirements Matrix header
Renames the "Adopt the Dependency Requirements Matrix" section to
"Update the Dependency Requirements Matrix" for clarity.
2025-04-07 17:17:26 +02:00
Martin Hauser
f8f5ab8d61 docs(release): Correct formatting in release checklist 2025-04-07 16:55:23 +02:00
github-actions
92317248a3 Update source translation strings 2025-04-05 05:02:12 +00:00
Jeremy Stretch
426e6439e3 Fixes #18553: Update site for VMs only if cluster has a site assigned (#19086) 2025-04-04 10:58:06 -07:00
Jeremy Stretch
621b29cd71 Closes #19035: Move the registration of core event types to the app config (#19088) 2025-04-04 11:18:42 -05:00
github-actions
8f5d273f08 Update source translation strings 2025-04-03 05:02:01 +00:00
Martin Hauser
45779a24a4 docs(release): Update checklist with dependency requirements
Add steps to update the dependency requirements matrix for each minor
release in the release checklist. Clarify how to document changes for
system requirements and linked installation guides.

Fixes #18733
2025-04-02 21:41:36 +02:00
Martin Hauser
f17bbe610e Fixes #19041: Call super().clean() in FrontPortCreateForm (#19051)
* fix(forms): Call super().clean() in clean methods

Adds a call to super().clean() in the clean methods of object creation
forms. This ensures base class validation logic is executed properly
before custom logic is applied.

Fixes #19041

* test(forms): Add tests for front port form validation

Introduces unit tests for validating FrontPortCreateForm behavior.
Tests include scenarios for matching and mismatched name-label pairs
to ensure proper form validation logic.

Fixes #19041

* Omit errant print statement

---------

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>
2025-04-02 08:29:21 -04:00
bctiemann
bad820001d Merge pull request #19015 from netbox-community/18738-script-list-ignoring-script-order
Fixes #18738: Ensure ScriptList respects script_order option
2025-04-01 10:09:39 -04:00
Martin Hauser
a5106b858d docs(upgrading): Add dependency matrix for NetBox versions
Adds a dependency matrix to the upgrade guide, detailing supported
Python, PostgreSQL, and Redis versions for each NetBox release. This
helps users verify compatibility before upgrading.

Fixes #18733
2025-04-01 07:23:42 +02:00
github-actions
bbd5e9cab9 Update source translation strings 2025-04-01 05:02:06 +00:00
bctiemann
12231ad71a Merge pull request #18997 from antoinekh/18964_fix_bulk_edit_all
Fixes #18964 Select all with bulk edit only changes the currently visible objects
2025-03-31 18:36:04 -04:00
Jeremy Stretch
88ef9ecfa3 Fixes #19023: get_field_value() should respect null values in bound forms (#19024) 2025-03-31 16:34:46 -05:00
github-actions
6f78b3d0cd Update source translation strings 2025-03-29 05:02:03 +00:00
Jason Novinger
d3f42deb32 Fixes #18895: Allows VirtualCircuitTerminations as Interface connected_endpoints (#19027) 2025-03-28 08:58:09 -07:00
Jason Novinger
db4fb8f406 Fixes #18999: Allow GraphQL to represent inventory items with no set manufacturar (#19016) 2025-03-28 07:57:56 -07:00
ZPrimed
5b8eaced1a Update choices.py - add MoCA (Coaxial) 2025-03-28 08:45:04 -04:00
github-actions
ada0c7f687 Update source translation strings 2025-03-28 05:02:14 +00:00
Jeremy Stretch
b750d0dff2 Fixes #19021: Ensure consistent styling for JSON form fields (#19022) 2025-03-27 08:58:37 -05:00
Jason Novinger
e1e514251e Fixes #18965: Ensure script list run buttons respect scripts' commit_default option (#19013)
* Fixes #18965: Script list run buttons respect scripts' commit_default

* Cleanup script .Meta access in template
2025-03-27 08:39:50 -04:00
Renato Almeida de Oliveira
7d80a45bf8 Fixes: #16144 GetReturnURLMixin Support for Plugin Views (#18996)
* Add plugin support to GetReturnURLMixin

* use get_viewname instead of resolving the name
2025-03-27 08:33:09 -04:00
github-actions
09854a3d54 Update source translation strings 2025-03-27 05:02:15 +00:00
Jason Novinger
39a96ddf3a Fixes #18738: Ensure ScriptList respects script_order option 2025-03-26 15:35:06 -05:00
atownson
be26f86b62 Added advanced object selector to custom field object and multi-object inputs (#18830) 2025-03-26 10:42:45 -07:00
Jason Novinger
fd2bcda8b8 Fixes #18991: AttributeError: NoneType object has not attribute model (#19006) 2025-03-26 10:12:45 -07:00
github-actions
817d7efee3 Update source translation strings 2025-03-26 05:03:20 +00:00
Renato Almeida de Oliveira
9a1d9365cd Fixes: #18783 Add a tag_id filter for all models which support tagging (#18889) 2025-03-25 08:06:22 -07:00
Antoine Keranflec'h
ada4a4b93c fix #18964 reinsert else condition 2025-03-25 08:22:59 +00:00
github-actions
64a98fd87f Update source translation strings 2025-03-25 05:02:04 +00:00
Arthur Hanson
bd8e00a935 18904 add tags to config context table (#18938)
* 18904 add tags to config context table

* 18904 tag to correct table
2025-03-24 17:02:36 -04:00
Jeremy Stretch
af5a600583 Closes #18980: Optimize update of object data when adding/removing custom fields (#18983)
* Employ native PostgreSQL functions for updating object JSON data when adding/removing custom fields

* Optimize rename_object_data()

* remove_stale_data() should validate model class
2025-03-24 12:02:54 -05:00
github-actions
8ab73501d1 Update source translation strings 2025-03-22 05:02:10 +00:00
Renato Almeida de Oliveira
447e108d97 Fixes: #18656 Unable to import IP Address and assign to FHRP Group (#18950)
* Add fhrpgroup to IPAddressImportForm

* Change fhrpgroup accessor to name

* rename fhrpgroup to fhrp_group

* Add fhrp_group to  IPAddressTestCase csv_data
2025-03-21 16:44:10 -05:00
bctiemann
e186113cb3 Merge pull request #18986 from netbox-community/release-v4.2.6
Release v4.2.6
2025-03-21 17:17:50 -04:00
Jason Novinger
40452ead62 Cleanup release notes 2025-03-21 16:03:34 -05:00
Jason Novinger
34d80beaa2 Release v4.2.6 2025-03-21 15:49:20 -05:00
Yi
b1d014b520 Fixes #18949: Add missing GraphQL ContactsMixin in types with ContactAssignments 2025-03-21 13:00:50 -05:00
github-actions
7db0765ed2 Update source translation strings 2025-03-21 05:02:02 +00:00
Jason Novinger
b8cc2d7116 Fixes #18887: Allows VMInterface object custom field on Prefix (#18945) 2025-03-20 13:55:12 -07:00
Renato Almeida de Oliveira
d332a0c0d7 Fix sitegroup typo, VLANGroupFilterForm field didn't match between form and filterset (#18947) 2025-03-20 11:30:39 -05:00
Jason Novinger
f07e2dd4e2 Fixes #18944: Clearing widget type field no longer causes 500 error (#18946)
* Fixes #18944: Clearing widget type field no longer causes 500 error

* Address PR feedback, cleanup implementation
2025-03-20 09:12:05 -04:00
Renato Almeida de Oliveira
d7b9b09d56 Fixes: #18939 Allow ASN search by site-group (#18948)
* Add site_group and site_group_id to ASNFilterSet and ASNFilterForm

* Implement ASNTestCase site_group test case
2025-03-20 09:07:48 -04:00
github-actions
9da4cf31ab Update source translation strings 2025-03-20 05:02:02 +00:00
Renato Almeida de Oliveira
bf1a9a6e2d Fixes: #18833 Inventory Item Bulk Import - 'InventoryItemImportForm' has no field named 'component_id'. (#18874)
* Refactor InventoryItemImportForm clean method

* Add super().clean(); renamed content_type; simplified component creation

* Fix missing component_name issue

* Update netbox/dcim/forms/bulk_import.py

---------

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>
2025-03-19 09:56:42 -04:00
bctiemann
c50b1c989d Merge pull request #18929 from netbox-community/18928-housekeeping-changelog-cleanup
Fixes #18928: Fix support for cascading deletions when cleaning up expired changelog records
2025-03-19 09:51:11 -04:00
bctiemann
79b0c0f5d6 Merge pull request #18901 from netbox-community/18872-JournalEntry-kind-required
Fixes #18872: JournalEntry `kind` is a required field
2025-03-19 09:40:55 -04:00
github-actions
43840e6a72 Update source translation strings 2025-03-19 05:02:13 +00:00
bctiemann
7c152e9234 Merge pull request #18854 from netbox-community/18782-dashboard-broken-on-notification-list-widget
Fixes #18782: Misconfigured `ObjectListWidget`s now degrade gracefully
2025-03-18 14:45:23 -04:00
Jason Novinger
d7709a2a55 Fixes #18926: Uses correct icon for base GitHub auth 2025-03-18 08:48:27 -04:00
github-actions
dce694afa9 Update source translation strings 2025-03-18 05:02:07 +00:00
Jeremy Stretch
c5801f9881 Fixes #18928: Fix support for cascading deletions when cleaning up expired changelog records 2025-03-17 14:16:55 -04:00
Jeremy Stretch
f86647dc28 Fixes #18884: Handle tag assignments manually within deserialize_object (#18908) 2025-03-17 08:43:08 -07:00
Benjamin Dale
0094703609 Closes #18816:Add FC/UPC, FC/APC and FC/PC port types (#18913)
* Closes #18816:Add FC/UPC, FC/APC and FC/PC port types

* Remove release note

---------

Co-authored-by: Ben Dale <7621213-ben_dale@users.noreply.gitlab.com>
Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>
2025-03-17 10:39:28 -04:00
github-actions
f286449284 Update source translation strings 2025-03-14 05:02:07 +00:00
bctiemann
4f45328c77 Fixes: #18863 - Exempt MPTT-based models from centrally applying ordering on querysets (#18867) 2025-03-13 13:38:33 -07:00
Jeremy Stretch
994e7eb9f4 Fixes #18872: JournalEntry kind is a required field 2025-03-13 16:23:53 -04:00
Jeremy Stretch
ed135102be Fixes #18880: Delay enqueuing of background tasks until the DB transaction has been committed (#18899) 2025-03-13 11:34:12 -05:00
Jason Novinger
78332d44c7 Fixes #18845: restores sort behavior for DeviceTable.name column (#18861)
* Fixes #18845: restores sort behavior for DeviceTable.name column

* Remove accessor/order_by and modify DEVICE_LINK template

Thanks to @alehaa for the suggestion.

This also includes an additional `.select_related()` operation on
`DeviceListView.queryset` to avoid extra queries. Thanks to
@renatoalmeidaoliveira and @jeremystretch for pointing out the need for
this.
2025-03-13 09:22:49 -04:00
github-actions
80926cda8f Update source translation strings 2025-03-13 05:02:07 +00:00
bctiemann
d924d4eb33 Merge pull request #18886 from ITJamie/add-rackname-to-device-rack-view
Add rack title above rack view on device page
2025-03-12 19:11:22 -04:00
bctiemann
b1e7d7c76b Merge pull request #18826 from Tishka17/fix/generic_prefetch_4.2
Prefetch interface data for REST API on netbox 4.2
2025-03-12 18:55:58 -04:00
Jeremy Stretch
092f7549ca Fixes #18869: Ensure to_meters() always returns a clean decimal value (#18883)
* Fixes #18869: Ensure to_meters() always returns a clean decimal value

* Handle float values
2025-03-12 13:42:38 -05:00
Andrey Tikhonov
2f51dfc07a Merge branch 'fix/generic_prefetch_4.2' of github.com:Tishka17/netbox into fix/generic_prefetch_4.2 2025-03-12 19:13:34 +01:00
Andrey Tikhonov
906654d807 Fix empty line, comments 2025-03-12 19:09:46 +01:00
Renato Almeida de Oliveira
749a83d742 Change JSONField, prepare_value to output str with enclosing " (#18846) 2025-03-12 10:00:40 -07:00
Andrey Tikhonov
cdd25368e7 Merge branch 'main' into fix/generic_prefetch_4.2 2025-03-12 16:27:12 +01:00
Andrey Tikhonov
7d64d3b5ed Move GenericArrayForeignKey to fields module 2025-03-12 16:22:11 +01:00
github-actions
5e22ef59c5 Update source translation strings 2025-03-12 05:02:02 +00:00
Fabi
19d1282683 Fixes #18838: Correctly reject invalid falsy local context data (#18860)
* Correctly reject invalid falsy local context data.

* move tests
2025-03-11 14:18:42 -05:00
bctiemann
2266a8af67 Merge pull request #18804 from renatoalmeidaoliveira/18742-Location-List-and-Locations-not-Showing-Associated-VLAN-Groups
Fixes: #18742 Location List and Locations not Showing Associated VLAN Groups
2025-03-11 11:13:24 -04:00
Renato Almeida de Oliveira
5d81f911d6 Fixes: #18582 Bulk import prefixes with associated VLAN not working when multiple VLANs with the same vid exist. (#18844)
* Add site CSVModelChoiceField

* Change site field to vlan_site
2025-03-11 08:46:46 -04:00
github-actions
89e3f3d3e9 Update source translation strings 2025-03-11 05:02:10 +00:00
Jeremy Stretch
292463c0de Closes #18857: Fix deprecation warnings (#18858) 2025-03-10 14:40:08 -07:00
Antoine Keranflec'h
a9fd191086 Fixes: #18744 Add Contact link as hyperlink (#18847)
* contact link as hyperlink

* fix(lint) add missing blank lines

* simplify by using lambda function
2025-03-10 12:49:24 -05:00
Tobias Genannt
1a60cb9884 Fixes: #18568 Update mkdocstrings and adapt config (#18841)
* Fixes: #18568 Update mkdocstrings and adapt config

* Fixed some output formatting errors

When trying to compare the output from "mkdocstrings[python-legacy]==0.27.0" and
"mkdocstrings[python]==0.28.2" I encountered some HTML errors:
- <div> inside a <p>
- unescaped non-tags <pk>
2025-03-10 13:11:35 -04:00
Jason Novinger
76c3c613a9 Adds validation for ObjectListWidget.ConfigForm.model field 2025-03-10 09:57:45 -05:00
Jason Novinger
528248b560 Fixes #18782: properly check if htmx_url is None
If this is done incorrently, then the string formatting operation turns
`htmx_url` into a string and the test in the template fails.
2025-03-10 09:52:59 -05:00
github-actions
8823b07745 Update source translation strings 2025-03-08 05:02:21 +00:00
Mika Busch
29c25e39fc 17686 config option for disk divider (#18011) 2025-03-07 10:47:27 -08:00
Andrey Tikhonov
d103e13732 Removed automatic cache invalidation 2025-03-07 17:29:04 +01:00
github-actions
6d69c76b83 Update source translation strings 2025-03-07 05:02:48 +00:00
bctiemann
f9c8d12a51 Add docstrings for get_queryset base class methods (#18832) 2025-03-06 11:11:55 -06:00
Renato Almeida de Oliveira
3ef7ab4416 Fixes: #18579 Add contact filters to services (#18818)
* Add Contact filter to Services

* Add ContactModelFilterForm to ProviderAccountFilterForm

* Add Contact filter support for Aggregate

* Add Contact filter support for Prefix

* Add Contact filter to IPRange

* Add Contact filter to IPAddress

* Add Contact filter to L2VPN

* Add Contact filter to TunnelGroup

* Add Contact filter to Tunnel

* Add ContactModelFilterSet to ProviderAccountFilterSet

* Fixes classes inheritance order

Setup NetBoxModelFilterSetForm as the last inherited class

Co-authored-by: Jason Novinger <jnovinger@gmail.com>

---------

Co-authored-by: Jason Novinger <jnovinger@gmail.com>
2025-03-06 09:41:41 -06:00
bctiemann
2d35cc56ed Merge pull request #18823 from netbox-community/release-v4.2.5
Release v4.2.5
2025-03-06 10:10:13 -05:00
Andrey Tikhonov
741645c9f7 Merge branch 'develop' into fix/generic_prefetch_4.2 2025-03-06 16:05:25 +01:00
Andrey Tikhonov
d226af420b Merge branch 'develop' into fix/generic_prefetch_4.2 2025-03-06 16:02:32 +01:00
Andrey Tikhonov
5c88317745 cleanup unused imports and extra line 2025-03-06 16:01:59 +01:00
Jeremy Stretch
dffa380e5c Tweak issue ordering 2025-03-06 09:50:32 -05:00
Brian Tiemann
6d2426843b Merge remote-tracking branch 'origin/release-v4.2.5' into release-v4.2.5 2025-03-06 09:28:08 -05:00
Brian Tiemann
e72b0606ba Bump Django and add missing PRs 2025-03-06 09:27:44 -05:00
Jeremy Stretch
c933cbf11e Update translations 2025-03-06 09:00:09 -05:00
github-actions
9f1ffb54f5 Update source translation strings 2025-03-06 05:02:11 +00:00
Brian Tiemann
29b8827128 Add translation files 2025-03-05 18:52:34 -05:00
bctiemann
6efc5682cd Override get_queryset on generic ObjectListView and NetBoxModelViewSet to reapply model-level ordering (#18805) 2025-03-05 15:52:00 -08:00
Brian Tiemann
033a960cab Fix strawberry-graphql==0.262.0 2025-03-05 18:46:30 -05:00
Brian Tiemann
9f69c46a99 NetBox v4.2.5 2025-03-05 18:43:41 -05:00
Marcus Weiner
631ff3e702 Allow primary key for nested models in OpenAPI request schemas (#18451) 2025-03-05 11:46:12 -08:00
Renato Almeida de Oliveira Zaroubin
ed6ccfb723 Add commit test in job execution 2025-03-05 09:34:18 -05:00
Renato Almeida de Oliveira Zaroubin
d3a9a6827f fix typo in VirtualCircuitFilterForm 2025-03-05 09:28:00 -05:00
github-actions
057653d362 Update source translation strings 2025-03-05 05:02:11 +00:00
Daniel Sheppard
4ab58f2da9 Fixes: #15016 - Catch AssertionError from cable trace and throw ValidationError (#16384) 2025-03-04 10:57:27 -08:00
Renato Almeida de Oliveira Zaroubin
d83c2f45bc Add vlangroup into LocationTable, LocationListView queryset and related_models in LocationView 2025-03-04 18:34:23 +00:00
github-actions
d208ddde9a Update source translation strings 2025-03-04 05:02:19 +00:00
bctiemann
0fbfc4f38c Merge pull request #18789 from jamestiotio/18774-tag-description
Closes #18774: Set title attribute of each tag to its description
2025-03-03 11:35:33 -05:00
Jason Novinger
e86dba8fc8 Fixes #18768: allow removing secondary MACAddress from interface 2025-03-03 09:35:00 -05:00
atownson
3e1d4369ba Closes #17944: Allow filtering of ObjectVar and MultiObjectVar script inputs (#18725)
* Add the advanced object selector to the ObjectVar and MultiObjectVar script inputs

* Fix formatting issue
2025-03-03 09:20:04 -05:00
James Raphael Tiovalen
06b5ff2e4a Closes #18774: Set title attribute of each tag to its description 2025-03-02 18:40:40 +08:00
github-actions
3b1daaaad6 Update source translation strings 2025-03-01 05:02:06 +00:00
Jeremy Stretch
63a167f130 Fixes #15924: Fix API interface patch tagged all mode (#18759)
* Fixes: #15924 - Prevent API payload from allowing tagged_vlans while interface mode is set to taged-all

* Prevent cleanup of tagged_vlans when no tagged_vlans set on interface

* Fix test errors

* Remove accidental debug statements

* Update validation to model clean method instead of serializer

* Remove clearing of tagged vlans from `save()`

* Make changes to validation to account for M2M not being available under model in addition to not being able to check incoming vlans under same model.

* Optimize untagged vlan check

* Re-ordering statements in validators

* Forgot to call super().clean()

* Adjust logic for form and serializer.  Add tests

* Fix test failure

* Fix ruff errors

* Fix test by removing now invalid test

* Update serializer, form and tests

* Optimize API test for vlan fields

* Optimize API serializer logic

---------

Co-authored-by: Daniel Sheppard <dans@dansheps.com>
2025-02-28 11:01:48 -05:00
Jason Novinger
09d867adc3 Fixes #18758: Enable sorting by Account count on prodiver list (#18763) 2025-02-28 07:28:09 -08:00
Jeremy Stretch
7aba6500dd Fixes #18141: Fix quick-add support for plugin models 2025-02-26 14:25:38 -05:00
github-actions
787a2dd7c2 Update source translation strings 2025-02-26 05:02:07 +00:00
Marcus Weiner
c81f4da780 Fix definition of vid_ranges in VLANGroup so it shows up in the OpenAPI schema (#18237) 2025-02-25 16:34:15 -08:00
Renato Almeida de Oliveira
cffb99cec5 Fixes: #17796 Custom Field Choices -> Create & Add Another causes IndexError (#18631) 2025-02-25 14:44:10 -08:00
Brian Tiemann
3b894f9ccb Handle null table in TableConfigForm 2025-02-25 12:59:26 -05:00
Alexander Haase
bf836c9bc2 Fixes 17357: Use virtual chassis name as fallback for device (#18710) 2025-02-25 07:55:00 -08:00
bctiemann
4a4596d5e8 Merge pull request #18721 from atownson/issue_18403
Closes #18403: Do not retrieve the data field from Job objects unless needed
2025-02-25 10:24:42 -05:00
atownson
48b825c64a Closes #18024: Add URL pattern for scripts to reference them by module.name (#18723)
* Add URL pattern for scripts to reference them by module.name

* Change _get_script function name and syntax

* Fix formatting issue
2025-02-25 09:39:39 -05:00
bctiemann
4fb42ac7b3 Merge pull request #18724 from netbox-community/18605-prefix-vlan-assignment-display
Fixes #18605: only VLANs at selected Site are shown in VLAN select
2025-02-25 09:31:48 -05:00
bctiemann
a8b4024016 Merge pull request #18491 from antoinekh/17542-Contact_Assignment_to_vpn_tunnels
#17542 contact assignment to vpn tunnels
2025-02-25 09:23:14 -05:00
Antoine Keranflec'h
a6c07e6a35 fix contact wrong model assignment 2025-02-25 13:53:50 +01:00
Antoine Keranflec'h
59cd5bc653 fix double line breaks 2025-02-25 09:15:55 +01:00
Antoine Keranflec'h
bda4f314a4 Merge branch 'netbox-community:main' into 17542-Contact_Assignment_to_vpn_tunnels 2025-02-25 09:09:13 +01:00
github-actions
2a56c08bc8 Update source translation strings 2025-02-25 05:02:09 +00:00
Brian Tiemann
beb0aff656 Add VLAN Translation Policy to bulk edit forms and tables for Interface and VMInterface 2025-02-24 13:55:40 -05:00
Jason Novinger
64270d6a4e Fixes #18605: only VLANs at selected Site are shown in VLAN select 2025-02-24 11:29:31 -06:00
github-actions
fba4141ce3 Update source translation strings 2025-02-24 15:18:11 +00:00
Jeremy Stretch
a4ecb82330 Clarify error message 2025-02-24 10:14:52 -05:00
atownson
5a3e213fb4 Do not retrieve the data field from Job objects unless needed 2025-02-24 09:07:16 -06:00
Andrey Tikhonov
83ca0ef955 Add missed init 2025-02-24 15:43:07 +01:00
Andrey Tikhonov
9c3e7f2c5d Cleanup 2025-02-24 15:38:19 +01:00
Andrey Tikhonov
7794c6cfcb Fix link peers 2025-02-24 15:28:45 +01:00
Andrey Tikhonov
8dc1d68aee port generic field to 4.2 2025-02-24 15:20:18 +01:00
bctiemann
c4304d059c Merge pull request #18703 from netbox-community/release-v4.2.4
Release v4.2.4
2025-02-21 15:34:15 -05:00
Brian Tiemann
fee66438f3 Fix django-htmx version 2025-02-21 15:19:54 -05:00
Brian Tiemann
0f52712468 Release v4.2.4 2025-02-21 15:15:14 -05:00
Jeremy Stretch
fbaa82df7b Fixes #18674: Fix form reset when selecting a value from a speed selection dropdown 2025-02-21 14:04:50 -05:00
mr1716
9c1358e6e7 #18698 Correct REST Wikipedia URL In Documentation 2025-02-21 09:34:16 -05:00
github-actions
63b7145baa Update source translation strings 2025-02-21 05:02:07 +00:00
Jeremy Stretch
bcd974210d Update Transifex resource slug 2025-02-20 12:53:25 -05:00
Jason Novinger
ed79e3bbf4 Fixes #18619: shift-select selects hidden items
This also fixes the inverse, when a range is unselected via shift-click,
previously checked checkboxes that are hidden are not changed.
2025-02-20 10:17:43 -05:00
Alexander Haase
b5bc0bad38 Cover multitable inheritance in serialization
During serialization, custom fields may be available to a model due to
multi-table inheritance, but might not be available in serialized data
because only direct fields of the model are covered. Now this attribute
is only used if available in serialized data. Models using multi-table
inheritance must modify their serialize_object() method to cover parent
serialization.
2025-02-20 10:09:35 -05:00
Jason Novinger
2a44affd03 Fixes #18594: asn_count sort in Sites list (#18634)
* Fixes #18594: asn_count sort in Sites list

* Fixes similar issue in `circuits.views.ProviderListView`

Thanks @bctiemann for point this out!
2025-02-20 10:01:04 -05:00
Jamie Murphy
d9066d6cff add device rack title 2025-02-19 22:02:59 +00:00
github-actions
57ef44706a Update source translation strings 2025-02-19 05:02:03 +00:00
Jason Novinger
70dddb673b Fixes #18585: filtering circuits by location (#18641)
* Fixes #18585: filtering circuits by location

This also fixes a related issue where selected filter is not shown in
the filter form.

Changes:
- Adds `CircuitFilterSet.location_id` field to enable filtering with
  incoming GET params
- Adds `CirciotFilterForm.location_id` field to enable filtering from
  list form
- Adds `location_id` to the Location fieldset on `CircuitFilterForm`

* Adds test for new CircuitFilterset.location_id filter
2025-02-18 13:33:05 -05:00
Alexander Haase
6c6cb321bf Fixes 18555: Fix model URL generator for plugins (#18607)
* Fix model URL generator for plugins

* Fix reverse accessor warning

* Revert "Fix reverse accessor warning"

This reverts commit f07642bb99.

* Add URL test case for regular models

* Split dummy models

Instead of using a single model for testing, one is used for testing the
plugin API and a dedicated one is used for testing the NetBox plugin
model features.

* Fix filterset test case error

* Rename test module

---------

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>
2025-02-18 09:11:32 -05:00
Renato Almeida de Oliveira
11514bfb21 Fixes: #18584 Add rack types column to manufacturers table (#18636)
* Add racktype_count annotation to list view queryset, create the LinkedCountColumn in ManufacturerTable

* Add Manufacturer field to RackTypeFilterForm
2025-02-18 08:41:12 -05:00
github-actions
c324d23634 Update source translation strings 2025-02-15 05:02:03 +00:00
Alexander Haase
f9431f1c29 Replace DurationChoices by JobIntervalChoices 2025-02-14 14:42:27 -05:00
Renato Almeida de Oliveira Zaroubin
b1ac20ac19 Update ModuleBay instance name before saving it 2025-02-14 14:22:29 -05:00
github-actions
f8022040b2 Update source translation strings 2025-02-12 05:02:12 +00:00
Tobias Genannt
8114492673 Close #18357: Display author name for plugins 2025-02-11 12:19:43 -05:00
Renato Almeida de Oliveira
154b3a7abb Fixes: 18593 - "Create & Add Another" broken for new IP addresses (#18602)
* update IPAddressEditView get_extra_addanother_params

* Simplify get_extra_addanother_params
2025-02-11 08:31:40 -05:00
github-actions
015ef25ca0 Update source translation strings 2025-02-10 18:34:35 +00:00
Alexander Haase
3e1cc0d7f3 Fixes 18208: Consolidate rendering configuration templates (#18604) 2025-02-10 11:03:08 -05:00
Alexander Haase
e1d1aab4bd Omit empty related models 2025-02-10 10:56:09 -05:00
Matej Vadnjal
299bde9653 use script form's cleaned data when calling script from CLI
so ObjectVar and other field values have proper types in script's data variable
2025-02-10 09:46:59 -05:00
Alexander Haase
4b98f74943 Fixes 18247: Fix dark mode button classes (#18617) 2025-02-10 09:42:08 -05:00
Jeremy Stretch
a33fb2a0a9 Closes #17918: Fix styling of "tagged items" list under tag view 2025-02-10 09:00:55 -05:00
github-actions
13dc6854c2 Update source translation strings 2025-02-08 05:02:19 +00:00
Antoine Keranflec'h
e475386936 Fixes: #18408 add STATUS_PAUSED to VirtualMachine (#18595)
* feat(vm): add extra status

* keep only usefull status

---------

Co-authored-by: Antoine Keranflec'h <antoine.keranflech@worldline.com>
2025-02-07 16:41:45 -05:00
Jeremy Stretch
0b194e363e Docs cleanup 2025-02-07 15:33:37 -05:00
github-actions
72e93b04da Update source translation strings 2025-02-07 05:02:00 +00:00
Renato Almeida de Oliveira
7794b6718a Fixes: #18013 - All saved filters showing up for Change Log table, regardless of defined object type (#18551)
* Setup ObjectChangeFilterForm __init__ to add query_param to filter_id

* code lint, move __init__ to end of class

* Move filter_id widget setup to SavedFiltersMixin, and add model attributes to Models FilterForms

* Add missing model declarations for filter forms

---------

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>
2025-02-06 17:21:46 -05:00
Renato Almeida de Oliveira
efa939d0c2 Fixes: #18241 - Script results log_threshold should default to Default (#18501)
* Changed LogLevelChoices order; Changed ScriptResultView to select LogLevelChoices to LOG_DEFAULT and setup the html template to put (All) in the last one

* Change LogLevelChoices in ScriptResultView get_table method

* Remove default option, add Default string to INFO

* Fix scripts.py and reports.py to reflect removing DEFAULT level

* fix linting
2025-02-06 16:30:25 -05:00
Jeremy Stretch
8e91db0394 Misc cleanup of the release checklist 2025-02-05 11:40:53 -05:00
bctiemann
260adfc9e7 Merge pull request #18569 from netbox-community/release-v4.2.3
Release 4.2.3
2025-02-04 15:35:45 -05:00
Brian Tiemann
9391f48d62 Update static bundle 2025-02-04 15:20:08 -05:00
Brian Tiemann
6e165435e2 Release 4.2.3 2025-02-04 15:09:37 -05:00
mr1716
29f405d27e #18496 Fixing Broken Link For Custom Links Documentation 2025-02-03 10:12:29 -05:00
Jeremy Stretch
f829f34b43 Closes #18559: Add a build parameter to ReleaseInfo (#18560)
* Closes #18559: Add a build parameter to ReleaseInfo

* Adjust dataclass typing
2025-02-03 09:44:00 -05:00
github-actions
0b794de40e Update source translation strings 2025-02-01 05:02:11 +00:00
Brian Tiemann
b2bc842f1c Remove 'provider' from VirtualCircuitIndex.display_attrs 2025-01-31 14:42:39 -05:00
Brian Tiemann
c8decf4c21 Add auth_required attrib on PluginMenuItem 2025-01-31 14:40:49 -05:00
Renato Almeida de Oliveira Zaroubin
e12a5d2edc Add get_extra_addanother_params method in IPAddressEditView 2025-01-31 14:33:26 -05:00
bctiemann
4c5fbb7326 Merge pull request #18544 from renatoalmeidaoliveira/18154-make-BaseTable-aware-default_user_preferences-annon-users
FIX #18154 - Cannot change default table preferences for anonymous users
2025-01-31 14:25:20 -05:00
mr1716
8aecf53d0e #18513 Updating Documentation Relating To Strawberry-Django Links 2025-01-31 14:14:48 -05:00
Renato Almeida de Oliveira Zaroubin
7d6089775e remove extra line 2025-01-31 18:48:50 +00:00
Renato Almeida de Oliveira Zaroubin
f5bdf7b593 Simplify Anon user logic 2025-01-31 18:03:55 +00:00
Antoine Keranflec'h
2a8728544c fix(pep) fix pep8 compliancy 2025-01-31 08:48:35 +01:00
Renato Almeida de Oliveira Zaroubin
62148bb83c Check if DEFAULT_USER_PREFERENCES are configured 2025-01-30 21:51:37 +00:00
Renato Almeida de Oliveira Zaroubin
22af6dd05f Add default user preferences tables testing in BaseTable 2025-01-30 21:09:36 +00:00
github-actions
5514df9dee Update source translation strings 2025-01-30 05:02:02 +00:00
Brian Tiemann
5cd7c6d167 Add <meta> tag reflecting settings.HOSTNAME 2025-01-29 12:50:08 -05:00
bctiemann
9ac79ebbdf Merge pull request #18516 from tobiasge/dont-fail-on-debug
Fix #18515: Don't fail in DEBUG mode
2025-01-28 15:20:52 -05:00
bctiemann
e6c0519ada Merge pull request #18517 from mr1716/main
#18512 Update required-parameters spelling
2025-01-28 15:17:59 -05:00
Tobias Genannt
07403f690a Fix #18515: Don't fail in DEBUG mode
When no Redis server is reachable management commands failed without
this try...except block.
2025-01-28 19:40:22 +01:00
mr1716
80e466dab7 #18512 Update required-parameters spelling 2025-01-28 09:06:37 -05:00
Brian Tiemann
34fa3835be NB-717 Update dashboard news feed URL to eliminate multiple 301 redirects 2025-01-28 08:26:35 -05:00
Brian Tiemann
7a6bb34d21 Reword references to develop and master branches 2025-01-28 08:26:05 -05:00
github-actions
968214b64a Update source translation strings 2025-01-28 05:02:09 +00:00
bctiemann
cf64f3cc43 Merge pull request #18444 from netbox-community/18433-fix-macaddress-primary-for-interface
Fixes: #18433 - Fix missing is_primary property on MACAddress model
2025-01-27 13:50:28 -05:00
Daniel Sheppard
ee5d7cfe31 Merge branch 'main' into 18433-fix-macaddress-primary-for-interface 2025-01-27 12:11:37 -06:00
Antoine Keranflec'h
f83e55e1db Merge branch 'netbox-community:main' into 17542-Contact_Assignment_to_vpn_tunnels 2025-01-25 14:19:25 +01:00
Jeremy Stretch
57fa1dd18d Add remaining issue types 2025-01-24 10:20:43 -05:00
Jeremy Stretch
b2b47ac740 Closes #18484: Exempt changes to GitHub templates from CI 2025-01-24 09:47:40 -05:00
Jeremy Stretch
313f44646b Assign GitHub issue type on creation 2025-01-24 09:33:04 -05:00
Brian Tiemann
c2daa70099 Fix typo in Site Groups docs 2025-01-24 08:10:39 -05:00
Brian Tiemann
5fce4eef8e Add note about \l command 2025-01-24 08:09:10 -05:00
Brian Tiemann
b1e7530295 Add warning about UTF8 encoding in PostgreSQL 2025-01-24 08:09:10 -05:00
github-actions
da9b452327 Update source translation strings 2025-01-24 05:02:20 +00:00
bctiemann
31efd1fe57 Merge pull request #18452 from netbox-community/18449-fix-formatting-errors
Fixes: #18449 - Clean up some formatting errors
2025-01-23 19:51:42 -05:00
bctiemann
a8168899b8 Merge pull request #18450 from netbox-community/18447-fix-legacy-macaddress-sorting
Fixes: #18447 - Fix sorting by `mac_address` field
2025-01-23 19:50:12 -05:00
bctiemann
e02ae72f0c Merge pull request #18445 from netbox-community/18436-fix-unassign-mac-with-primary
Fixes: #18436 - Prevent unassigning mac address when primary on an interface
2025-01-23 19:45:53 -05:00
Daniel Sheppard
3219609253 Change to @cached_property 2025-01-23 18:30:54 -06:00
Daniel Sheppard
adcb6bebd2 Remove mac_address from tables. 2025-01-22 14:14:56 -06:00
Daniel Sheppard
ad4e4e89a7 Update VirtualMachineVMInterfaceTable 2025-01-21 11:15:33 -06:00
Daniel Sheppard
c56a39a168 Fixes: #18449 - Clean up some formatting errors 2025-01-21 10:44:46 -06:00
Daniel Sheppard
d1914595f6 Fixes: #18447 - Fix sorting by mac_address field
* Disable sorting by `mac_address` for legacy `mac_address` field for Device and VM Interfaces
* Ensure `primary_mac_address` field is included in field list for Device and VM Interfaces
2025-01-21 10:15:33 -06:00
Jeremy Stretch
b913661297 Fixes #18438: Specify batch_size for migrations which run bulk_update() 2025-01-21 09:48:35 -05:00
Daniel Sheppard
bec97df242 Fix Tests 2025-01-20 23:44:36 -06:00
Daniel Sheppard
22e320084a Update UI to disable interface assignment when assigned as primary 2025-01-20 23:06:29 -06:00
Daniel Sheppard
277acd3a31 Fixes: #18436 - Prevent unassigning mac address when primary on an interface 2025-01-20 22:49:55 -06:00
Daniel Sheppard
51a79505fe Fixes: #18433 - Fix missing is_primary property on MACAddress model 2025-01-20 22:21:36 -06:00
github-actions
d11deb6678 Update source translation strings 2025-01-18 05:02:12 +00:00
Jeremy Stretch
f845b2cf07 Release v4.2.2 2025-01-17 15:05:09 -05:00
atownson
2ed4a2b005 Fixes: #18369 - Remove the json filter for protection rules (#18388)
* Remove the json filter for protection rules

* Configure PROTECTION_RULE config attribute to use ConfigJSONEncoder as serializer

* Tweak getattr()

---------

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>
2025-01-17 14:02:12 -05:00
Jeremy Stretch
5b9210dfa5 Fixes #18392: Exclude config contexts assigned to locations for VMs 2025-01-17 13:14:05 -05:00
Jeremy Stretch
4a13664e0f Closes #18425: Remove the triage priority field from GitHub issue templates 2025-01-17 11:06:17 -05:00
Jeremy Stretch
a9f3c74b0c Fixes #18379: Ensure RSS feed content within dashboard widget is sanitized 2025-01-17 10:25:22 -05:00
Brian Tiemann
50b7f46fc0 Migrate DEFAULT_FILE_STORAGE to STORAGES 2025-01-17 09:04:51 -05:00
Brian Tiemann
07ad4c1321 Make GFK scope field sortable=False on tables where it appears 2025-01-17 08:52:12 -05:00
bctiemann
4a1fea3504 Fixes: #18336 - Perform Rack object validation of u_height and starting_unit on rack_type if present (#18395)
* Perform Rack object validation of u_height and starting_unit on rack_type if present

* Calculate effective values before doing validation
2025-01-17 08:45:17 -05:00
bctiemann
993d8f1480 Fixes: #18373 - Fix validation of site in Assign Device to Cluster flow (#18375)
* Fix validation of site in Assign Device to Cluster flow

* Validate Location as well as Site scope
2025-01-17 08:35:17 -05:00
bctiemann
c3efa2149c Fixes: #18350 - Remove 'site' and 'provider_network' from CircuitTerminationIndex.display_attrs (#18351)
* Remove 'site' and 'provider_network' from CircuitTerminationIndex.display_attrs

* Use '_site' and '_provider_network' in display_attrs

* Replace private fields with 'termination'
2025-01-17 08:28:43 -05:00
Jeremy Stretch
a75fa53d4d Closes #18348: Disable legacy pre-commit hook script 2025-01-13 08:50:34 -05:00
Jeremy Stretch
e75d327f38 Fixes #18376: Include tagged VLANs in interfaces list for Q-in-Q interfaces 2025-01-10 09:10:34 -05:00
github-actions
a79d869bd8 Update source translation strings 2025-01-10 05:02:08 +00:00
Brian Tiemann
32422d1683 Don't cache CACHE_KEY_CATALOG_ERROR if ISOLATED_DEPLOYMENT is True 2025-01-09 15:21:27 -05:00
Jeremy Stretch
571f604ce8 Fixes #18368: Restore missing fields on REST API serializer for MAC addresses 2025-01-09 14:53:03 -05:00
Jeremy Stretch
b12c8c880f Fixes #18363: Fix assignment of MAC addresses to interfaces via REST API (#18367)
* Fixes #18363: Fix assignment of MAC addresses to interfaces via REST API

* Add missing API & view tests
2025-01-09 13:55:19 -05:00
Jeremy Stretch
b11f179527 Closes #18362: Create a system job for census reporting 2025-01-09 11:56:09 -05:00
Brian Tiemann
80e1fd02bb Update docs to indicate PostgreSQL 13+ requirement 2025-01-09 10:58:51 -05:00
github-actions
4090afbf24 Update source translation strings 2025-01-09 05:02:09 +00:00
Jeremy Stretch
d04fc11c61 Release v4.2.1 (#18346)
* Release v4.2.1

* Add changelog for #18282
2025-01-08 10:19:28 -05:00
Brian Tiemann
f6b8c1966d Use order_by to change ordering behavior of VLAN column rather than changing accessor 2025-01-08 09:54:00 -05:00
Brian Tiemann
4456c488f1 Change PrefixTable.vlan to represent the VLAN ID rather than the VLAN object, to enable more useful sorting by VLAN ID rather than site-grouped VLAN objects 2025-01-08 09:54:00 -05:00
Jeremy Stretch
53aa2c8624 Fixes #18329: Pin strawberry-graphql-django to v0.52.0 to resolve upstream bug 2025-01-08 08:59:54 -05:00
github-actions
ffac0974dd Update source translation strings 2025-01-08 05:02:12 +00:00
bctiemann
e518f08604 Fixes: #18316 - Fix PrefixIndex reference to 'site' (#18322)
* Fix PrefixIndex reference to 'site'

* Fix ClusterIndex reference to 'site' and add 'scope' to WirelessLANIndex
2025-01-07 10:47:05 -05:00
Tobias Genannt
4ae5529362 Fix #18314: Use get to avoid KeyError 2025-01-07 10:39:55 -05:00
Jeremy Stretch
ef6c89ee5d Fixes #18324: Correct filter names for certain related object listings 2025-01-07 10:34:35 -05:00
Jeremy Stretch
9c960c2387 Fixes #18318: Correct navigation breadcrumbs for module type UI view 2025-01-07 10:28:22 -05:00
github-actions
ed541220e8 Update source translation strings 2025-01-07 05:02:25 +00:00
Jeremy Stretch
14cec518f5 Closes #18311: Update minimum required version of PostgreSQL 2025-01-06 17:04:13 -05:00
Antoine Keranflec'h
113c8d1d85 Merge branch 'netbox-community:develop' into 17542-Contact_Assignment_to_vpn_tunnels 2024-11-12 14:17:05 +01:00
Antoine Keranflec'h
5b2241aaaf fix(17542) add contact to tunnels 2024-10-10 15:38:48 +02:00
260 changed files with 68631 additions and 56335 deletions

View File

@@ -1,5 +1,6 @@
---
name: ✨ Feature Request
type: Feature
description: Propose a new NetBox feature or enhancement
labels: ["type: feature", "status: needs triage"]
body:
@@ -14,7 +15,7 @@ body:
attributes:
label: NetBox version
description: What version of NetBox are you currently running?
placeholder: v4.2.0
placeholder: v4.2.8
validations:
required: true
- type: dropdown
@@ -27,19 +28,6 @@ body:
- Other
validations:
required: true
- type: dropdown
attributes:
label: Triage priority
description: >
Issue triage may be prioritized in some cases. Select whichever of the following
conditions applies, if any.
options:
- I volunteer to perform this work (if approved)
- I'm a NetBox Labs customer
- N/A
default: 2
validations:
required: true
- type: textarea
attributes:
label: Proposed functionality

View File

@@ -1,5 +1,6 @@
---
name: 🐛 Bug Report
type: Bug
description: Report a reproducible bug in the current release of NetBox
labels: ["type: bug", "status: needs triage"]
body:
@@ -22,24 +23,11 @@ body:
- Self-hosted
validations:
required: true
- type: dropdown
attributes:
label: Triage priority
description: >
Issue triage may be prioritized in some cases. Select whichever of the following
conditions applies, if any.
options:
- I volunteer to perform this work (if approved)
- I'm a NetBox Labs customer
- N/A
default: 2
validations:
required: true
- type: input
attributes:
label: NetBox Version
description: What version of NetBox are you currently running?
placeholder: v4.2.0
placeholder: v4.2.8
validations:
required: true
- type: dropdown

View File

@@ -1,5 +1,6 @@
---
name: 📖 Documentation Change
type: Documentation
description: Suggest an addition or modification to the NetBox documentation
labels: ["type: documentation", "status: needs triage"]
body:

View File

@@ -1,5 +1,6 @@
---
name: 🌍 Translation
type: Translation
description: Request support for a new language in the user interface
labels: ["type: translation"]
body:

View File

@@ -1,5 +1,6 @@
---
name: 🏡 Housekeeping
type: Housekeeping
description: A change pertaining to the codebase itself (developers only)
labels: ["type: housekeeping"]
body:

View File

@@ -1,5 +1,6 @@
---
name: 🗑️ Deprecation
type: Deprecation
description: The removal of an existing feature or resource
labels: ["type: deprecation"]
body:

View File

@@ -3,11 +3,15 @@ name: CI
on:
push:
paths-ignore:
- '.github/ISSUE_TEMPLATE/**'
- '.github/PULL_REQUEST_TEMPLATE.md'
- 'contrib/**'
- 'docs/**'
- 'netbox/translations/**'
pull_request:
paths-ignore:
- '.github/ISSUE_TEMPLATE/**'
- '.github/PULL_REQUEST_TEMPLATE.md'
- 'contrib/**'
- 'docs/**'
- 'netbox/translations/**'

View File

@@ -12,6 +12,7 @@ permissions:
jobs:
stale:
if: github.repository == 'netbox-community/netbox'
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v9

View File

@@ -13,6 +13,7 @@ permissions:
jobs:
stale:
if: github.repository == 'netbox-community/netbox'
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v9

View File

@@ -13,6 +13,7 @@ permissions:
jobs:
lock:
if: github.repository == 'netbox-community/netbox'
runs-on: ubuntu-latest
steps:
- uses: dessant/lock-threads@v5

View File

@@ -13,6 +13,7 @@ env:
jobs:
makemessages:
if: github.repository == 'netbox-community/netbox'
runs-on: ubuntu-latest
env:
NETBOX_CONFIGURATION: netbox.configuration_testing

View File

@@ -1,7 +1,7 @@
[main]
host = https://app.transifex.com
[o:netbox-community:p:netbox:r:9cbf4fcf95b3d92e4ebbf1a5e5d1caee]
[o:netbox-community:p:netbox:r:034999968a7366ba27a8bdf1ab63bf42]
file_filter = netbox/translations/<lang>/LC_MESSAGES/django.po
source_file = netbox/translations/en/LC_MESSAGES/django.po
type = PO

View File

@@ -84,7 +84,7 @@ intake policy](https://github.com/netbox-community/netbox/wiki/Issue-Intake-Poli
* It's very important that you not submit a pull request until a relevant issue has been opened **and** assigned to you. Otherwise, you risk wasting time on work that may ultimately not be needed.
* New pull requests should generally be based off of the `develop` branch, rather than `master`. The `develop` branch is used for ongoing development, while `master` is used for tracking stable releases. (If you're developing for an upcoming minor release, use `feature` instead.)
* New pull requests should generally be based off of the `main` branch. This branch, in keeping with the [trunk-based development](https://trunkbaseddevelopment.com/) approach, is used for ongoing development and bug fixes and always represents the newest stable code, from which releases are periodically branched. (If you're developing for an upcoming minor release, use `feature` instead.)
* In most cases, it is not necessary to add a changelog entry: A maintainer will take care of this when the PR is merged. (This helps avoid merge conflicts resulting from multiple PRs being submitted simultaneously.)

View File

@@ -8,8 +8,6 @@ django-cors-headers
# Runtime UI tool for debugging Django
# https://github.com/jazzband/django-debug-toolbar/blob/main/docs/changes.rst
# Pinned for DNS looukp bug; see https://github.com/netbox-community/netbox/issues/16454
# and https://github.com/jazzband/django-debug-toolbar/issues/1927
django-debug-toolbar
# Library for writing reusable URL query filters
@@ -90,7 +88,7 @@ mkdocs-material
# Introspection for embedded code
# https://github.com/mkdocstrings/mkdocstrings/blob/main/CHANGELOG.md
mkdocstrings[python-legacy]
mkdocstrings[python]
# Library for manipulating IP prefixes and addresses
# https://github.com/netaddr/netaddr/blob/master/CHANGELOG.rst

View File

@@ -427,6 +427,7 @@
"e3",
"xdsl",
"docsis",
"moca",
"bpon",
"epon",
"10g-epon",
@@ -500,6 +501,9 @@
"n",
"mrj21",
"fc",
"fc-pc",
"fc-upc",
"fc-apc",
"lc",
"lc-pc",
"lc-upc",
@@ -565,6 +569,9 @@
"n",
"mrj21",
"fc",
"fc-pc",
"fc-upc",
"fc-apc",
"lc",
"lc-pc",
"lc-upc",

View File

@@ -54,6 +54,7 @@ Icons](https://github.com/google/material-design-icons) icon's name; or be
`None` for no icon.
For instance, the OIDC backend may be customized with
```python
SOCIAL_AUTH_BACKEND_ATTRS = {
'oidc': ("My awesome SSO", "login"),

View File

@@ -233,3 +233,15 @@ This parameter controls how frequently a failed job is retried, up to the maximu
Default: `0` (retries disabled)
The maximum number of times a background task will be retried before being marked as failed.
## DISK_BASE_UNIT
Default: `1000`
The base unit for disk sizes. Set this to `1024` to use binary prefixes (MiB, GiB, etc.) instead of decimal prefixes (MB, GB, etc.).
## RAM_BASE_UNIT
Default: `1000`
The base unit for RAM sizes. Set this to `1024` to use binary prefixes (MiB, GiB, etc.) instead of decimal prefixes (MB, GB, etc.).

View File

@@ -2,7 +2,7 @@
## ALLOWED_HOSTS
This is a list of valid fully-qualified domain names (FQDNs) and/or IP addresses that can be used to reach the NetBox service. Usually this is the same as the hostname for the NetBox server, but can also be different; for example, when using a reverse proxy serving the NetBox website under a different FQDN than the hostname of the NetBox server. To help guard against [HTTP Host header attackes](https://docs.djangoproject.com/en/3.0/topics/security/#host-headers-virtual-hosting), NetBox will not permit access to the server via any other hostnames (or IPs).
This is a list of valid fully-qualified domain names (FQDNs) and/or IP addresses that can be used to reach the NetBox service. Usually this is the same as the hostname for the NetBox server, but can also be different; for example, when using a reverse proxy serving the NetBox website under a different FQDN than the hostname of the NetBox server. To help guard against [HTTP Host header attacks](https://docs.djangoproject.com/en/3.0/topics/security/#host-headers-virtual-hosting), NetBox will not permit access to the server via any other hostnames (or IPs).
!!! note
This parameter must always be defined as a list or tuple, even if only a single value is provided.
@@ -25,7 +25,7 @@ ALLOWED_HOSTS = ['*']
## DATABASE
NetBox requires access to a PostgreSQL 12 or later database service to store data. This service can run locally on the NetBox server or on a remote system. The following parameters must be defined within the `DATABASE` dictionary:
NetBox requires access to a PostgreSQL 13 or later database service to store data. This service can run locally on the NetBox server or on a remote system. The following parameters must be defined within the `DATABASE` dictionary:
* `NAME` - Database name
* `USER` - PostgreSQL username

View File

@@ -2,7 +2,7 @@
Custom links allow users to display arbitrary hyperlinks to external content within NetBox object views. These are helpful for cross-referencing related records in systems outside NetBox. For example, you might create a custom link on the device view which links to the current device in a Network Monitoring System (NMS).
Custom links are created by navigating to Customization > Custom Links. Each link is associated with a particular NetBox object type (site, device, prefix, etc.) and will be displayed on relevant views. Each link has display text and a URL, and data from the NetBox item being viewed can be included in the link using [Jinja2 template code](https://jinja2docs.readthedocs.io/en/stable/) through the variable `object`, and custom fields through `object.cf`.
Custom links are created by navigating to Customization > Custom Links. Each link is associated with a particular NetBox object type (site, device, prefix, etc.) and will be displayed on relevant views. Each link has display text and a URL, and data from the NetBox item being viewed can be included in the link using [Jinja template code](https://jinja.palletsprojects.com/en/stable/) through the variable `object`, and custom fields through `object.cf`.
For example, you might define a link like this:

View File

@@ -308,6 +308,7 @@ A particular object within NetBox. Each ObjectVar must specify a particular mode
* `query_params` - A dictionary of query parameters to use when retrieving available options (optional)
* `context` - A custom dictionary mapping template context variables to fields, used when rendering `<option>` elements within the dropdown menu (optional; see below)
* `null_option` - A label representing a "null" or empty choice (optional)
* `selector` - A boolean that, when True, includes an advanced object selection widget to assist the user in identifying the desired object (optional; False by default)
To limit the selections available within the list, additional query parameters can be passed as the `query_params` dictionary. For example, to show only devices with an "active" status:

View File

@@ -25,6 +25,7 @@ Height: {{ rack.u_height }}U
To access custom fields of an object within a template, use the `cf` attribute. For example, `{{ obj.cf.color }}` will return the value (if any) for a custom field named `color` on `obj`.
If you need to use the config context data in an export template, you'll should use the function `get_config_context` to get all the config context data. For example:
```
{% for server in queryset %}
{% set data = server.get_config_context() %}

View File

@@ -1,12 +1,14 @@
# Release Checklist
This documentation describes the process of packaging and publishing a new NetBox release. There are three types of release:
This documentation describes the process of packaging and publishing a new NetBox release. There are three types of releases:
* Major release (e.g. v3.7.8 to v4.0.0)
* Minor release (e.g. v4.0.10 to v4.1.0)
* Patch release (e.g. v4.1.0 to v4.1.1)
While major releases generally introduce some very substantial change to the application, they are typically treated the same as minor version increments for the purpose of release packaging.
While major releases generally introduce some very substantial changes to the application, they are typically treated the same as minor version increments for the purpose of release packaging.
For patch releases (e.g. upgrading from v4.2.2 to v4.2.3), begin at the [patch releases](#patch-releases) heading below. For minor or major releases, complete the entire checklist.
## Minor Version Releases
@@ -29,6 +31,29 @@ Close the [release milestone](https://github.com/netbox-community/netbox/milesto
Check that a link to the release notes for the new version is present in the navigation menu (defined in `mkdocs.yml`), and that a summary of all major new features has been added to `docs/index.md`.
### Update the Dependency Requirements Matrix
For every minor release, update the dependency requirements matrix in `docs/installation/upgrading.md` ("All versions") to reflect the supported versions of Python, PostgreSQL, and Redis:
1. Add a new row with the supported dependency versions.
2. Include a documentation link using the release tag format: `https://github.com/netbox-community/netbox/blob/v4.2.0/docs/installation/index.md`
3. Bold any version changes for clarity.
**Example Update:**
```markdown
| NetBox Version | Python min | Python max | PostgreSQL min | Redis min | Documentation |
|:--------------:|:----------:|:----------:|:--------------:|:---------:|:-------------------------------------------------------------------------------------------------:|
| 4.2 | 3.10 | 3.12 | **13** | 4.0 | [Link](https://github.com/netbox-community/netbox/blob/v4.2.0/docs/installation/index.md) |
```
### Update System Requirements
If a new Django release is adopted or other major dependencies (Python, PostgreSQL, Redis) change:
* Update the installation guide (`docs/installation/index.md`) with the new minimum versions.
* Update the upgrade guide (`docs/installation/upgrading.md`) for the current version accordingly.
### Manually Perform a New Install
Start the documentation server and navigate to the current version of the installation docs:
@@ -37,15 +62,25 @@ Start the documentation server and navigate to the current version of the instal
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.
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.
### Test Upgrade Paths
Upgrading from a previous version typically involves database migrations, which must work without errors. Supported upgrade paths include from one minor version to another within the same major version (i.e. 4.0 to 4.1), as well as from the latest patch version of the previous minor version (i.e. 3.7 to 4.0 or to 4.1). Prior to release, test all these supported paths by loading demo data from the source version and performing a `./manage.py migrate`.
Upgrading from a previous version typically involves database migrations, which must work without errors.
Test the following supported upgrade paths:
- From one minor version to another within the same major version (e.g. 4.0 to 4.1).
- From the latest patch version of the previous minor version (e.g. 3.7 to 4.0 or 4.1).
Prior to release, test all these supported paths by loading demo data from the source version and performing:
```no-highlight
./manage.py migrate
```
### Merge the `feature` Branch
Submit a pull request to merge the `feature` branch into the `main` branch in preparation for its release. Once it has been merged, continue with the section for patch releases below.
Submit a pull request to merge the `feature` branch into the `main` branch in preparation for its release. Once it has been merged, continue with the section for the patch releases below.
### Rebuild Demo Data (After Release)
@@ -57,7 +92,7 @@ After the release of a new minor version, generate a new demo data snapshot comp
### Create a Release Branch
Begin by creating a new branch (based off of `main`) to effect the release. This will comprise the changes listed below.
Begin by creating a new branch (based on `main`) to effect the release. This will comprise the changes listed below.
```
git checkout main
@@ -85,7 +120,20 @@ In cases where upgrading a dependency to its most recent release is breaking, it
### Update UI Dependencies
Check whether any UI dependencies (JavaScript packages, fonts, etc.) need to be updated by running `yarn outdated` from within the `project-static/` directory. [Upgrade these dependencies](./web-ui.md#updating-dependencies) as necessary, then run `yarn bundle` to generate the necessary files for distribution.
Check whether any UI dependencies (JavaScript packages, fonts, etc.) need to be updated by running `yarn outdated` from within the `project-static/` directory. [Upgrade these dependencies](./web-ui.md#updating-dependencies) as necessary, then run `yarn bundle` to generate the necessary files for distribution:
```
$ yarn bundle
yarn run v1.22.19
$ node bundle.js
✅ Bundled source file 'styles/external.scss' to 'netbox-external.css'
✅ Bundled source file 'styles/netbox.scss' to 'netbox.css'
✅ Bundled source file 'styles/svg/rack_elevation.scss' to 'rack_elevation.css'
✅ Bundled source file 'styles/svg/cable_trace.scss' to 'cable_trace.css'
✅ Bundled source file 'index.ts' to 'netbox.js'
✅ Copied graphiql files
Done in 1.00s.
```
### Rebuild the Device Type Definition Schema
@@ -102,7 +150,7 @@ This will automatically update the schema file at `contrib/generated_schema.json
Updated language translations should be pulled from [Transifex](https://app.transifex.com/netbox-community/netbox/dashboard/) and re-compiled for each new release. First, retrieve any updated translation files using the Transifex CLI client:
```no-highlight
tx pull
tx pull --force
```
Then, compile these portable (`.po`) files for use in the application:
@@ -116,9 +164,12 @@ Then, compile these portable (`.po`) files for use in the application:
### Update Version and Changelog
* Update the version and published date in `release.yaml` with the current version & date. Add a designation (e.g.g `beta1`) if applicable.
* Update the version number and date in `netbox/release.yaml`. Add or remove the designation (e.g. `beta1`) if applicable.
* Update the example version numbers in the feature request and bug report templates under `.github/ISSUE_TEMPLATES/`.
* Replace the "FUTURE" placeholder in the release notes with the current date.
* Add a section for this release at the top of the changelog page for the minor version (e.g. `docs/release-notes/version-4.2.md`) listing all relevant changes made in this release.
!!! tip
Put yourself in the shoes of the user when recording change notes. Focus on the effect that each change has for the end user, rather than the specific bits of code that were modified in a PR. Ensure that each message conveys meaning absent context of the initial feature request or bug report. Remember to include keywords or phrases (such as exception names) that can be easily searched.
### Submit a Pull Request
@@ -126,6 +177,9 @@ Commit the above changes and submit a pull request titled **"Release vX.Y.Z"** t
Once CI has completed and a colleague has reviewed the PR, merge it. This effects a new release in the `main` branch.
!!! warning
To ensure a streamlined review process, the pull request for a release **must** be limited to the changes outlined in this document. A release PR must never include functional changes to the application: Any unrelated "cleanup" needs to be captured in a separate PR prior to the release being shipped.
### Create a New Release
Create a [new release](https://github.com/netbox-community/netbox/releases/new) on GitHub with the following parameters.

View File

@@ -22,7 +22,7 @@ NetBox generally follows the [Django style guide](https://docs.djangoproject.com
### Linting
The [ruff](https://docs.astral.sh/ruff/) linter is used to enforce code style. A [pre-commit hook](./getting-started.md#3-enable-pre-commit-hooks) which runs this automatically is included with NetBox. To invoke `ruff` manually, run:
The [ruff](https://docs.astral.sh/ruff/) linter is used to enforce code style, and is run automatically by [pre-commit](./getting-started.md#5-install-pre-commit). To invoke `ruff` manually, run:
```
ruff check netbox/

View File

@@ -30,13 +30,13 @@ To download translated strings automatically, you'll need to:
1. Install the [Transifex CLI client](https://github.com/transifex/cli)
2. Generate a [Transifex API token](https://app.transifex.com/user/settings/api/)
Once you have the client set up, run the following command:
Once you have the client set up, run the following command from the project root (e.g. `/opt/netbox/`):
```no-highlight
TX_TOKEN=$TOKEN tx pull
TX_TOKEN=$TOKEN tx pull --force
```
This will download all portable (`.po`) translation files from Transifex, updating them locally as needed.
This will download all portable (`.po`) translation files from Transifex, updating them locally as needed. (The `--force` argument instructs the client to disregard the timestamps of local translation files.)
Once retrieved, the updated strings need to be compiled into new `.mo` files so they can be used by the application. Run Django's [`compilemessages`](https://docs.djangoproject.com/en/stable/ref/django-admin/#django-admin-compilemessages) management command to compile them:
@@ -46,6 +46,9 @@ Once retrieved, the updated strings need to be compiled into new `.mo` files so
Once any new `.mo` files have been generated, they need to be committed and pushed back up to GitHub. (Again, this is typically done as part of publishing a new NetBox release.)
!!! tip
Run `git status` to check that both `*.mo` & `*.po` files have been updated as expected.
## Proposing New Languages
If you'd like to add support for a new language to NetBox, the first step is to [submit a GitHub issue](https://github.com/netbox-community/netbox/issues/new?assignees=&labels=type%3A+translation&projects=&template=translation.yaml) to capture the proposal. While we'd like to add as many languages as possible, we do need to limit the rate at which new languages are added. New languages will be selected according to community interest and the number of volunteers who sign up as translators.

View File

@@ -46,7 +46,7 @@ Regions will always be listed alphabetically by name within each parent, and the
Like regions, site groups can be arranged in a recursive hierarchy for grouping sites. However, whereas regions are intended for geographic organization, site groups may be used for functional grouping. For example, you might classify sites as corporate, branch, or customer sites in addition to where they are physically located.
The use of both regions and site groups affords to independent but complementary dimensions across which sites can be organized.
The use of both regions and site groups affords two independent but complementary dimensions across which sites can be organized.
## Sites

View File

@@ -2,8 +2,8 @@
This section entails the installation and configuration of a local PostgreSQL database. If you already have a PostgreSQL database service in place, skip to [the next section](2-redis.md).
!!! warning "PostgreSQL 12 or later required"
NetBox requires PostgreSQL 12 or later. Please note that MySQL and other relational databases are **not** supported.
!!! warning "PostgreSQL 13 or later required"
NetBox requires PostgreSQL 13 or later. Please note that MySQL and other relational databases are **not** supported.
## Installation
@@ -34,7 +34,7 @@ This section entails the installation and configuration of a local PostgreSQL da
sudo systemctl enable --now postgresql
```
Before continuing, verify that you have installed PostgreSQL 12 or later:
Before continuing, verify that you have installed PostgreSQL 13 or later:
```no-highlight
psql -V
@@ -62,6 +62,9 @@ GRANT CREATE ON SCHEMA public TO netbox;
!!! danger "Use a strong password"
**Do not use the password from the example.** Choose a strong, random password to ensure secure database authentication for your NetBox installation.
!!! danger "Use UTF8 encoding"
Make sure that your database uses `UTF8` encoding (the default for new installations). Especially do not use `SQL_ASCII` encoding, as it can lead to unpredictable and unrecoverable errors. Enter `\l` to check your encoding.
Once complete, enter `\q` to exit the PostgreSQL shell.
## Verify Service Status

View File

@@ -246,7 +246,7 @@ Once NetBox has been configured, we're ready to proceed with the actual installa
* Create a Python virtual environment
* Installs all required Python packages
* Run database schema migrations
* Run database schema migrations (skip with `--readonly`)
* Builds the documentation locally (for offline use)
* Aggregate static resource files on disk
@@ -266,6 +266,9 @@ sudo PYTHON=/usr/bin/python3.10 /opt/netbox/upgrade.sh
!!! note
Upon completion, the upgrade script may warn that no existing virtual environment was detected. As this is a new installation, this warning can be safely ignored.
!!! note
To run the script on a node connected to a database in read-only mode, include the `--readonly` parameter. This will skip the application of any database migrations.
## Create a Super User
NetBox does not come with any predefined user accounts. You'll need to create a super user (administrative account) to be able to log into NetBox. First, enter the Python virtual environment created by the upgrade script:

View File

@@ -5,8 +5,6 @@
The installation instructions provided here have been tested to work on Ubuntu 22.04 and CentOS 8.3. The particular commands needed to install dependencies on other distributions may vary significantly. Unfortunately, this is outside the control of the NetBox maintainers. Please consult your distribution's documentation for assistance with any errors.
<iframe width="560" height="315" src="https://www.youtube.com/embed/_y5JRiW_PLM" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
The following sections detail how to set up a new instance of NetBox:
1. [PostgreSQL database](1-postgresql.md)
@@ -21,7 +19,7 @@ The following sections detail how to set up a new instance of NetBox:
| Dependency | Supported Versions |
|------------|--------------------|
| Python | 3.10, 3.11, 3.12 |
| PostgreSQL | 12+ |
| PostgreSQL | 13+ |
| Redis | 4.0+ |
Below is a simplified overview of the NetBox application stack for reference:

View File

@@ -17,11 +17,52 @@ Prior to upgrading your NetBox instance, be sure to carefully review all [releas
NetBox requires the following dependencies:
| Dependency | Supported Versions |
|------------|--------------------|
| Python | 3.10, 3.11, 3.12 |
| PostgreSQL | 12+ |
| Redis | 4.0+ |
=== "Current Version"
| Dependency | Supported Versions |
|------------|--------------------|
| Python | 3.10, 3.11, 3.12 |
| PostgreSQL | 13+ |
| Redis | 4.0+ |
=== "All Versions"
| NetBox Version | Python min | Python max | PostgreSQL min | Redis min | Documentation |
|:--------------:|:----------:|:----------:|:--------------:|:---------:|:-------------------------------------------------------------------------------------------------:|
| 4.2 | 3.10 | 3.12 | **13** | 4.0 | [Link](https://github.com/netbox-community/netbox/blob/v4.2.0/docs/installation/index.md) |
| 4.1 | 3.10 | 3.12 | 12 | 4.0 | [Link](https://github.com/netbox-community/netbox/blob/v4.1.0/docs/installation/index.md) |
| 4.0 | **3.10** | **3.12** | 12 | 4.0 | [Link](https://github.com/netbox-community/netbox/blob/v4.0.0/docs/installation/index.md) |
| 3.7 | 3.8 | 3.11 | 12 | 4.0 | [Link](https://github.com/netbox-community/netbox/blob/v3.7.0/docs/installation/index.md) |
| 3.6 | 3.8 | **3.11** | **12** | 4.0 | [Link](https://github.com/netbox-community/netbox/blob/v3.6.0/docs/installation/index.md) |
| 3.5 | 3.8 | 3.10 | 11 | 4.0 | [Link](https://github.com/netbox-community/netbox/blob/v3.5.0/docs/installation/index.md) |
| 3.4 | 3.8 | 3.10 | **11** | 4.0 | [Link](https://github.com/netbox-community/netbox/blob/v3.4.0/docs/installation/index.md) |
| 3.3 | 3.8 | 3.10 | 10 | 4.0 | [Link](https://github.com/netbox-community/netbox/blob/v3.3.0/docs/installation/index.md) |
| 3.2 | **3.8** | **3.10** | 10 | 4.0 | [Link](https://github.com/netbox-community/netbox/blob/v3.2.0/docs/installation/index.md) |
| 3.1 | 3.7 | 3.9 | **10** | 4.0 | [Link](https://github.com/netbox-community/netbox/blob/v3.1.0/docs/installation/index.md) |
| 3.0 | **3.7** | 3.9 | 9.6 | 4.0 | [Link](https://github.com/netbox-community/netbox/blob/v3.0.0/docs/installation/index.md) |
| 2.11 | 3.6 | **3.9** | 9.6 | 4.0 | [Link](https://github.com/netbox-community/netbox/blob/v2.11.0/docs/installation/index.md) |
| 2.10 | 3.6 | 3.8 | **9.6** | 4.0 | [Link](https://github.com/netbox-community/netbox/blob/v2.10.0/docs/installation/index.md) |
| 2.9 | 3.6 | 3.8 | 9.5 | **4.0** | [Link](https://github.com/netbox-community/netbox/blob/v2.9.0/docs/installation/index.md) |
| 2.8 | **3.6** | **3.8** | **9.5** | **3.4** | [Link](https://github.com/netbox-community/netbox/blob/v2.8.0/docs/installation/index.md) |
| 2.7 | 3.5 | 3.7 | 9.4 | - | [Link](https://github.com/netbox-community/netbox/blob/v2.7.0/docs/installation/index.md) |
| 2.6 | 3.5 | 3.7 | 9.4 | - | [Link](https://github.com/netbox-community/netbox/blob/v2.6.0/docs/installation/index.md) |
| 2.5 | **3.5** | 3.7 | 9.4 | - | [Link](https://github.com/netbox-community/netbox/blob/v2.5.0/docs/installation/index.md) |
| 2.4 | **3.4** | **3.7** | 9.4 | - | [Link](https://github.com/netbox-community/netbox/blob/v2.4.0/docs/installation/index.md) |
| 2.3 | 2.7 | 3.6 | 9.4 | - | [Link](https://github.com/netbox-community/netbox/blob/v2.3.0/docs/installation/postgresql.md) |
| 2.2 | 2.7 | 3.6 | **9.4** | - | [Link](https://github.com/netbox-community/netbox/blob/v2.2.0/docs/installation/postgresql.md) |
| 2.1 | 2.7 | 3.6 | 9.3 | - | [Link](https://github.com/netbox-community/netbox/blob/v2.1.0/docs/installation/postgresql.md) |
| 2.0 | 2.7 | **3.6** | **9.3** | - | [Link](https://github.com/netbox-community/netbox/blob/v2.0.0/docs/installation/postgresql.md) |
| 1.9 | 2.7 | 3.5 | 9.2 | - | [Link](https://github.com/netbox-community/netbox/blob/v1.9.0-r1/docs/installation/postgresql.md) |
| 1.8 | 2.7 | 3.5 | 9.2 | - | [Link](https://github.com/netbox-community/netbox/blob/v1.8.0/docs/installation/postgresql.md) |
| 1.7 | 2.7 | 3.5 | 9.2 | - | [Link](https://github.com/netbox-community/netbox/blob/v1.7.0/docs/installation/postgresql.md) |
| 1.6 | 2.7 | 3.5 | 9.2 | - | [Link](https://github.com/netbox-community/netbox/blob/v1.6.0/docs/installation/postgresql.md) |
| 1.5 | 2.7 | 3.5 | **9.2** | - | [Link](https://github.com/netbox-community/netbox/blob/v1.5.0/docs/installation/postgresql.md) |
| 1.4 | 2.7 | 3.5 | 9.1 | - | [Link](https://github.com/netbox-community/netbox/blob/v1.4.0/docs/installation/postgresql.md) |
| 1.3 | 2.7 | 3.5 | 9.1 | - | [Link](https://github.com/netbox-community/netbox/blob/v1.3.0/docs/installation/postgresql.md) |
| 1.2 | 2.7 | 3.5 | 9.1 | - | [Link](https://github.com/netbox-community/netbox/blob/v1.2.0/docs/installation/postgresql.md) |
| 1.1 | 2.7 | 3.5 | 9.1 | - | [Link](https://github.com/netbox-community/netbox/blob/v1.1.0/docs/getting-started.md) |
| 1.0 | 2.7 | 3.5 | 9.1 | - | [Link](https://github.com/netbox-community/netbox/blob/1.0.0/docs/getting-started.md) |
## 3. Install the Latest Release
@@ -83,17 +124,19 @@ sudo cp /opt/netbox-$OLDVER/gunicorn.py /opt/netbox/
### Option B: Check Out a Git Release
This guide assumes that NetBox is installed at `/opt/netbox`. First, determine the latest release either by visiting our [releases page](https://github.com/netbox-community/netbox/releases) or by running the following `git` commands:
This guide assumes that NetBox is installed at `/opt/netbox`. First, determine the latest release either by visiting our [releases page](https://github.com/netbox-community/netbox/releases) or by running the following command:
```
sudo git fetch --tags
git describe --tags $(git rev-list --tags --max-count=1)
git ls-remote --tags https://github.com/netbox-community/netbox.git \
| grep -o 'refs/tags/v[0-9]*\.[0-9]*\.[0-9]*$' \
| tail -n 1 \
| sed 's|refs/tags/||'
```
Check out the desired release by specifying its tag:
Check out the desired release by specifying its tag. For example:
```
sudo git checkout v4.2.0
sudo git checkout v4.2.7
```
## 4. Run the Upgrade Script
@@ -111,6 +154,9 @@ sudo ./upgrade.sh
sudo PYTHON=/usr/bin/python3.10 ./upgrade.sh
```
!!! note
To run the script on a node connected to a database in read-only mode, include the `--readonly` parameter. This will skip the application of any database migrations.
This script performs the following actions:
* Destroys and rebuilds the Python virtual environment

View File

@@ -1,6 +1,6 @@
# GraphQL API Overview
NetBox provides a read-only [GraphQL](https://graphql.org/) API to complement its REST API. This API is powered by [Strawberry Django](https://strawberry-graphql.github.io/strawberry-django/).
NetBox provides a read-only [GraphQL](https://graphql.org/) API to complement its REST API. This API is powered by [Strawberry Django](https://strawberry.rocks/).
## Queries
@@ -47,7 +47,7 @@ NetBox provides both a singular and plural query field for each object type:
For example, query `device(id:123)` to fetch a specific device (identified by its unique ID), and query `device_list` (with an optional set of filters) to fetch all devices.
For more detail on constructing GraphQL queries, see the [GraphQL queries documentation](https://graphql.org/learn/queries/). For filtering and lookup syntax, please refer to the [Strawberry Django documentation](https://strawberry-graphql.github.io/strawberry-django/guide/filters/).
For more detail on constructing GraphQL queries, see the [GraphQL queries documentation](https://graphql.org/learn/queries/). For filtering and lookup syntax, please refer to the [Strawberry Django documentation](https://strawberry.rocks/docs/django/guide/filters).
## Filtering
@@ -60,6 +60,7 @@ query {
}
}
```
In addition, filtering can be done on list of related objects as shown in the following query:
```
@@ -98,8 +99,8 @@ Certain queries can return multiple types of objects, for example cable terminat
}
}
}
```
The field "class_type" is an easy way to distinguish what type of object it is when viewing the returned data, or when filtering. It contains the class name, for example "CircuitTermination" or "ConsoleServerPort".
## Authentication

View File

@@ -2,7 +2,7 @@
## What is a REST API?
REST stands for [representational state transfer](https://en.wikipedia.org/wiki/Representational_state_transfer). It's a particular type of API which employs HTTP requests and [JavaScript Object Notation (JSON)](https://www.json.org/) to facilitate create, retrieve, update, and delete (CRUD) operations on objects within an application. Each type of operation is associated with a particular HTTP verb:
REST stands for [representational state transfer](https://en.wikipedia.org/wiki/REST). It's a particular type of API which employs HTTP requests and [JavaScript Object Notation (JSON)](https://www.json.org/) to facilitate create, retrieve, update, and delete (CRUD) operations on objects within an application. Each type of operation is associated with a particular HTTP verb:
* `GET`: Retrieve an object or list of objects
* `POST`: Create an object

View File

@@ -79,5 +79,5 @@ NetBox is built on the [Django](https://djangoproject.com/) Python framework and
| HTTP service | nginx or Apache |
| WSGI service | gunicorn or uWSGI |
| Application | Django/Python |
| Database | PostgreSQL 12+ |
| Database | PostgreSQL 13+ |
| Task queuing | Redis/django-rq |

View File

@@ -204,6 +204,7 @@ To ease development, it is recommended to go ahead and install the plugin at thi
```no-highlight
$ pip install -e .
```
More information on editable builds can be found at [Editable installs for pyproject.toml ](https://peps.python.org/pep-0660/).
## Configure NetBox

View File

@@ -150,5 +150,5 @@ The [NAPALM automation](https://github.com/napalm-automation/napalm) library pro
* Modified the interface serializer to include three discrete fields relating to connections: `is_connected` (boolean), `interface_connection`, and `circuit_termination`
* Added two new fields to the inventory item serializer: `asset_tag` and `description`
* Added "wireless" to interface type filter (in addition to physical, virtual, and LAG)
* Added a new endpoint at /api/ipam/prefixes/<pk>/available-ips/ to retrieve or create available IPs within a prefix
* Added a new endpoint at /api/ipam/prefixes/<pk\>/available-ips/ to retrieve or create available IPs within a prefix
* Extended `parent_device` on DeviceSerializer to include the `url` and `display_name` of the parent Device, and the `url` of the DeviceBay

View File

@@ -1,10 +1,215 @@
# NetBox v4.2
## v4.2.8 (2025-04-22)
### Enhancements
* [#17136](https://github.com/netbox-community/netbox/issues/17136) - Introduce the `--readonly` flag on upgrade script
* [#17908](https://github.com/netbox-community/netbox/issues/17908) - Add trace buttons to terminations under cable view
* [#18879](https://github.com/netbox-community/netbox/issues/18879) - Enable filtering prefixes by group of assigned VLAN
* [#18976](https://github.com/netbox-community/netbox/issues/18976) - Include FHRP group name on interface lists
* [#18978](https://github.com/netbox-community/netbox/issues/18978) - Add 802.1Q mode to interface filter form
* [#19038](https://github.com/netbox-community/netbox/issues/19038) - Show count of related VLAN groups under cluster view
* [#19040](https://github.com/netbox-community/netbox/issues/19040) - Add "copy to clipboard" button for rendered config
* [#19056](https://github.com/netbox-community/netbox/issues/19056) - Enable filtering devices by location slug
* [#19196](https://github.com/netbox-community/netbox/issues/19196) - Add filtering by VLAN translation policy to interface filter forms
### Bug Fixes
* [#18500](https://github.com/netbox-community/netbox/issues/18500) - `prepare_cloned_fields()` should validate cloning support on model
* [#18669](https://github.com/netbox-community/netbox/issues/18669) - Ensure default custom field values are respected when creating objects via the REST API
* [#18881](https://github.com/netbox-community/netbox/issues/18881) - Include missing related object counts under certain views
* [#18955](https://github.com/netbox-community/netbox/issues/18955) - Omit "clear" button on required choice fields
* [#18959](https://github.com/netbox-community/netbox/issues/18959) - Preserve ordering of terminations in cable traces
* [#18961](https://github.com/netbox-community/netbox/issues/18961) - Virtual chassis form should exclude members of other VCs when adding members
* [#19166](https://github.com/netbox-community/netbox/issues/19166) - Fix custom field choices bulk import support for `base_choices`
* [#19189](https://github.com/netbox-community/netbox/issues/19189) - The `load_yaml()` convenience method on BaseScript should use SafeLoader
* [#19195](https://github.com/netbox-community/netbox/issues/19195) - Language cookie should respect `SESSION_COOKIE_SECURE` value
* [#19230](https://github.com/netbox-community/netbox/issues/19230) - Allow label reuse when creating multiple components from a pattern
* [#19268](https://github.com/netbox-community/netbox/issues/19268) - Restore editing conflict protection for several object forms
---
## v4.2.7 (2025-04-10)
### Enhancements
* [#16144](https://github.com/netbox-community/netbox/issues/16144) - Add support for plugin models to GetReturnURLMixin
* [#18138](https://github.com/netbox-community/netbox/issues/18138) - Enable filtering of ObjectVar and MultiObjectVar input selections for custom fields
* [#18656](https://github.com/netbox-community/netbox/issues/18656) - Enable FHRP group assignment when bulk importing IP addresses
* [#18980](https://github.com/netbox-community/netbox/issues/18980) - Optimize bulk updates of custom field values when custom fields are added/removed
* [#19018](https://github.com/netbox-community/netbox/issues/19018) - Add MoCA interface type
### Bug Fixes
* [#18553](https://github.com/netbox-community/netbox/issues/18553) - Avoid clearing site of assigned virtual machines when editing a cluster
* [#18738](https://github.com/netbox-community/netbox/issues/18738) - Respect declared ordering of custom scripts within a module
* [#18895](https://github.com/netbox-community/netbox/issues/18895) - Fix GraphQL support for interfaces which terminate virtual circuits
* [#18904](https://github.com/netbox-community/netbox/issues/18904) - Add missing tags column to config contexts table
* [#18964](https://github.com/netbox-community/netbox/issues/18964) - Fix "select all" behavior on object lists
* [#18965](https://github.com/netbox-community/netbox/issues/18965) - "Run script" button should respect default commit toggle for custom scripts
* [#18991](https://github.com/netbox-community/netbox/issues/18991) - Fix cable path tracing for pass-through ports in REST API
* [#18999](https://github.com/netbox-community/netbox/issues/18999) - Fix filtering of inventory items with no manufacturer in GraphQL API
* [#19021](https://github.com/netbox-community/netbox/issues/19021) - Preserve JSONField stylign when `help_text` is passed
* [#19023](https://github.com/netbox-community/netbox/issues/19023) - `get_field_value()` should honor null values on bound form fields
* [#19030](https://github.com/netbox-community/netbox/issues/19030) - Prevent pagination buttons from overlapping bulk action buttons on object lists
* [#19041](https://github.com/netbox-community/netbox/issues/19041) - Fix `IndexError` exception when creating multiple front ports with a label
* [#19092](https://github.com/netbox-community/netbox/issues/19092) - Fix clearing of scope field when bulk editing prefixes
* [#19122](https://github.com/netbox-community/netbox/issues/19122) - Fix styling of server error page
---
## v4.2.6 (2025-03-21)
### Enhancements
* [#17503](https://github.com/netbox-community/netbox/issues/17503) - Add rack title above rack on rack detail view
* [#17686](https://github.com/netbox-community/netbox/issues/17686) - Add config option for disk space divisor
* [#18579](https://github.com/netbox-community/netbox/issues/18579) - Update filtersets and filter forms to include contact filters where missing
* [#18744](https://github.com/netbox-community/netbox/issues/18744) - Ensure contact link in tables is hyperlinked
* [#18816](https://github.com/netbox-community/netbox/issues/18816) - Add FC/UPC, FC/APC and FC/PC port types
* [#18880](https://github.com/netbox-community/netbox/issues/18880) - Delay enqueuing background tasks until DB transaction is committed to avoid race condition
* [#18939](https://github.com/netbox-community/netbox/issues/18939) - Support site group search for ASNs
### Bug Fixes
* [#18409](https://github.com/netbox-community/netbox/issues/18409) - Eliminate N+1 issue by adding generic prefetch operation to Interface API endpoint
* [#18557](https://github.com/netbox-community/netbox/issues/18557) - Update JSONField to enclose bare string values in quotes
* [#18582](https://github.com/netbox-community/netbox/issues/18582) - Fix prefix bulk import with associated VLAN and conflicting VLAN IDs
* [#18742](https://github.com/netbox-community/netbox/issues/18742) - Ensure location list and detail views show related VLAN group information
* [#18782](https://github.com/netbox-community/netbox/issues/18782) - Ensure misconfigured object list widgets on the dashboard now degrade gracefully
* [#18833](https://github.com/netbox-community/netbox/issues/18833) - Fix inventory item bulk edit to ensure that component name and type are both validated Ensure
* [#18838](https://github.com/netbox-community/netbox/issues/18838) - Ensure that local context data correctly rejects falsy values
* [#18845](https://github.com/netbox-community/netbox/issues/18845) - Restore default sort behavior of name column on devices list view
* [#18863](https://github.com/netbox-community/netbox/issues/18863) - Exempt MPTT-based models from ordering fix introduced in #18279
* [#18869](https://github.com/netbox-community/netbox/issues/18869) - Ensure numeric conversion helper always return a clean decimal value
* [#18872](https://github.com/netbox-community/netbox/issues/18872) - Ensure that `kind` is a required field when making journal entries
* [#18884](https://github.com/netbox-community/netbox/issues/18884) - Ensure tag deserialization is handled correctly
* [#18887](https://github.com/netbox-community/netbox/issues/18887) - Allow VM interface objects to be set on prefix object-type custom field
* [#18926](https://github.com/netbox-community/netbox/issues/18926) - Fix icon displayed for GitHub authentication on login page
* [#18928](https://github.com/netbox-community/netbox/issues/18928) - Support cascading deletions when cleaning up expired changelog records
* [#18933](https://github.com/netbox-community/netbox/issues/18933) - Allow filtering VLAN groups by associated site groups
* [#18944](https://github.com/netbox-community/netbox/issues/18944) - Ensure clearing "Widget type" field when adding widgets to dashboard does not cause a "ValueError: Unregistered widget class" error
* [#18949](https://github.com/netbox-community/netbox/issues/18949) - Add missing contacts property to GraphQL types where the associated model has a connection to a contact
---
## v4.2.5 (2025-03-06)
### Enhancements
* [#17357](https://github.com/netbox-community/netbox/issues/17357) - Use VirtualChassis name as fallback for unnamed devices
* [#17542](https://github.com/netbox-community/netbox/issues/17542) - Add contact assignments to VPN tunnels
* [#17944](https://github.com/netbox-community/netbox/issues/17944) - Allow script inputs to be filtered on ObjectVar and MultiObjectVar selections
* [#18024](https://github.com/netbox-community/netbox/issues/18024) - Add permalink URL pattern to match a custom script by module and class name
* [#18141](https://github.com/netbox-community/netbox/issues/18141) - Support "Quick Add" for plugins
* [#18403](https://github.com/netbox-community/netbox/issues/18403) - Improve performance of job list views
* [#18693](https://github.com/netbox-community/netbox/issues/18693) - Support setting VLAN translation on bulk edit of interfaces
* [#18772](https://github.com/netbox-community/netbox/issues/18772) - Add "type" filter for virtual circuits
* [#18774](https://github.com/netbox-community/netbox/issues/18774) - Add tooltip preview of tag descriptions when hovering over tags
### Bug Fixes
* [#15016](https://github.com/netbox-community/netbox/issues/15016) - Prevent AssertionError when adding multiple devices "mid-span" in a cable trace
* [#15924](https://github.com/netbox-community/netbox/issues/15924) - Prevent setting tagged VLANs on interfaces with mode: tagged-all
* [#17488](https://github.com/netbox-community/netbox/issues/17488) - Ensure VLANGroup.vid_ranges shows up in API results
* [#17709](https://github.com/netbox-community/netbox/issues/17709) - Allow primary key for nested models in OpenAPI request schemas
* [#17796](https://github.com/netbox-community/netbox/issues/17796) - Fix IndexError on "Create & Add Another" operation on custom field choices
* [#18605](https://github.com/netbox-community/netbox/issues/18605) - Limit VLAN selection dropdown to choices appropriate to site
* [#18722](https://github.com/netbox-community/netbox/issues/18722) - Improve UI feedback on failed script execution
* [#18729](https://github.com/netbox-community/netbox/issues/18729) - Fix unpredictable ordering on querysets with annotations/groupings
* [#18753](https://github.com/netbox-community/netbox/issues/18753) - Prevent webhooks from being triggered on a script dry-run
* [#18758](https://github.com/netbox-community/netbox/issues/18758) - Fix FieldError when sorting by account count field in providers list
* [#18768](https://github.com/netbox-community/netbox/issues/18768) - Fix removing a secondary MAC address from an interface
---
## v4.2.4 (2025-02-21)
### Enhancements
* [#17309](https://github.com/netbox-community/netbox/issues/17309) - Omit empty counts in related object tables
* [#18277](https://github.com/netbox-community/netbox/issues/18277) - Improve multi-table inheritance in serialization of change-logged models
* [#18286](https://github.com/netbox-community/netbox/issues/18286) - Add more job duration choices
* [#18357](https://github.com/netbox-community/netbox/issues/18357) - Display author name in plugin list for locally installed plugins
* [#18408](https://github.com/netbox-community/netbox/issues/18408) - Add Paused status for virtual machines
* [#18584](https://github.com/netbox-community/netbox/issues/18584) - Add rack type column to manufacturer list
### Bug Fixes
* [#17436](https://github.com/netbox-community/netbox/issues/17436) - Fix {module} replacement in module bays
* [#18013](https://github.com/netbox-community/netbox/issues/18013) - Limit object type to selected object in change log filter
* [#18241](https://github.com/netbox-community/netbox/issues/18241) - Default logging level of custom scripts changed to INFO
* [#18247](https://github.com/netbox-community/netbox/issues/18247) - Fix visibility of disabled cable paths in dark mode
* [#18480](https://github.com/netbox-community/netbox/issues/18480) - Clean data passed to script in runscript command
* [#18555](https://github.com/netbox-community/netbox/issues/18555) - Add default get_absolute_url method to plugin models
* [#18585](https://github.com/netbox-community/netbox/issues/18585) - Fix filtering circuits by location
* [#18593](https://github.com/netbox-community/netbox/issues/18593) - Fix "Create & Add Another" IP Address workflow
* [#18594](https://github.com/netbox-community/netbox/issues/18594) - Enable sorting by ASN count on site and provider lists
* [#18619](https://github.com/netbox-community/netbox/issues/18619) - Ensure shift-click selection selects only visible list items
* [#18674](https://github.com/netbox-community/netbox/issues/18674) - Preserve form values when selecting speed on circuit termination
---
## v4.2.3 (2025-02-04)
### Enhancements
* [#18518](https://github.com/netbox-community/netbox/issues/18518) - Add a "hostname" `<meta>` tag to the page header
### Bug Fixes
* [#18497](https://github.com/netbox-community/netbox/issues/18497) - Fix unhandled `FieldDoesNotExist` exception when search results include virtual circuit
* [#18433](https://github.com/netbox-community/netbox/issues/18433) - Fix MAC address not shown as "primary for interface" in MAC address detail view
* [#18154](https://github.com/netbox-community/netbox/issues/18154) - Allow anonymous users to change default table preferences
* [#18515](https://github.com/netbox-community/netbox/issues/18515) - Fix Django `collectstatic` management command in debug mode with Redis not running
* [#18456](https://github.com/netbox-community/netbox/issues/18456) - Avoid duplicate MAC Address column in interface tables
* [#18447](https://github.com/netbox-community/netbox/issues/18447) - Fix `FieldError` exception when sorting interface tables on MAC Address columns
* [#18438](https://github.com/netbox-community/netbox/issues/18438) - Improve performance in IPAM migration `0072_prefix_cached_relations` when upgrading from v4.1 or earlier
* [#18436](https://github.com/netbox-community/netbox/issues/18436) - Reset primary MAC address when unassigning MAC address from interface
* [#18181](https://github.com/netbox-community/netbox/issues/18181) - Fix "Create & Add Another" workflow when adding IP addresses to interfaces
---
## v4.2.2 (2025-01-17)
### Bug Fixes
* [#18336](https://github.com/netbox-community/netbox/issues/18336) - Validate new rack height against installed devices when changing a rack's type
* [#18350](https://github.com/netbox-community/netbox/issues/18350) - Fix `FieldDoesNotExist` exception when global search results include a circuit termination
* [#18353](https://github.com/netbox-community/netbox/issues/18353) - Disable fetching of plugin catalog data when `ISOLATED_DEPLOYMENT` is enabled
* [#18362](https://github.com/netbox-community/netbox/issues/18362) - Avoid transmitting census data on every worker restart
* [#18363](https://github.com/netbox-community/netbox/issues/18363) - Fix support for assigning a MAC address to an interface via the REST API
* [#18368](https://github.com/netbox-community/netbox/issues/18368) - Restore missing attributes from REST API serializer for MAC addresses (`tags`, `created`, `last_updated`, and custom fields)
* [#18369](https://github.com/netbox-community/netbox/issues/18369) - Fix `TypeError` exception when rendering the system configuration view with one or more custom classes defined under `PROTECTION_RULES`
* [#18373](https://github.com/netbox-community/netbox/issues/18373) - Fix `AttributeError` exception when attempting to assign host devices to a cluster
* [#18376](https://github.com/netbox-community/netbox/issues/18376) - Fix the display of tagged VLANs in interfaces list for Q-in-Q interfaces
* [#18379](https://github.com/netbox-community/netbox/issues/18379) - Ensure RSS feed dashboard widget content is sanitized
* [#18392](https://github.com/netbox-community/netbox/issues/18392) - Virtual machines should not inherit config contexts assigned to locations
* [#18400](https://github.com/netbox-community/netbox/issues/18400) - Fix support for `STORAGE_BACKEND` configuration parameter
* [#18406](https://github.com/netbox-community/netbox/issues/18406) - Scope column headers in object lists should not be orderable
---
## v4.2.1 (2025-01-08)
### Bug Fixes
* [#18282](https://github.com/netbox-community/netbox/issues/18282) - Fix ordering of prefixes list by assigned VLAN
* [#18314](https://github.com/netbox-community/netbox/issues/18314) - Fix KeyError exception when rendering pre-saved dashboard (`requires_internet` missing)
* [#18316](https://github.com/netbox-community/netbox/issues/18316) - Fix AttributeError exception when global search results include prefixes and/or clusters
* [#18318](https://github.com/netbox-community/netbox/issues/18318) - Correct navigation breadcrumbs for module type UI view
* [#18324](https://github.com/netbox-community/netbox/issues/18324) - Correct filtering for certain related object listings
* [#18329](https://github.com/netbox-community/netbox/issues/18329) - Address upstream bug in GraphQL API where only one primary IP address is returned within a device/VM list
---
## v4.2.0 (2025-01-06)
### Breaking Changes
* Support for the Django admin UI has been completely removed. (The Django admin UI was disabled by default in NetBox v4.0.)
* This release drops support for PostgreSQL 12. PostgreSQL 13 or later is required to run this release.
* NetBox has adopted collation-based natural ordering for many models. This may alter the order in which some objects are listed by default.
* Automatic redirects from pre-v4.1 UI views for virtual disks have been removed.
* The `site` and `provider_network` foreign key fields on `circuits.CircuitTermination` have been replaced by the `termination` generic foreign key.

View File

@@ -28,12 +28,7 @@ plugins:
- mkdocstrings:
handlers:
python:
setup_commands:
- import os
- import django
- os.chdir('netbox/')
- os.environ.setdefault("DJANGO_SETTINGS_MODULE", "netbox.settings")
- django.setup()
paths: ["netbox"]
options:
heading_level: 3
members_order: source
@@ -64,6 +59,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format
- pymdownx.tabbed:
alternate_style: true
not_in_nav: |
/index.md
nav:
- Introduction: 'introduction.md'
- Features:

View File

@@ -28,6 +28,7 @@ from netbox.config import get_config
from netbox.views import generic
from users import forms, tables
from users.models import UserConfig
from utilities.string import remove_linebreaks
from utilities.views import register_model_view
@@ -123,12 +124,18 @@ class LoginView(View):
# Set the user's preferred language (if any)
if language := request.user.config.get('locale.language'):
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language, max_age=request.session.get_expiry_age())
response.set_cookie(
key=settings.LANGUAGE_COOKIE_NAME,
value=language,
max_age=request.session.get_expiry_age(),
secure=settings.SESSION_COOKIE_SECURE,
)
return response
else:
logger.debug(f"Login form validation failed for username: {form['username'].value()}")
username = form['username'].value()
logger.debug(f"Login form validation failed for username: {remove_linebreaks(username)}")
return render(request, self.template_name, {
'form': form,
@@ -140,10 +147,10 @@ class LoginView(View):
redirect_url = data.get('next', settings.LOGIN_REDIRECT_URL)
if redirect_url and url_has_allowed_host_and_scheme(redirect_url, allowed_hosts=None):
logger.debug(f"Redirecting user to {redirect_url}")
logger.debug(f"Redirecting user to {remove_linebreaks(redirect_url)}")
else:
if redirect_url:
logger.warning(f"Ignoring unsafe 'next' URL passed to login form: {redirect_url}")
logger.warning(f"Ignoring unsafe 'next' URL passed to login form: {remove_linebreaks(redirect_url)}")
redirect_url = reverse('home')
return HttpResponseRedirect(redirect_url)
@@ -218,7 +225,12 @@ class UserConfigView(LoginRequiredMixin, View):
# Set/clear language cookie
if language := form.cleaned_data['locale.language']:
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language, max_age=request.session.get_expiry_age())
response.set_cookie(
key=settings.LANGUAGE_COOKIE_NAME,
value=language,
max_age=request.session.get_expiry_age(),
secure=settings.SESSION_COOKIE_SECURE,
)
else:
response.delete_cookie(settings.LANGUAGE_COOKIE_NAME)

View File

@@ -95,7 +95,7 @@ class ProviderFilterSet(NetBoxModelFilterSet, ContactModelFilterSet):
)
class ProviderAccountFilterSet(NetBoxModelFilterSet):
class ProviderAccountFilterSet(NetBoxModelFilterSet, ContactModelFilterSet):
provider_id = django_filters.ModelMultipleChoiceFilter(
queryset=Provider.objects.all(),
label=_('Provider (ID)'),
@@ -234,6 +234,11 @@ class CircuitFilterSet(NetBoxModelFilterSet, TenancyFilterSet, ContactModelFilte
to_field_name='slug',
label=_('Site (slug)'),
)
location_id = django_filters.ModelMultipleChoiceFilter(
field_name='terminations___location',
label=_('Location (ID)'),
queryset=Location.objects.all(),
)
termination_a_id = django_filters.ModelMultipleChoiceFilter(
queryset=CircuitTermination.objects.all(),
label=_('Termination A (ID)'),

View File

@@ -66,11 +66,12 @@ class ProviderFilterForm(ContactModelFilterForm, NetBoxModelFilterSetForm):
tag = TagFilterField(model)
class ProviderAccountFilterForm(NetBoxModelFilterSetForm):
class ProviderAccountFilterForm(ContactModelFilterForm, NetBoxModelFilterSetForm):
model = ProviderAccount
fieldsets = (
FieldSet('q', 'filter_id', 'tag'),
FieldSet('provider_id', 'account', name=_('Attributes')),
FieldSet('contact', 'contact_role', 'contact_group', name=_('Contacts')),
)
provider_id = DynamicModelMultipleChoiceField(
queryset=Provider.objects.all(),
@@ -126,7 +127,7 @@ class CircuitFilterForm(TenancyFilterForm, ContactModelFilterForm, NetBoxModelFi
'type_id', 'status', 'install_date', 'termination_date', 'commit_rate', 'distance', 'distance_unit',
name=_('Attributes')
),
FieldSet('region_id', 'site_group_id', 'site_id', name=_('Location')),
FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', name=_('Location')),
FieldSet('tenant_group_id', 'tenant_id', name=_('Tenant')),
FieldSet('contact', 'contact_role', 'contact_group', name=_('Contacts')),
)
@@ -181,6 +182,11 @@ class CircuitFilterForm(TenancyFilterForm, ContactModelFilterForm, NetBoxModelFi
},
label=_('Site')
)
location_id = DynamicModelMultipleChoiceField(
queryset=Location.objects.all(),
required=False,
label=_('Location')
)
install_date = forms.DateField(
label=_('Install date'),
required=False,
@@ -322,7 +328,7 @@ class VirtualCircuitFilterForm(TenancyFilterForm, ContactModelFilterForm, NetBox
fieldsets = (
FieldSet('q', 'filter_id', 'tag'),
FieldSet('provider_id', 'provider_account_id', 'provider_network_id', name=_('Provider')),
FieldSet('type', 'status', name=_('Attributes')),
FieldSet('type_id', 'status', name=_('Attributes')),
FieldSet('tenant_group_id', 'tenant_id', name=_('Tenant')),
)
selector_fields = ('filter_id', 'q', 'provider_id', 'provider_network_id')

View File

@@ -43,7 +43,7 @@ class ProviderType(NetBoxObjectType, ContactsMixin):
fields='__all__',
filters=ProviderAccountFilter
)
class ProviderAccountType(NetBoxObjectType):
class ProviderAccountType(ContactsMixin, NetBoxObjectType):
provider: Annotated["ProviderType", strawberry.lazy('circuits.graphql.types')]
circuits: List[Annotated["CircuitType", strawberry.lazy('circuits.graphql.types')]]

View File

@@ -1,4 +1,3 @@
# Generated by Django 5.0.9 on 2024-10-21 17:34
import django.db.models.deletion
from django.db import migrations, models
@@ -16,7 +15,7 @@ def populate_denormalized_fields(apps, schema_editor):
termination._site_id = termination.site_id
# Note: Location cannot be set prior to migration
CircuitTermination.objects.bulk_update(terminations, ['_region', '_site_group', '_site'])
CircuitTermination.objects.bulk_update(terminations, ['_region', '_site_group', '_site'], batch_size=100)
class Migration(migrations.Migration):

View File

@@ -349,9 +349,8 @@ class CircuitTermination(
def clean(self):
super().clean()
# Must define either site *or* provider network
if self.termination is None:
raise ValidationError(_("A circuit termination must attach to termination."))
raise ValidationError(_("A circuit termination must attach to a terminating object."))
def save(self, *args, **kwargs):
# Cache objects associated with the terminating object (for filtering)

View File

@@ -34,7 +34,7 @@ class CircuitTerminationIndex(SearchIndex):
('port_speed', 2000),
('upstream_speed', 2000),
)
display_attrs = ('circuit', 'site', 'provider_network', 'description')
display_attrs = ('circuit', 'termination', 'description')
@register_search
@@ -90,7 +90,7 @@ class VirtualCircuitIndex(SearchIndex):
('description', 500),
('comments', 5000),
)
display_attrs = ('provider', 'provider_network', 'provider_account', 'status', 'tenant', 'description')
display_attrs = ('provider_network', 'provider_account', 'status', 'tenant', 'description')
@register_search

View File

@@ -111,7 +111,7 @@ class CircuitTerminationTable(NetBoxTable):
provider = tables.Column(
verbose_name=_('Provider'),
linkify=True,
accessor='circuit.provider'
accessor='circuit__provider'
)
term_side = tables.Column(
verbose_name=_('Side')

View File

@@ -23,7 +23,6 @@ class ProviderTable(ContactsColumnMixin, NetBoxTable):
verbose_name=_('Accounts')
)
account_count = columns.LinkedCountColumn(
accessor=tables.A('accounts__count'),
viewname='circuits:provideraccount_list',
url_params={'provider_id': 'pk'},
verbose_name=_('Account Count')
@@ -33,7 +32,6 @@ class ProviderTable(ContactsColumnMixin, NetBoxTable):
verbose_name=_('ASNs')
)
asn_count = columns.LinkedCountColumn(
accessor=tables.A('asns__count'),
viewname='ipam:asn_list',
url_params={'provider_id': 'pk'},
verbose_name=_('ASN Count')

View File

@@ -3,8 +3,10 @@ from django.test import TestCase
from circuits.choices import *
from circuits.filtersets import *
from circuits.models import *
from dcim.choices import InterfaceTypeChoices
from dcim.models import Cable, Device, DeviceRole, DeviceType, Interface, Manufacturer, Region, Site, SiteGroup
from dcim.choices import InterfaceTypeChoices, LocationStatusChoices
from dcim.models import (
Cable, Device, DeviceRole, DeviceType, Interface, Location, Manufacturer, Region, Site, SiteGroup
)
from ipam.models import ASN, RIR
from netbox.choices import DistanceUnitChoices
from tenancy.models import Tenant, TenantGroup
@@ -225,6 +227,17 @@ class CircuitTestCase(TestCase, ChangeLoggedFilterSetTests):
)
ProviderNetwork.objects.bulk_create(provider_networks)
locations = (
Location.objects.create(
site=sites[0], name='Test Location 1', slug='test-location-1',
status=LocationStatusChoices.STATUS_ACTIVE,
),
Location.objects.create(
site=sites[1], name='Test Location 2', slug='test-location-2',
status=LocationStatusChoices.STATUS_ACTIVE,
),
)
circuits = (
Circuit(
provider=providers[0],
@@ -305,7 +318,9 @@ class CircuitTestCase(TestCase, ChangeLoggedFilterSetTests):
circuit_terminations = ((
CircuitTermination(circuit=circuits[0], termination=sites[0], term_side='A'),
CircuitTermination(circuit=circuits[0], termination=locations[0], term_side='Z'),
CircuitTermination(circuit=circuits[1], termination=sites[1], term_side='A'),
CircuitTermination(circuit=circuits[1], termination=locations[1], term_side='Z'),
CircuitTermination(circuit=circuits[2], termination=sites[2], term_side='A'),
CircuitTermination(circuit=circuits[3], termination=provider_networks[0], term_side='A'),
CircuitTermination(circuit=circuits[4], termination=provider_networks[1], term_side='A'),
@@ -395,6 +410,11 @@ class CircuitTestCase(TestCase, ChangeLoggedFilterSetTests):
params = {'site': [sites[0].slug, sites[1].slug]}
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
def test_location(self):
location_ids = Location.objects.values_list('id', flat=True)[:2]
params = {'location_id': location_ids}
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
def test_tenant(self):
tenants = Tenant.objects.all()[:2]
params = {'tenant_id': [tenants[0].pk, tenants[1].pk]}

View File

@@ -4,6 +4,7 @@ from django.shortcuts import get_object_or_404, redirect, render
from django.utils.translation import gettext_lazy as _
from dcim.views import PathTraceView
from ipam.models import ASN
from netbox.views import generic
from tenancy.views import ObjectContactsView
from utilities.forms import ConfirmationForm
@@ -20,7 +21,9 @@ from .models import *
@register_model_view(Provider, 'list', path='', detail=False)
class ProviderListView(generic.ObjectListView):
queryset = Provider.objects.annotate(
count_circuits=count_related(Circuit, 'provider')
count_circuits=count_related(Circuit, 'provider'),
asn_count=count_related(ASN, 'providers'),
account_count=count_related(ProviderAccount, 'provider'),
)
filterset = filtersets.ProviderFilterSet
filterset_form = forms.ProviderFilterForm
@@ -167,11 +170,16 @@ class ProviderNetworkView(GetRelatedModelsMixin, generic.ObjectView):
'related_models': self.get_related_models(
request,
instance,
omit=(CircuitTermination,),
extra=(
(
Circuit.objects.restrict(request.user, 'view').filter(terminations___provider_network=instance),
'provider_network_id',
),
(
CircuitTermination.objects.restrict(request.user, 'view').filter(_provider_network=instance),
'provider_network_id',
),
),
),
}

View File

@@ -2,12 +2,13 @@ import re
import typing
from collections import OrderedDict
from drf_spectacular.extensions import OpenApiSerializerFieldExtension
from drf_spectacular.extensions import OpenApiSerializerFieldExtension, OpenApiSerializerExtension, _SchemaType
from drf_spectacular.openapi import AutoSchema
from drf_spectacular.plumbing import (
build_basic_type, build_choice_field, build_media_type_object, build_object_type, get_doc,
)
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import Direction
from netbox.api.fields import ChoiceField
from netbox.api.serializers import WritableNestedSerializer
@@ -277,3 +278,40 @@ class FixSerializedPKRelatedField(OpenApiSerializerFieldExtension):
return component.ref if component else None
else:
return build_basic_type(OpenApiTypes.INT)
class FixIntegerRangeSerializerSchema(OpenApiSerializerExtension):
target_class = 'netbox.api.fields.IntegerRangeSerializer'
def map_serializer(self, auto_schema: 'AutoSchema', direction: Direction) -> _SchemaType:
return {
'type': 'array',
'items': {
'type': 'array',
'items': {
'type': 'integer',
},
'minItems': 2,
'maxItems': 2,
},
}
# Nested models can be passed by ID in requests
# The logic for this is handled in `BaseModelSerializer.to_internal_value`
class FixWritableNestedSerializerAllowPK(OpenApiSerializerFieldExtension):
target_class = 'netbox.api.serializers.BaseModelSerializer'
match_subclasses = True
def map_serializer_field(self, auto_schema, direction):
schema = auto_schema._map_serializer_field(self.target, direction, bypass_extensions=True)
if schema is None:
return schema
if direction == 'request' and self.target.nested:
return {
'oneOf': [
build_basic_type(OpenApiTypes.INT),
schema,
]
}
return schema

View File

@@ -3,7 +3,10 @@ from django.conf import settings
from django.core.cache import cache
from django.db import models
from django.db.migrations.operations import AlterModelOptions
from django.utils.translation import gettext as _
from core.events import *
from netbox.events import EventType, EVENT_TYPE_KIND_DANGER, EVENT_TYPE_KIND_SUCCESS, EVENT_TYPE_KIND_WARNING
from utilities.migration import custom_deconstruct
# Ignore verbose_name & verbose_name_plural Meta options when calculating model migrations
@@ -26,6 +29,18 @@ class CoreConfig(AppConfig):
# Register models
register_models(*self.get_models())
# Register core events
EventType(OBJECT_CREATED, _('Object created')).register()
EventType(OBJECT_UPDATED, _('Object updated')).register()
EventType(OBJECT_DELETED, _('Object deleted'), destructive=True).register()
EventType(JOB_STARTED, _('Job started')).register()
EventType(JOB_COMPLETED, _('Job completed'), kind=EVENT_TYPE_KIND_SUCCESS).register()
EventType(JOB_FAILED, _('Job failed'), kind=EVENT_TYPE_KIND_WARNING).register()
EventType(JOB_ERRORED, _('Job errored'), kind=EVENT_TYPE_KIND_DANGER).register()
# Clear Redis cache on startup in development mode
if settings.DEBUG:
cache.clear()
try:
cache.clear()
except Exception:
pass

View File

@@ -81,8 +81,10 @@ class JobIntervalChoices(ChoiceSet):
CHOICES = (
(INTERVAL_MINUTELY, _('Minutely')),
(INTERVAL_HOURLY, _('Hourly')),
(INTERVAL_HOURLY * 12, _('12 hours')),
(INTERVAL_DAILY, _('Daily')),
(INTERVAL_WEEKLY, _('Weekly')),
(INTERVAL_DAILY * 30, _('30 days')),
)

View File

@@ -1,7 +1,3 @@
from django.utils.translation import gettext as _
from netbox.events import EventType, EVENT_TYPE_KIND_DANGER, EVENT_TYPE_KIND_SUCCESS, EVENT_TYPE_KIND_WARNING
__all__ = (
'JOB_COMPLETED',
'JOB_ERRORED',
@@ -22,12 +18,3 @@ JOB_STARTED = 'job_started'
JOB_COMPLETED = 'job_completed'
JOB_FAILED = 'job_failed'
JOB_ERRORED = 'job_errored'
# Register core events
EventType(OBJECT_CREATED, _('Object created')).register()
EventType(OBJECT_UPDATED, _('Object updated')).register()
EventType(OBJECT_DELETED, _('Object deleted'), destructive=True).register()
EventType(JOB_STARTED, _('Job started')).register()
EventType(JOB_COMPLETED, _('Job completed'), kind=EVENT_TYPE_KIND_SUCCESS).register()
EventType(JOB_FAILED, _('Job failed'), kind=EVENT_TYPE_KIND_WARNING).register()
EventType(JOB_ERRORED, _('Job errored'), kind=EVENT_TYPE_KIND_DANGER).register()

View File

@@ -62,6 +62,7 @@ class DataFileFilterForm(NetBoxModelFilterSetForm):
class JobFilterForm(SavedFiltersMixin, FilterForm):
model = Job
fieldsets = (
FieldSet('q', 'filter_id'),
FieldSet('object_type', 'status', name=_('Attributes')),
@@ -162,6 +163,7 @@ class ObjectChangeFilterForm(SavedFiltersMixin, FilterForm):
class ConfigRevisionFilterForm(SavedFiltersMixin, FilterForm):
model = ConfigRevision
fieldsets = (
FieldSet('q', 'filter_id'),
)

View File

@@ -1,8 +1,11 @@
import logging
import requests
import sys
from netbox.jobs import JobRunner
from django.conf import settings
from netbox.jobs import JobRunner, system_job
from netbox.search.backends import search_backend
from .choices import DataSourceStatusChoices
from .choices import DataSourceStatusChoices, JobIntervalChoices
from .exceptions import SyncError
from .models import DataSource
@@ -31,3 +34,44 @@ class SyncDataSourceJob(JobRunner):
if type(e) is SyncError:
logging.error(e)
raise e
@system_job(interval=JobIntervalChoices.INTERVAL_DAILY)
class SystemHousekeepingJob(JobRunner):
"""
Perform daily system housekeeping functions.
"""
class Meta:
name = "System Housekeeping"
def run(self, *args, **kwargs):
# Skip if running in development or test mode
if settings.DEBUG or 'test' in sys.argv:
return
# TODO: Migrate other housekeeping functions from the `housekeeping` management command.
self.send_census_report()
@staticmethod
def send_census_report():
"""
Send a census report (if enabled).
"""
# Skip if census reporting is disabled
if settings.ISOLATED_DEPLOYMENT or not settings.CENSUS_REPORTING_ENABLED:
return
census_data = {
'version': settings.RELEASE.full_version,
'python_version': sys.version.split()[0],
'deployment_id': settings.DEPLOYMENT_ID,
}
try:
requests.get(
url=settings.CENSUS_URL,
params=census_data,
timeout=3,
proxies=settings.HTTP_PROXIES
)
except requests.exceptions.RequestException:
pass

View File

@@ -1,11 +1,12 @@
import uuid
from functools import partial
import django_rq
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator
from django.db import models
from django.db import models, transaction
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import gettext as _
@@ -258,10 +259,12 @@ class Job(models.Model):
# Schedule the job to run at a specific date & time.
elif schedule_at:
queue.enqueue_at(schedule_at, func, job_id=str(job.job_id), job=job, **kwargs)
callback = partial(queue.enqueue_at, schedule_at, func, job_id=str(job.job_id), job=job, **kwargs)
transaction.on_commit(callback)
# Schedule the job to run asynchronously at this first available opportunity.
else:
queue.enqueue(func, job_id=str(job.job_id), job=job, **kwargs)
callback = partial(queue.enqueue, func, job_id=str(job.job_id), job=job, **kwargs)
transaction.on_commit(callback)
return job

View File

@@ -80,6 +80,13 @@ def get_local_plugins(plugins=None):
plugin = importlib.import_module(plugin_name)
plugin_config: PluginConfig = plugin.config
if plugin_config.author:
author = PluginAuthor(
name=plugin_config.author,
)
else:
author = None
local_plugins[plugin_config.name] = Plugin(
config_name=plugin_config.name,
title_short=plugin_config.verbose_name,
@@ -88,6 +95,7 @@ def get_local_plugins(plugins=None):
description_short=plugin_config.description,
is_local=True,
is_installed=True,
author=author,
installed_version=plugin_config.version,
)

View File

@@ -165,7 +165,7 @@ class DataFileBulkDeleteView(generic.BulkDeleteView):
@register_model_view(Job, 'list', path='', detail=False)
class JobListView(generic.ObjectListView):
queryset = Job.objects.all()
queryset = Job.objects.defer('data')
filterset = filtersets.JobFilterSet
filterset_form = forms.JobFilterForm
table = tables.JobTable
@@ -182,12 +182,12 @@ class JobView(generic.ObjectView):
@register_model_view(Job, 'delete')
class JobDeleteView(generic.ObjectDeleteView):
queryset = Job.objects.all()
queryset = Job.objects.defer('data')
@register_model_view(Job, 'bulk_delete', path='delete', detail=False)
class JobBulkDeleteView(generic.BulkDeleteView):
queryset = Job.objects.all()
queryset = Job.objects.defer('data')
filterset = filtersets.JobFilterSet
table = tables.JobTable
@@ -570,8 +570,9 @@ class SystemView(UserPassesTestMixin, View):
return response
# Serialize any CustomValidator classes
if hasattr(config, 'CUSTOM_VALIDATORS') and config.CUSTOM_VALIDATORS:
config.CUSTOM_VALIDATORS = json.dumps(config.CUSTOM_VALIDATORS, cls=ConfigJSONEncoder, indent=4)
for attr in ['CUSTOM_VALIDATORS', 'PROTECTION_RULES']:
if hasattr(config, attr) and getattr(config, attr, None):
setattr(config, attr, json.dumps(getattr(config, attr), cls=ConfigJSONEncoder, indent=4))
return render(request, 'core/system.html', {
'stats': stats,
@@ -594,7 +595,7 @@ class BasePluginView(UserPassesTestMixin, View):
catalog_plugins_error = cache.get(self.CACHE_KEY_CATALOG_ERROR, default=False)
if not catalog_plugins_error:
catalog_plugins = get_catalog_plugins()
if not catalog_plugins:
if not catalog_plugins and not settings.ISOLATED_DEPLOYMENT:
# Cache for 5 minutes to avoid spamming connection
cache.set(self.CACHE_KEY_CATALOG_ERROR, True, 300)
messages.warning(request, _("Plugins catalog could not be loaded"))

View File

@@ -1,3 +1,4 @@
from django.utils.translation import gettext as _
from django.contrib.contenttypes.models import ContentType
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
@@ -232,8 +233,56 @@ class InterfaceSerializer(NetBoxModelSerializer, CabledObjectSerializer, Connect
def validate(self, data):
# Validate many-to-many VLAN assignments
if not self.nested:
# Validate 802.1q mode and vlan(s)
mode = None
tagged_vlans = []
# Gather Information
if self.instance:
mode = data.get('mode') if 'mode' in data.keys() else self.instance.mode
untagged_vlan = data.get('untagged_vlan') if 'untagged_vlan' in data.keys() else \
self.instance.untagged_vlan
qinq_svlan = data.get('qinq_svlan') if 'qinq_svlan' in data.keys() else \
self.instance.qinq_svlan
tagged_vlans = data.get('tagged_vlans') if 'tagged_vlans' in data.keys() else \
self.instance.tagged_vlans.all()
else:
mode = data.get('mode', None)
untagged_vlan = data.get('untagged_vlan') if 'untagged_vlan' in data.keys() else None
qinq_svlan = data.get('qinq_svlan') if 'qinq_svlan' in data.keys() else None
tagged_vlans = data.get('tagged_vlans') if 'tagged_vlans' in data.keys() else None
errors = {}
# Non Q-in-Q mode with service vlan set
if mode != InterfaceModeChoices.MODE_Q_IN_Q and qinq_svlan:
errors.update({
'qinq_svlan': _("Interface mode does not support q-in-q service vlan")
})
# Routed mode
if not mode:
# Untagged vlan
if untagged_vlan:
errors.update({
'untagged_vlan': _("Interface mode does not support untagged vlan")
})
# Tagged vlan
if tagged_vlans:
errors.update({
'tagged_vlans': _("Interface mode does not support tagged vlans")
})
# Non-tagged mode
elif mode in (InterfaceModeChoices.MODE_TAGGED_ALL, InterfaceModeChoices.MODE_ACCESS) and tagged_vlans:
errors.update({
'tagged_vlans': _("Interface mode does not support tagged vlans")
})
if errors:
raise serializers.ValidationError(errors)
# Validate many-to-many VLAN assignments
device = self.instance.device if self.instance else data.get('device')
for vlan in data.get('tagged_vlans', []):
if vlan.site not in [device.site, None]:

View File

@@ -170,8 +170,8 @@ class MACAddressSerializer(NetBoxModelSerializer):
class Meta:
model = MACAddress
fields = [
'id', 'url', 'display_url', 'display', 'mac_address', 'assigned_object_type', 'assigned_object',
'description', 'comments',
'id', 'url', 'display_url', 'display', 'mac_address', 'assigned_object_type', 'assigned_object_id',
'assigned_object', 'description', 'comments', 'tags', 'custom_fields', 'created', 'last_updated',
]
brief_fields = ('id', 'url', 'display', 'mac_address', 'description')

View File

@@ -1,3 +1,4 @@
from django.contrib.contenttypes.prefetch import GenericPrefetch
from django.http import Http404, HttpResponse
from django.shortcuts import get_object_or_404
from drf_spectacular.types import OpenApiTypes
@@ -442,7 +443,18 @@ class PowerOutletViewSet(PathEndpointMixin, NetBoxModelViewSet):
class InterfaceViewSet(PathEndpointMixin, NetBoxModelViewSet):
queryset = Interface.objects.prefetch_related(
'_path', 'cable__terminations',
GenericPrefetch(
"cable__terminations__termination",
[
Interface.objects.select_related("device", "cable"),
],
),
GenericPrefetch(
"_path__path_objects",
[
Interface.objects.select_related("device", "cable"),
],
),
'l2vpn_terminations', # Referenced by InterfaceSerializer.l2vpn_termination
'ip_addresses', # Referenced by Interface.count_ipaddresses()
'fhrp_group_assignments', # Referenced by Interface.count_fhrp_groups()

View File

@@ -53,10 +53,10 @@ class ScopedFilterSet(BaseFilterSet):
label=_('Site (slug)'),
)
location_id = TreeNodeMultipleChoiceFilter(
queryset=Location.objects.all(),
field_name='_location',
lookup_expr='in',
label=_('Location (ID)'),
queryset=Location.objects.all(),
field_name='_location',
lookup_expr='in',
label=_('Location (ID)'),
)
location = TreeNodeMultipleChoiceFilter(
queryset=Location.objects.all(),

View File

@@ -986,6 +986,7 @@ class InterfaceTypeChoices(ChoiceSet):
# Coaxial
TYPE_DOCSIS = 'docsis'
TYPE_MOCA = 'moca'
# PON
TYPE_BPON = 'bpon'
@@ -1182,6 +1183,7 @@ class InterfaceTypeChoices(ChoiceSet):
_('Coaxial'),
(
(TYPE_DOCSIS, 'DOCSIS'),
(TYPE_MOCA, 'MoCA'),
)
),
(
@@ -1345,6 +1347,9 @@ class PortTypeChoices(ChoiceSet):
TYPE_SC_UPC = 'sc-upc'
TYPE_SC_APC = 'sc-apc'
TYPE_FC = 'fc'
TYPE_FC_PC = 'fc-pc'
TYPE_FC_UPC = 'fc-upc'
TYPE_FC_APC = 'fc-apc'
TYPE_LC = 'lc'
TYPE_LC_PC = 'lc-pc'
TYPE_LC_UPC = 'lc-upc'
@@ -1405,6 +1410,9 @@ class PortTypeChoices(ChoiceSet):
_('Fiber Optic'),
(
(TYPE_FC, 'FC'),
(TYPE_FC_PC, 'FC/PC'),
(TYPE_FC_UPC, 'FC/UPC'),
(TYPE_FC_APC, 'FC/APC'),
(TYPE_LC, 'LC'),
(TYPE_LC_PC, 'LC/PC'),
(TYPE_LC_UPC, 'LC/UPC'),

View File

@@ -0,0 +1,2 @@
class UnsupportedCablePath(Exception):
pass

View File

@@ -1057,6 +1057,13 @@ class DeviceFilterSet(
lookup_expr='in',
label=_('Location (ID)'),
)
location = TreeNodeMultipleChoiceFilter(
queryset=Location.objects.all(),
field_name='location',
lookup_expr='in',
to_field_name='slug',
label=_('Location (slug)'),
)
rack_id = django_filters.ModelMultipleChoiceFilter(
field_name='rack',
queryset=Rack.objects.all(),
@@ -1193,6 +1200,7 @@ class DeviceFilterSet(
return queryset
return queryset.filter(
Q(name__icontains=value) |
Q(virtual_chassis__name__icontains=value) |
Q(serial__icontains=value.strip()) |
Q(inventoryitems__serial__icontains=value.strip()) |
Q(asset_tag__icontains=value.strip()) |
@@ -1652,8 +1660,8 @@ class MACAddressFilterSet(NetBoxModelFilterSet):
if not value.strip():
return queryset
qs_filter = (
Q(mac_address__icontains=value) |
Q(description__icontains=value)
Q(mac_address__icontains=value) |
Q(description__icontains=value)
)
return queryset.filter(qs_filter)
@@ -1681,6 +1689,10 @@ class MACAddressFilterSet(NetBoxModelFilterSet):
class CommonInterfaceFilterSet(django_filters.FilterSet):
mode = django_filters.MultipleChoiceFilter(
choices=InterfaceModeChoices,
label=_('802.1Q Mode')
)
vlan_id = django_filters.CharFilter(
method='filter_vlan_id',
label=_('Assigned VLAN')

View File

@@ -1411,7 +1411,7 @@ class InterfaceBulkEditForm(
form_from_model(Interface, [
'label', 'type', 'parent', 'bridge', 'lag', 'speed', 'duplex', 'wwn', 'mtu', 'mgmt_only', 'mark_connected',
'description', 'mode', 'rf_role', 'rf_channel', 'rf_channel_frequency', 'rf_channel_width', 'tx_power',
'wireless_lans'
'wireless_lans', 'vlan_translation_policy'
])
):
enabled = forms.NullBooleanField(
@@ -1564,7 +1564,9 @@ class InterfaceBulkEditForm(
FieldSet('vdcs', 'mtu', 'tx_power', 'enabled', 'mgmt_only', 'mark_connected', name=_('Operation')),
FieldSet('poe_mode', 'poe_type', name=_('PoE')),
FieldSet('parent', 'bridge', 'lag', name=_('Related Interfaces')),
FieldSet('mode', 'vlan_group', 'untagged_vlan', 'qinq_svlan', name=_('802.1Q Switching')),
FieldSet(
'mode', 'vlan_group', 'untagged_vlan', 'qinq_svlan', 'vlan_translation_policy', name=_('802.1Q Switching')
),
FieldSet(
TabbedGroups(
FieldSet('tagged_vlans', name=_('Assignment')),
@@ -1579,7 +1581,7 @@ class InterfaceBulkEditForm(
nullable_fields = (
'module', 'label', 'parent', 'bridge', 'lag', 'speed', 'duplex', 'wwn', 'vdcs', 'mtu', 'description',
'poe_mode', 'poe_type', 'mode', 'rf_channel', 'rf_channel_frequency', 'rf_channel_width', 'tx_power',
'untagged_vlan', 'tagged_vlans', 'qinq_svlan', 'vrf', 'wireless_lans'
'untagged_vlan', 'tagged_vlans', 'qinq_svlan', 'vrf', 'wireless_lans', 'vlan_translation_policy',
)
def __init__(self, *args, **kwargs):

View File

@@ -1161,27 +1161,45 @@ class InventoryItemImportForm(NetBoxModelImportForm):
else:
self.fields['parent'].queryset = InventoryItem.objects.none()
def clean_component_name(self):
content_type = self.cleaned_data.get('component_type')
component_name = self.cleaned_data.get('component_name')
def clean(self):
super().clean()
cleaned_data = self.cleaned_data
component_type = cleaned_data.get('component_type')
component_name = cleaned_data.get('component_name')
device = self.cleaned_data.get("device")
if not device and hasattr(self, 'instance') and hasattr(self.instance, 'device'):
device = self.instance.device
if not all([device, content_type, component_name]):
return None
model = content_type.model_class()
try:
component = model.objects.get(device=device, name=component_name)
self.instance.component = component
except ObjectDoesNotExist:
raise forms.ValidationError(
_("Component not found: {device} - {component_name}").format(
device=device, component_name=component_name
if component_type:
if device is None:
cleaned_data.pop('component_type', None)
if component_name is None:
cleaned_data.pop('component_type', None)
raise forms.ValidationError(
_("Component name must be specified when component type is specified")
)
)
if all([device, component_name]):
try:
model = component_type.model_class()
self.instance.component = model.objects.get(device=device, name=component_name)
except ObjectDoesNotExist:
cleaned_data.pop('component_type', None)
cleaned_data.pop('component_name', None)
raise forms.ValidationError(
_("Component not found: {device} - {component_name}").format(
device=device, component_name=component_name
)
)
else:
cleaned_data.pop('component_type', None)
if not component_name:
raise forms.ValidationError(
_("Component name must be specified when component type is specified")
)
else:
if component_name:
raise forms.ValidationError(
_("Component type must be specified when component name is specified")
)
return cleaned_data
#

View File

@@ -43,20 +43,14 @@ class InterfaceCommonForm(forms.Form):
super().clean()
parent_field = 'device' if 'device' in self.cleaned_data else 'virtual_machine'
tagged_vlans = self.cleaned_data.get('tagged_vlans')
# Untagged interfaces cannot be assigned tagged VLANs
if self.cleaned_data['mode'] == InterfaceModeChoices.MODE_ACCESS and tagged_vlans:
raise forms.ValidationError({
'mode': _("An access interface cannot have tagged VLANs assigned.")
})
# Remove all tagged VLAN assignments from "tagged all" interfaces
elif self.cleaned_data['mode'] == InterfaceModeChoices.MODE_TAGGED_ALL:
self.cleaned_data['tagged_vlans'] = []
if 'tagged_vlans' in self.fields.keys():
tagged_vlans = self.cleaned_data.get('tagged_vlans') if self.is_bound else \
self.get_initial_for_field(self.fields['tagged_vlans'], 'tagged_vlans')
else:
tagged_vlans = []
# Validate tagged VLANs; must be a global VLAN or in the same site
elif self.cleaned_data['mode'] == InterfaceModeChoices.MODE_TAGGED and tagged_vlans:
if self.cleaned_data['mode'] == InterfaceModeChoices.MODE_TAGGED and tagged_vlans:
valid_sites = [None, self.cleaned_data[parent_field].site]
invalid_vlans = [str(v) for v in tagged_vlans if v.site not in valid_sites]

View File

@@ -6,7 +6,7 @@ from dcim.constants import *
from dcim.models import *
from extras.forms import LocalConfigContextFilterForm
from extras.models import ConfigTemplate
from ipam.models import ASN, VRF
from ipam.models import ASN, VRF, VLANTranslationPolicy
from netbox.choices import *
from netbox.forms import NetBoxModelFilterSetForm
from tenancy.forms import ContactModelFilterForm, TenancyFilterForm
@@ -303,7 +303,7 @@ class RackTypeFilterForm(RackBaseFilterForm):
model = RackType
fieldsets = (
FieldSet('q', 'filter_id', 'tag'),
FieldSet('form_factor', 'width', 'u_height', name=_('Rack Type')),
FieldSet('manufacturer_id', 'form_factor', 'width', 'u_height', name=_('Rack Type')),
FieldSet('starting_unit', 'desc_units', name=_('Numbering')),
FieldSet('weight', 'max_weight', 'weight_unit', name=_('Weight')),
)
@@ -1332,6 +1332,7 @@ class InterfaceFilterForm(PathEndpointFilterForm, DeviceComponentFilterForm):
FieldSet('name', 'label', 'kind', 'type', 'speed', 'duplex', 'enabled', 'mgmt_only', name=_('Attributes')),
FieldSet('vrf_id', 'l2vpn_id', 'mac_address', 'wwn', name=_('Addressing')),
FieldSet('poe_mode', 'poe_type', name=_('PoE')),
FieldSet('mode', 'vlan_translation_policy_id', name=_('802.1Q Switching')),
FieldSet('rf_role', 'rf_channel', 'rf_channel_width', 'tx_power', name=_('Wireless')),
FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', 'rack_id', name=_('Location')),
FieldSet(
@@ -1403,6 +1404,16 @@ class InterfaceFilterForm(PathEndpointFilterForm, DeviceComponentFilterForm):
required=False,
label=_('PoE type')
)
mode = forms.MultipleChoiceField(
choices=InterfaceModeChoices,
required=False,
label=_('802.1Q mode')
)
vlan_translation_policy_id = DynamicModelMultipleChoiceField(
queryset=VLANTranslationPolicy.objects.all(),
required=False,
label=_('VLAN Translation Policy')
)
rf_role = forms.MultipleChoiceField(
choices=WirelessRoleChoices,
required=False,

View File

@@ -1810,6 +1810,11 @@ class MACAddressForm(NetBoxModelForm):
super().__init__(*args, **kwargs)
if instance and instance.assigned_object and instance.assigned_object.primary_mac_address:
if instance.assigned_object.primary_mac_address.pk == instance.pk:
self.fields['interface'].disabled = True
self.fields['vminterface'].disabled = True
def clean(self):
super().clean()

View File

@@ -55,19 +55,23 @@ class ComponentCreateForm(forms.Form):
def clean(self):
super().clean()
# Validate that all replication fields generate an equal number of values
# Validate that all replication fields generate an equal number of values (or a single value)
if not (patterns := self.cleaned_data.get(self.replication_fields[0])):
return
pattern_count = len(patterns)
for field_name in self.replication_fields:
value_count = len(self.cleaned_data[field_name])
if self.cleaned_data[field_name] and value_count != pattern_count:
raise forms.ValidationError({
field_name: _(
"The provided pattern specifies {value_count} values, but {pattern_count} are expected."
).format(value_count=value_count, pattern_count=pattern_count)
}, code='label_pattern_mismatch')
if self.cleaned_data[field_name]:
if value_count == 1:
# If the field resolves to a single value (because no pattern was used), multiply it by the number
# of expected values. This allows us to reuse the same label when creating multiple components.
self.cleaned_data[field_name] = self.cleaned_data[field_name] * pattern_count
elif value_count != pattern_count:
raise forms.ValidationError({
field_name: _(
"The provided pattern specifies {value_count} values, but {pattern_count} are expected."
).format(value_count=value_count, pattern_count=pattern_count)
}, code='label_pattern_mismatch')
#
@@ -153,6 +157,7 @@ class FrontPortTemplateCreateForm(ComponentCreateForm, model_forms.FrontPortTemp
self.fields['rear_port'].choices = choices
def clean(self):
super().clean()
# Check that the number of FrontPortTemplates to be created matches the selected number of RearPortTemplate
# positions
@@ -302,6 +307,7 @@ class FrontPortCreateForm(ComponentCreateForm, model_forms.FrontPortForm):
self.fields['rear_port'].choices = choices
def clean(self):
super().clean()
# Check that the number of FrontPorts to be created matches the selected number of RearPort positions
frontport_count = len(self.cleaned_data['name'])
@@ -402,6 +408,7 @@ class VirtualChassisCreateForm(NetBoxModelForm):
queryset=Device.objects.all(),
required=False,
query_params={
'virtual_chassis_id': 'null',
'site_id': '$site',
'rack_id': '$rack',
}

View File

@@ -30,6 +30,7 @@ class PathEndpointMixin:
connected_endpoints: List[Annotated[Union[
Annotated["CircuitTerminationType", strawberry.lazy('circuits.graphql.types')], # noqa: F821
Annotated["VirtualCircuitTerminationType", strawberry.lazy('circuits.graphql.types')], # noqa: F821
Annotated["ConsolePortType", strawberry.lazy('dcim.graphql.types')], # noqa: F821
Annotated["ConsoleServerPortType", strawberry.lazy('dcim.graphql.types')], # noqa: F821
Annotated["FrontPortType", strawberry.lazy('dcim.graphql.types')], # noqa: F821

View File

@@ -429,7 +429,7 @@ class InterfaceTemplateType(ModularComponentTemplateType):
)
class InventoryItemType(ComponentType):
role: Annotated["InventoryItemRoleType", strawberry.lazy('dcim.graphql.types')] | None
manufacturer: Annotated["ManufacturerType", strawberry.lazy('dcim.graphql.types')]
manufacturer: Annotated["ManufacturerType", strawberry.lazy('dcim.graphql.types')] | None
child_items: List[Annotated["InventoryItemType", strawberry.lazy('dcim.graphql.types')]]

View File

@@ -1,5 +1,4 @@
import itertools
from collections import defaultdict
from django.contrib.contenttypes.fields import GenericForeignKey
from django.core.exceptions import ValidationError
@@ -15,7 +14,8 @@ from dcim.fields import PathField
from dcim.utils import decompile_path_node, object_to_path_node
from netbox.models import ChangeLoggedModel, PrimaryModel
from utilities.conversion import to_meters
from utilities.fields import ColorField
from utilities.exceptions import AbortRequest
from utilities.fields import ColorField, GenericArrayForeignKey
from utilities.querysets import RestrictedQuerySet
from wireless.models import WirelessLink
from .device_components import FrontPort, RearPort, PathEndpoint
@@ -26,6 +26,7 @@ __all__ = (
'CableTermination',
)
from ..exceptions import UnsupportedCablePath
trace_paths = Signal()
@@ -236,8 +237,10 @@ class Cable(PrimaryModel):
for termination in self.b_terminations:
if not termination.pk or termination not in b_terminations:
CableTermination(cable=self, cable_end='B', termination=termination).save()
trace_paths.send(Cable, instance=self, created=_created)
try:
trace_paths.send(Cable, instance=self, created=_created)
except UnsupportedCablePath as e:
raise AbortRequest(e)
def get_status_color(self):
return LinkStatusChoices.colors.get(self.status)
@@ -490,13 +493,16 @@ class CablePath(models.Model):
return ObjectType.objects.get_for_id(ct_id)
@property
def path_objects(self):
"""
Cache and return the complete path as lists of objects, derived from their annotation within the path.
"""
if not hasattr(self, '_path_objects'):
self._path_objects = self._get_path()
return self._path_objects
def _path_decompiled(self):
res = []
for step in self.path:
nodes = []
for node in step:
nodes.append(decompile_path_node(node))
res.append(nodes)
return res
path_objects = GenericArrayForeignKey("_path_decompiled")
@property
def origins(self):
@@ -531,8 +537,8 @@ class CablePath(models.Model):
return None
# Ensure all originating terminations are attached to the same link
if len(terminations) > 1:
assert all(t.link == terminations[0].link for t in terminations[1:])
if len(terminations) > 1 and not all(t.link == terminations[0].link for t in terminations[1:]):
raise UnsupportedCablePath(_("All originating terminations must be attached to the same link"))
path = []
position_stack = []
@@ -543,12 +549,13 @@ class CablePath(models.Model):
while terminations:
# Terminations must all be of the same type
assert all(isinstance(t, type(terminations[0])) for t in terminations[1:])
if not all(isinstance(t, type(terminations[0])) for t in terminations[1:]):
raise UnsupportedCablePath(_("All mid-span terminations must have the same termination type"))
# All mid-span terminations must all be attached to the same device
if not isinstance(terminations[0], PathEndpoint):
assert all(isinstance(t, type(terminations[0])) for t in terminations[1:])
assert all(t.parent_object == terminations[0].parent_object for t in terminations[1:])
if (not isinstance(terminations[0], PathEndpoint) and not
all(t.parent_object == terminations[0].parent_object for t in terminations[1:])):
raise UnsupportedCablePath(_("All mid-span terminations must have the same parent object"))
# Check for a split path (e.g. rear port fanning out to multiple front ports with
# different cables attached)
@@ -571,8 +578,10 @@ class CablePath(models.Model):
return None
# Otherwise, halt the trace if no link exists
break
assert all(type(link) in (Cable, WirelessLink) for link in links)
assert all(isinstance(link, type(links[0])) for link in links)
if not all(type(link) in (Cable, WirelessLink) for link in links):
raise UnsupportedCablePath(_("All links must be cable or wireless"))
if not all(isinstance(link, type(links[0])) for link in links):
raise UnsupportedCablePath(_("All links must match first link type"))
# Step 3: Record asymmetric paths as split
not_connected_terminations = [termination.link for termination in terminations if termination.link is None]
@@ -653,14 +662,18 @@ class CablePath(models.Model):
positions = position_stack.pop()
# Ensure we have a number of positions equal to the amount of remote terminations
assert len(remote_terminations) == len(positions)
if len(remote_terminations) != len(positions):
raise UnsupportedCablePath(
_("All positions counts within the path on opposite ends of links must match")
)
# Get our front ports
q_filter = Q()
for rt in remote_terminations:
position = positions.pop()
q_filter |= Q(rear_port_id=rt.pk, rear_port_position=position)
assert q_filter is not Q()
if q_filter is Q():
raise UnsupportedCablePath(_("Remote termination position filter is missing"))
front_ports = FrontPort.objects.filter(q_filter)
# Obtain the individual front ports based on the termination and position
elif position_stack:
@@ -746,42 +759,6 @@ class CablePath(models.Model):
self.delete()
retrace.alters_data = True
def _get_path(self):
"""
Return the path as a list of prefetched objects.
"""
# Compile a list of IDs to prefetch for each type of model in the path
to_prefetch = defaultdict(list)
for node in self._nodes:
ct_id, object_id = decompile_path_node(node)
to_prefetch[ct_id].append(object_id)
# Prefetch path objects using one query per model type. Prefetch related devices where appropriate.
prefetched = {}
for ct_id, object_ids in to_prefetch.items():
model_class = ObjectType.objects.get_for_id(ct_id).model_class()
queryset = model_class.objects.filter(pk__in=object_ids)
if hasattr(model_class, 'device'):
queryset = queryset.prefetch_related('device')
prefetched[ct_id] = {
obj.id: obj for obj in queryset
}
# Replicate the path using the prefetched objects.
path = []
for step in self.path:
nodes = []
for node in step:
ct_id, object_id = decompile_path_node(node)
try:
nodes.append(prefetched[ct_id][object_id])
except KeyError:
# Ignore stale (deleted) object IDs
pass
path.append(nodes)
return path
def get_cable_ids(self):
"""
Return all Cable IDs within the path.

View File

@@ -184,8 +184,11 @@ class CabledObjectModel(models.Model):
@cached_property
def link_peers(self):
if self.cable:
peers = self.cable.terminations.exclude(cable_end=self.cable_end).prefetch_related('termination')
return [peer.termination for peer in peers]
return [
peer.termination
for peer in self.cable.terminations.all()
if peer.cable_end != self.cable_end
]
return []
@property
@@ -934,6 +937,8 @@ class Interface(ModularComponentModel, BaseInterface, CabledObjectModel, PathEnd
raise ValidationError({'rf_channel_width': _("Cannot specify custom width with channel selected.")})
# VLAN validation
if not self.mode and self.untagged_vlan:
raise ValidationError({'untagged_vlan': _("Interface mode does not support an untagged vlan.")})
# Validate untagged VLAN
if self.untagged_vlan and self.untagged_vlan.site not in [self.device.site, None]:

View File

@@ -15,6 +15,7 @@ from django.urls import reverse
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from core.models import ObjectType
from dcim.choices import *
from dcim.constants import *
from dcim.fields import MACAddressField
@@ -801,14 +802,10 @@ class Device(
verbose_name_plural = _('devices')
def __str__(self):
if self.name and self.asset_tag:
return f'{self.name} ({self.asset_tag})'
elif self.name:
return self.name
elif self.virtual_chassis and self.asset_tag:
return f'{self.virtual_chassis.name}:{self.vc_position} ({self.asset_tag})'
elif self.virtual_chassis:
return f'{self.virtual_chassis.name}:{self.vc_position} ({self.pk})'
if self.label and self.asset_tag:
return f'{self.label} ({self.asset_tag})'
elif self.label:
return self.label
elif self.device_type and self.asset_tag:
return f'{self.device_type.manufacturer} {self.device_type.model} ({self.asset_tag})'
elif self.device_type:
@@ -1072,14 +1069,22 @@ class Device(
device.location = self.location
device.save()
@property
def label(self):
"""
Return the device name if set; otherwise return a generated name if available.
"""
if self.name:
return self.name
if self.virtual_chassis:
return f'{self.virtual_chassis.name}:{self.vc_position}'
@property
def identifier(self):
"""
Return the device name if set; otherwise return the Device's primary key as {pk}
"""
if self.name is not None:
return self.name
return '{{{}}}'.format(self.pk)
return self.label or '{{{}}}'.format(self.pk)
@property
def primary_ip(self):
@@ -1297,6 +1302,7 @@ class Module(PrimaryModel, ConfigContextModel):
else:
# ModuleBays must be saved individually for MPTT
for instance in create_instances:
instance.name = instance.name.replace(MODULE_TOKEN, str(self.module_bay.position))
instance.save()
update_fields = ['module']
@@ -1522,3 +1528,37 @@ class MACAddress(PrimaryModel):
def __str__(self):
return str(self.mac_address)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Denote the original assigned object (if any) for validation in clean()
self._original_assigned_object_id = self.__dict__.get('assigned_object_id')
self._original_assigned_object_type_id = self.__dict__.get('assigned_object_type_id')
@cached_property
def is_primary(self):
if self.assigned_object and hasattr(self.assigned_object, 'primary_mac_address'):
if self.assigned_object.primary_mac_address and self.assigned_object.primary_mac_address.pk == self.pk:
return True
return False
def clean(self, *args, **kwargs):
super().clean()
if self._original_assigned_object_id and self._original_assigned_object_type_id:
assigned_object = self.assigned_object
ct = ObjectType.objects.get_for_id(self._original_assigned_object_type_id)
original_assigned_object = ct.get_object_for_this_type(pk=self._original_assigned_object_id)
if (
original_assigned_object.primary_mac_address
and original_assigned_object.primary_mac_address.pk == self.pk
):
if not assigned_object:
raise ValidationError(
_("Cannot unassign MAC Address while it is designated as the primary MAC for an object")
)
elif original_assigned_object != assigned_object:
raise ValidationError(
_("Cannot reassign MAC Address while it is designated as the primary MAC for an object")
)

View File

@@ -374,22 +374,27 @@ class Rack(ContactsMixin, ImageAttachmentsMixin, RackBase):
if not self._state.adding:
mounted_devices = Device.objects.filter(rack=self).exclude(position__isnull=True).order_by('position')
effective_u_height = self.rack_type.u_height if self.rack_type else self.u_height
effective_starting_unit = self.rack_type.starting_unit if self.rack_type else self.starting_unit
# Validate that Rack is tall enough to house the highest mounted Device
if top_device := mounted_devices.last():
min_height = top_device.position + top_device.device_type.u_height - self.starting_unit
if self.u_height < min_height:
min_height = top_device.position + top_device.device_type.u_height - effective_starting_unit
if effective_u_height < min_height:
field = 'rack_type' if self.rack_type else 'u_height'
raise ValidationError({
'u_height': _(
field: _(
"Rack must be at least {min_height}U tall to house currently installed devices."
).format(min_height=min_height)
})
# Validate that the Rack's starting unit is less than or equal to the position of the lowest mounted Device
if last_device := mounted_devices.first():
if self.starting_unit > last_device.position:
if effective_starting_unit > last_device.position:
field = 'rack_type' if self.rack_type else 'starting_unit'
raise ValidationError({
'starting_unit': _("Rack unit numbering must begin at {position} or less to house "
"currently installed devices.").format(position=last_device.position)
field: _("Rack unit numbering must begin at {position} or less to house "
"currently installed devices.").format(position=last_device.position)
})
# Validate that Rack was assigned a Location of its same site, if applicable

View File

@@ -44,6 +44,7 @@ class DeviceIndex(SearchIndex):
('asset_tag', 50),
('serial', 60),
('name', 100),
('virtual_chassis', 200),
('description', 500),
('comments', 5000),
)

View File

@@ -225,8 +225,7 @@ class CableTraceSVG:
"""
nodes_height = 0
nodes = []
# Sort them by name to make renders more readable
for i, term in enumerate(sorted(terminations, key=lambda x: str(x))):
for i, term in enumerate(terminations):
node = Node(
position=(offset_x + i * width, self.cursor),
width=width,

View File

@@ -30,10 +30,8 @@ STROKE_RESERVED = '#4d4dff'
def get_device_name(device):
if device.virtual_chassis:
name = f'{device.virtual_chassis.name}:{device.vc_position}'
elif device.name:
name = device.name
if device.label:
name = device.label
else:
name = str(device.device_type)
if device.devicebay_count:

View File

@@ -144,7 +144,7 @@ class DeviceTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable):
name = tables.TemplateColumn(
verbose_name=_('Name'),
template_code=DEVICE_LINK,
linkify=True
linkify=True,
)
status = columns.ChoiceFieldColumn(
verbose_name=_('Status'),
@@ -671,7 +671,7 @@ class InterfaceTable(BaseInterfaceTable, ModularDeviceComponentTable, PathEndpoi
'rf_role', 'rf_channel', 'rf_channel_frequency', 'rf_channel_width', 'tx_power', 'description',
'mark_connected', 'cable', 'cable_color', 'wireless_link', 'wireless_lans', 'link_peer', 'connection',
'tags', 'vdcs', 'vrf', 'l2vpn', 'tunnel', 'ip_addresses', 'fhrp_groups', 'untagged_vlan', 'tagged_vlans',
'qinq_svlan', 'inventory_items', 'created', 'last_updated',
'qinq_svlan', 'inventory_items', 'created', 'last_updated', 'vlan_translation_policy'
)
default_columns = ('pk', 'name', 'device', 'label', 'enabled', 'type', 'description')
@@ -705,7 +705,7 @@ class DeviceInterfaceTable(InterfaceTable):
model = models.Interface
fields = (
'pk', 'id', 'name', 'module_bay', 'module', 'label', 'enabled', 'type', 'parent', 'bridge', 'lag',
'mgmt_only', 'mtu', 'mode', 'mac_address', 'wwn', 'rf_role', 'rf_channel', 'rf_channel_frequency',
'mgmt_only', 'mtu', 'mode', 'primary_mac_address', 'wwn', 'rf_role', 'rf_channel', 'rf_channel_frequency',
'rf_channel_width', 'tx_power', 'description', 'mark_connected', 'cable', 'cable_color', 'wireless_link',
'wireless_lans', 'link_peer', 'connection', 'tags', 'vdcs', 'vrf', 'l2vpn', 'tunnel', 'ip_addresses',
'fhrp_groups', 'untagged_vlan', 'tagged_vlans', 'qinq_svlan', 'actions',

View File

@@ -31,6 +31,11 @@ class ManufacturerTable(ContactsColumnMixin, NetBoxTable):
verbose_name=_('Name'),
linkify=True
)
racktype_count = columns.LinkedCountColumn(
viewname='dcim:racktype_list',
url_params={'manufacturer_id': 'pk'},
verbose_name=_('Rack Types')
)
devicetype_count = columns.LinkedCountColumn(
viewname='dcim:devicetype_list',
url_params={'manufacturer_id': 'pk'},
@@ -58,12 +63,12 @@ class ManufacturerTable(ContactsColumnMixin, NetBoxTable):
class Meta(NetBoxTable.Meta):
model = models.Manufacturer
fields = (
'pk', 'id', 'name', 'devicetype_count', 'moduletype_count', 'inventoryitem_count', 'platform_count',
'description', 'slug', 'tags', 'contacts', 'actions', 'created', 'last_updated',
'pk', 'id', 'name', 'racktype_count', 'devicetype_count', 'moduletype_count', 'inventoryitem_count',
'platform_count', 'description', 'slug', 'tags', 'contacts', 'actions', 'created', 'last_updated',
)
default_columns = (
'pk', 'name', 'devicetype_count', 'moduletype_count', 'inventoryitem_count', 'platform_count',
'description', 'slug',
'pk', 'name', 'racktype_count', 'devicetype_count', 'moduletype_count', 'inventoryitem_count',
'platform_count', 'description', 'slug',
)

View File

@@ -94,7 +94,6 @@ class SiteTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable):
verbose_name=_('ASNs')
)
asn_count = columns.LinkedCountColumn(
accessor=tables.A('asns__count'),
viewname='ipam:asn_list',
url_params={'site_id': 'pk'},
verbose_name=_('ASN Count')
@@ -147,6 +146,11 @@ class LocationTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable):
url_params={'location_id': 'pk'},
verbose_name=_('Devices')
)
vlangroup_count = columns.LinkedCountColumn(
viewname='ipam:vlangroup_list',
url_params={'location': 'pk'},
verbose_name=_('VLAN Groups')
)
tags = columns.TagColumn(
url_name='dcim:location_list'
)
@@ -158,8 +162,9 @@ class LocationTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable):
model = Location
fields = (
'pk', 'id', 'name', 'site', 'status', 'facility', 'tenant', 'tenant_group', 'rack_count', 'device_count',
'description', 'slug', 'contacts', 'tags', 'actions', 'created', 'last_updated',
'description', 'slug', 'contacts', 'tags', 'actions', 'created', 'last_updated', 'vlangroup_count',
)
default_columns = (
'pk', 'name', 'site', 'status', 'facility', 'tenant', 'rack_count', 'device_count', 'description'
'pk', 'name', 'site', 'status', 'facility', 'tenant', 'rack_count', 'device_count', 'vlangroup_count',
'description'
)

View File

@@ -35,7 +35,7 @@ WEIGHT = """
"""
DEVICE_LINK = """
{{ value|default:'<span class="badge text-bg-info">Unnamed device</span>' }}
{{ record.label|default:'<span class="badge text-bg-info">Unnamed device</span>' }}
"""
DEVICEBAY_STATUS = """
@@ -64,21 +64,23 @@ INTERFACE_IPADDRESSES = """
INTERFACE_FHRPGROUPS = """
{% for assignment in value.all %}
<a href="{{ assignment.group.get_absolute_url }}">{{ assignment.group.get_protocol_display }}: {{ assignment.group.group_id }}</a>
<a href="{{ assignment.group.get_absolute_url }}">{{ assignment.group }}</a>
{% endfor %}
"""
INTERFACE_TAGGED_VLANS = """
{% if record.mode == 'tagged' %}
{% load i18n %}
{% if record.mode == 'access' %}
{% elif record.mode == 'tagged-all' %}
{% trans "All" %}
{% else %}
{% if value.count > 3 %}
<a href="{% url 'ipam:vlan_list' %}?{{ record|meta:"model_name" }}_id={{ record.pk }}">{{ value.count }} VLANs</a>
{% else %}
{% for vlan in value.all %}
<a href="{{ vlan.get_absolute_url }}">{{ vlan }}</a><br />
<a href="{{ vlan.get_absolute_url }}">{{ vlan }}</a><br />
{% endfor %}
{% endif %}
{% elif record.mode == 'tagged-all' %}
All
{% endif %}
"""
@@ -157,8 +159,8 @@ CONSOLEPORT_BUTTONS = """
</span>
{% endif %}
{% elif perms.dcim.add_cable %}
<a href="#" class="btn btn-outline-dark btn-sm disabled"><i class="mdi mdi-transit-connection-variant" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-dark btn-sm disabled"><i class="mdi mdi-lan-connect" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-secondary btn-sm disabled"><i class="mdi mdi-transit-connection-variant" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-secondary btn-sm disabled"><i class="mdi mdi-lan-connect" aria-hidden="true"></i></a>
<span class="dropdown">
<button type="button" class="btn btn-success btn-sm dropdown-toggle" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="mdi mdi-ethernet-cable" aria-hidden="true"></span>
@@ -170,7 +172,7 @@ CONSOLEPORT_BUTTONS = """
</ul>
</span>
{% else %}
<a href="#" class="btn btn-outline-dark btn-sm disabled"><i class="mdi mdi-ethernet-cable" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-secondary btn-sm disabled"><i class="mdi mdi-ethernet-cable" aria-hidden="true"></i></a>
{% endif %}
"""
@@ -207,8 +209,8 @@ CONSOLESERVERPORT_BUTTONS = """
</span>
{% endif %}
{% elif perms.dcim.add_cable %}
<a href="#" class="btn btn-outline-dark btn-sm disabled"><i class="mdi mdi-transit-connection-variant" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-dark btn-sm disabled"><i class="mdi mdi-lan-connect" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-secondary btn-sm disabled"><i class="mdi mdi-transit-connection-variant" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-secondary btn-sm disabled"><i class="mdi mdi-lan-connect" aria-hidden="true"></i></a>
<span class="dropdown">
<button type="button" class="btn btn-success btn-sm dropdown-toggle" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="mdi mdi-ethernet-cable" aria-hidden="true"></span>
@@ -220,7 +222,7 @@ CONSOLESERVERPORT_BUTTONS = """
</ul>
</span>
{% else %}
<a href="#" class="btn btn-outline-dark btn-sm disabled"><i class="mdi mdi-ethernet-cable" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-secondary btn-sm disabled"><i class="mdi mdi-ethernet-cable" aria-hidden="true"></i></a>
{% endif %}
"""
@@ -257,8 +259,8 @@ POWERPORT_BUTTONS = """
</span>
{% endif %}
{% elif perms.dcim.add_cable %}
<a href="#" class="btn btn-outline-dark btn-sm disabled"><i class="mdi mdi-transit-connection-variant" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-dark btn-sm disabled"><i class="mdi mdi-lan-connect" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-secondary btn-sm disabled"><i class="mdi mdi-transit-connection-variant" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-secondary btn-sm disabled"><i class="mdi mdi-lan-connect" aria-hidden="true"></i></a>
<span class="dropdown">
<button type="button" class="btn btn-success btn-sm dropdown-toggle" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="mdi mdi-ethernet-cable" aria-hidden="true"></span>
@@ -269,7 +271,7 @@ POWERPORT_BUTTONS = """
</ul>
</span>
{% else %}
<a href="#" class="btn btn-outline-dark btn-sm disabled"><i class="mdi mdi-ethernet-cable" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-secondary btn-sm disabled"><i class="mdi mdi-ethernet-cable" aria-hidden="true"></i></a>
{% endif %}
"""
@@ -306,14 +308,14 @@ POWEROUTLET_BUTTONS = """
</span>
{% endif %}
{% elif perms.dcim.add_cable %}
<a href="#" class="btn btn-outline-dark btn-sm disabled"><i class="mdi mdi-transit-connection-variant" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-dark btn-sm disabled"><i class="mdi mdi-lan-connect" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-secondary btn-sm disabled"><i class="mdi mdi-transit-connection-variant" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-secondary btn-sm disabled"><i class="mdi mdi-lan-connect" aria-hidden="true"></i></a>
{% if not record.mark_connected %}
<a href="{% url 'dcim:cable_add' %}?a_terminations_type=dcim.poweroutlet&a_terminations={{ record.pk }}&b_terminations_type=dcim.powerport&termination_b_site={{ object.site.pk }}&termination_b_rack={{ object.rack.pk }}&return_url={% url 'dcim:device_poweroutlets' pk=object.pk %}" title="Connect" class="btn btn-success btn-sm">
<i class="mdi mdi-ethernet-cable" aria-hidden="true"></i>
</a>
{% else %}
<a href="#" class="btn btn-outline-dark btn-sm disabled"><i class="mdi mdi-ethernet-cable" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-secondary btn-sm disabled"><i class="mdi mdi-ethernet-cable" aria-hidden="true"></i></a>
{% endif %}
{% endif %}
"""
@@ -400,8 +402,8 @@ INTERFACE_BUTTONS = """
</a>
{% endif %}
{% elif record.is_wired and perms.dcim.add_cable %}
<a href="#" class="btn btn-outline-dark btn-sm disabled"><i class="mdi mdi-transit-connection-variant" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-dark btn-sm disabled"><i class="mdi mdi-lan-connect" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-secondary btn-sm disabled"><i class="mdi mdi-transit-connection-variant" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-secondary btn-sm disabled"><i class="mdi mdi-lan-connect" aria-hidden="true"></i></a>
{% if not record.mark_connected %}
<span class="dropdown">
<button type="button" class="btn btn-success btn-sm dropdown-toggle" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" title="Connect cable">
@@ -415,7 +417,7 @@ INTERFACE_BUTTONS = """
</ul>
</span>
{% else %}
<a href="#" class="btn btn-outline-dark btn-sm disabled"><i class="mdi mdi-ethernet-cable" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-secondary btn-sm disabled"><i class="mdi mdi-ethernet-cable" aria-hidden="true"></i></a>
{% endif %}
{% elif record.is_wireless and perms.wireless.add_wirelesslink %}
<a href="{% url 'wireless:wirelesslink_add' %}?site_a={{ record.device.site.pk }}&location_a={{ record.device.location.pk }}&device_a={{ record.device_id }}&interface_a={{ record.pk }}&site_b={{ record.device.site.pk }}&location_b={{ record.device.location.pk }}" class="btn btn-success btn-sm">
@@ -457,8 +459,8 @@ FRONTPORT_BUTTONS = """
</span>
{% endif %}
{% elif perms.dcim.add_cable %}
<a href="#" class="btn btn-outline-dark btn-sm disabled"><i class="mdi mdi-transit-connection-variant" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-dark btn-sm disabled"><i class="mdi mdi-lan-connect" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-secondary btn-sm disabled"><i class="mdi mdi-transit-connection-variant" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-secondary btn-sm disabled"><i class="mdi mdi-lan-connect" aria-hidden="true"></i></a>
{% if not record.mark_connected %}
<span class="dropdown">
<button type="button" class="btn btn-success btn-sm dropdown-toggle" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
@@ -474,7 +476,7 @@ FRONTPORT_BUTTONS = """
</ul>
</span>
{% else %}
<a href="#" class="btn btn-outline-dark btn-sm disabled"><i class="mdi mdi-ethernet-cable" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-secondary btn-sm disabled"><i class="mdi mdi-ethernet-cable" aria-hidden="true"></i></a>
{% endif %}
{% endif %}
"""
@@ -512,8 +514,8 @@ REARPORT_BUTTONS = """
</span>
{% endif %}
{% elif perms.dcim.add_cable %}
<a href="#" class="btn btn-outline-dark btn-sm disabled"><i class="mdi mdi-transit-connection-variant" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-dark btn-sm disabled"><i class="mdi mdi-lan-connect" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-secondary btn-sm disabled"><i class="mdi mdi-transit-connection-variant" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-secondary btn-sm disabled"><i class="mdi mdi-lan-connect" aria-hidden="true"></i></a>
{% if not record.mark_connected %}
<span class="dropdown">
<button type="button" class="btn btn-success btn-sm dropdown-toggle" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
@@ -529,7 +531,7 @@ REARPORT_BUTTONS = """
</ul>
</span>
{% else %}
<a href="#" class="btn btn-outline-dark btn-sm disabled"><i class="mdi mdi-ethernet-cable" aria-hidden="true"></i></a>
<a href="#" class="btn btn-outline-secondary btn-sm disabled"><i class="mdi mdi-ethernet-cable" aria-hidden="true"></i></a>
{% endif %}
{% endif %}
"""

View File

@@ -1,4 +1,6 @@
from django.test import override_settings
import json
from django.test import override_settings, tag
from django.urls import reverse
from django.utils.translation import gettext as _
from rest_framework import status
@@ -1748,6 +1750,23 @@ class InterfaceTest(Mixins.ComponentTraceMixin, APIViewTestCases.APIViewTestCase
},
]
def _perform_interface_test_with_invalid_data(self, mode: str = None, invalid_data: dict = {}):
device = Device.objects.first()
data = {
'device': device.pk,
'name': 'Interface 1',
'type': InterfaceTypeChoices.TYPE_1GE_FIXED,
}
data.update({'mode': mode})
data.update(invalid_data)
response = self.client.post(self._get_list_url(), data, format='json', **self.header)
self.assertHttpStatus(response, status.HTTP_400_BAD_REQUEST)
content = json.loads(response.content)
for key in invalid_data.keys():
self.assertIn(key, content)
self.assertIsNone(content.get('data'))
def test_bulk_delete_child_interfaces(self):
interface1 = Interface.objects.get(name='Interface 1')
device = interface1.device
@@ -1775,6 +1794,57 @@ class InterfaceTest(Mixins.ComponentTraceMixin, APIViewTestCases.APIViewTestCase
self.client.delete(self._get_list_url(), data, format='json', **self.header)
self.assertEqual(device.interfaces.count(), 2) # Child & parent were both deleted
def test_create_child_interfaces_mode_invalid_data(self):
"""
POST data to test interface mode check and invalid tagged/untagged VLANS.
"""
self.add_permissions('dcim.add_interface')
vlans = VLAN.objects.all()[0:3]
# Routed mode, untagged, tagged and qinq service vlan
invalid_data = {
'untagged_vlan': vlans[0].pk,
'tagged_vlans': [vlans[1].pk, vlans[2].pk],
'qinq_svlan': vlans[2].pk
}
self._perform_interface_test_with_invalid_data(None, invalid_data)
# Routed mode, untagged and tagged vlan
invalid_data = {
'untagged_vlan': vlans[0].pk,
'tagged_vlans': [vlans[1].pk, vlans[2].pk],
}
self._perform_interface_test_with_invalid_data(None, invalid_data)
# Routed mode, untagged vlan
invalid_data = {
'untagged_vlan': vlans[0].pk,
}
self._perform_interface_test_with_invalid_data(None, invalid_data)
invalid_data = {
'tagged_vlans': [vlans[1].pk, vlans[2].pk],
}
# Routed mode, qinq service vlan
self._perform_interface_test_with_invalid_data(None, invalid_data)
# Access mode, tagged vlans
self._perform_interface_test_with_invalid_data(InterfaceModeChoices.MODE_ACCESS, invalid_data)
# All tagged mode, tagged vlans
self._perform_interface_test_with_invalid_data(InterfaceModeChoices.MODE_TAGGED_ALL, invalid_data)
invalid_data = {
'qinq_svlan': vlans[0].pk,
}
# Routed mode, qinq service vlan
self._perform_interface_test_with_invalid_data(None, invalid_data)
# Access mode, qinq service vlan
self._perform_interface_test_with_invalid_data(InterfaceModeChoices.MODE_ACCESS, invalid_data)
# Tagged mode, qinq service vlan
self._perform_interface_test_with_invalid_data(InterfaceModeChoices.MODE_TAGGED, invalid_data)
# Tagged-all mode, qinq service vlan
self._perform_interface_test_with_invalid_data(InterfaceModeChoices.MODE_TAGGED_ALL, invalid_data)
class FrontPortTest(APIViewTestCases.APIViewTestCase):
model = FrontPort
@@ -1834,6 +1904,27 @@ class FrontPortTest(APIViewTestCases.APIViewTestCase):
},
]
@tag('regression') # Issue #18991
def test_front_port_paths(self):
device = Device.objects.first()
rear_port = RearPort.objects.create(
device=device, name='Rear Port 10', type=PortTypeChoices.TYPE_8P8C
)
interface1 = Interface.objects.create(device=device, name='Interface 1')
front_port = FrontPort.objects.create(
device=device,
name='Rear Port 10',
type=PortTypeChoices.TYPE_8P8C,
rear_port=rear_port,
)
Cable.objects.create(a_terminations=[interface1], b_terminations=[front_port])
self.add_permissions(f'dcim.view_{self.model._meta.model_name}')
url = reverse(f'dcim-api:{self.model._meta.model_name}-paths', kwargs={'pk': front_port.pk})
response = self.client.get(url, **self.header)
self.assertHttpStatus(response, status.HTTP_200_OK)
class RearPortTest(APIViewTestCases.APIViewTestCase):
model = RearPort
@@ -1877,6 +1968,23 @@ class RearPortTest(APIViewTestCases.APIViewTestCase):
},
]
@tag('regression') # Issue #18991
def test_rear_port_paths(self):
device = Device.objects.first()
interface1 = Interface.objects.create(device=device, name='Interface 1')
rear_port = RearPort.objects.create(
device=device,
name='Rear Port 10',
type=PortTypeChoices.TYPE_8P8C,
)
Cable.objects.create(a_terminations=[interface1], b_terminations=[rear_port])
self.add_permissions(f'dcim.view_{self.model._meta.model_name}')
url = reverse(f'dcim-api:{self.model._meta.model_name}-paths', kwargs={'pk': rear_port.pk})
response = self.client.get(url, **self.header)
self.assertHttpStatus(response, status.HTTP_200_OK)
class ModuleBayTest(APIViewTestCases.APIViewTestCase):
model = ModuleBay
@@ -2447,3 +2555,46 @@ class VirtualDeviceContextTest(APIViewTestCases.APIViewTestCase):
# Omit identifier to test uniqueness constraint
},
]
class MACAddressTest(APIViewTestCases.APIViewTestCase):
model = MACAddress
brief_fields = ['description', 'display', 'id', 'mac_address', 'url']
bulk_update_data = {
'description': 'New description',
}
@classmethod
def setUpTestData(cls):
device = create_test_device(name='Device 1')
interfaces = (
Interface(device=device, name='Interface 1', type='1000base-t'),
Interface(device=device, name='Interface 2', type='1000base-t'),
Interface(device=device, name='Interface 3', type='1000base-t'),
Interface(device=device, name='Interface 4', type='1000base-t'),
Interface(device=device, name='Interface 5', type='1000base-t'),
)
Interface.objects.bulk_create(interfaces)
mac_addresses = (
MACAddress(mac_address='00:00:00:00:00:01', assigned_object=interfaces[0]),
MACAddress(mac_address='00:00:00:00:00:02', assigned_object=interfaces[1]),
MACAddress(mac_address='00:00:00:00:00:03', assigned_object=interfaces[2]),
)
MACAddress.objects.bulk_create(mac_addresses)
cls.create_data = [
{
'mac_address': '00:00:00:00:00:04',
'assigned_object_type': 'dcim.interface',
'assigned_object_id': interfaces[3].pk,
},
{
'mac_address': '00:00:00:00:00:05',
'assigned_object_type': 'dcim.interface',
'assigned_object_id': interfaces[4].pk,
},
{
'mac_address': '00:00:00:00:00:06',
},
]

View File

@@ -5,6 +5,7 @@ from dcim.choices import LinkStatusChoices
from dcim.models import *
from dcim.svg import CableTraceSVG
from dcim.utils import object_to_path_node
from utilities.exceptions import AbortRequest
class CablePathTestCase(TestCase):
@@ -2470,7 +2471,7 @@ class CablePathTestCase(TestCase):
b_terminations=[frontport1, frontport3],
label='C1'
)
with self.assertRaises(AssertionError):
with self.assertRaises(AbortRequest):
cable1.save()
self.assertPathDoesNotExist(
@@ -2489,7 +2490,7 @@ class CablePathTestCase(TestCase):
label='C3'
)
with self.assertRaises(AssertionError):
with self.assertRaises(AbortRequest):
cable3.save()
self.assertPathDoesNotExist(

View File

@@ -2561,6 +2561,8 @@ class DeviceTestCase(TestCase, ChangeLoggedFilterSetTests):
locations = Location.objects.all()[:2]
params = {'location_id': [locations[0].pk, locations[1].pk]}
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
params = {'location': [locations[0].slug, locations[1].slug]}
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
def test_rack(self):
racks = Rack.objects.all()[:2]
@@ -4151,7 +4153,7 @@ class InterfaceTestCase(TestCase, DeviceComponentFilterSetTests, ChangeLoggedFil
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 4)
def test_mode(self):
params = {'mode': InterfaceModeChoices.MODE_ACCESS}
params = {'mode': [InterfaceModeChoices.MODE_ACCESS]}
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
def test_description(self):

View File

@@ -1,8 +1,15 @@
from django.test import TestCase
from dcim.choices import DeviceFaceChoices, DeviceStatusChoices, InterfaceTypeChoices
from dcim.choices import (
DeviceFaceChoices,
DeviceStatusChoices,
InterfaceModeChoices,
InterfaceTypeChoices,
PortTypeChoices,
)
from dcim.forms import *
from dcim.models import *
from ipam.models import VLAN
from utilities.testing import create_test_device
from virtualization.models import Cluster, ClusterGroup, ClusterType
@@ -117,11 +124,68 @@ class DeviceTestCase(TestCase):
self.assertIn('position', form.errors)
class LabelTestCase(TestCase):
class FrontPortTestCase(TestCase):
@classmethod
def setUpTestData(cls):
cls.device = create_test_device('Panel Device 1')
cls.rear_ports = (
RearPort(name='RearPort1', device=cls.device, type=PortTypeChoices.TYPE_8P8C),
RearPort(name='RearPort2', device=cls.device, type=PortTypeChoices.TYPE_8P8C),
RearPort(name='RearPort3', device=cls.device, type=PortTypeChoices.TYPE_8P8C),
RearPort(name='RearPort4', device=cls.device, type=PortTypeChoices.TYPE_8P8C),
)
RearPort.objects.bulk_create(cls.rear_ports)
def test_front_port_label_count_valid(self):
"""
Test that generating an equal number of names and labels passes form validation.
"""
front_port_data = {
'device': self.device.pk,
'name': 'FrontPort[1-4]',
'label': 'Port[1-4]',
'type': PortTypeChoices.TYPE_8P8C,
'rear_port': [f'{rear_port.pk}:1' for rear_port in self.rear_ports],
}
form = FrontPortCreateForm(front_port_data)
self.assertTrue(form.is_valid())
def test_front_port_label_count_mismatch(self):
"""
Check that attempting to generate a differing number of names and labels results in a validation error.
"""
bad_front_port_data = {
'device': self.device.pk,
'name': 'FrontPort[1-4]',
'label': 'Port[1-2]',
'type': PortTypeChoices.TYPE_8P8C,
'rear_port': [f'{rear_port.pk}:1' for rear_port in self.rear_ports],
}
form = FrontPortCreateForm(bad_front_port_data)
self.assertFalse(form.is_valid())
self.assertIn('label', form.errors)
class InterfaceTestCase(TestCase):
@classmethod
def setUpTestData(cls):
cls.device = create_test_device('Device 1')
cls.vlans = (
VLAN(name='VLAN 1', vid=1),
VLAN(name='VLAN 2', vid=2),
VLAN(name='VLAN 3', vid=3),
)
VLAN.objects.bulk_create(cls.vlans)
cls.interface = Interface.objects.create(
device=cls.device,
name='Interface 1',
type=InterfaceTypeChoices.TYPE_1GE_GBIC,
mode=InterfaceModeChoices.MODE_TAGGED,
)
def test_interface_label_count_valid(self):
"""
@@ -151,3 +215,152 @@ class LabelTestCase(TestCase):
self.assertFalse(form.is_valid())
self.assertIn('label', form.errors)
def test_create_interface_mode_valid_data(self):
"""
Test that saving valid interface mode and tagged/untagged vlans works properly
"""
# Validate access mode
data = {
'device': self.device.pk,
'name': 'ethernet1/1',
'type': InterfaceTypeChoices.TYPE_1GE_GBIC,
'mode': InterfaceModeChoices.MODE_ACCESS,
'untagged_vlan': self.vlans[0].pk
}
form = InterfaceCreateForm(data)
self.assertTrue(form.is_valid())
# Validate tagged vlans
data = {
'device': self.device.pk,
'name': 'ethernet1/2',
'type': InterfaceTypeChoices.TYPE_1GE_GBIC,
'mode': InterfaceModeChoices.MODE_TAGGED,
'untagged_vlan': self.vlans[0].pk,
'tagged_vlans': [self.vlans[1].pk, self.vlans[2].pk]
}
form = InterfaceCreateForm(data)
self.assertTrue(form.is_valid())
# Validate tagged vlans
data = {
'device': self.device.pk,
'name': 'ethernet1/3',
'type': InterfaceTypeChoices.TYPE_1GE_GBIC,
'mode': InterfaceModeChoices.MODE_TAGGED_ALL,
'untagged_vlan': self.vlans[0].pk,
}
form = InterfaceCreateForm(data)
self.assertTrue(form.is_valid())
def test_create_interface_mode_access_invalid_data(self):
"""
Test that saving invalid interface mode and tagged/untagged vlans works properly
"""
data = {
'device': self.device.pk,
'name': 'ethernet1/4',
'type': InterfaceTypeChoices.TYPE_1GE_GBIC,
'mode': InterfaceModeChoices.MODE_ACCESS,
'untagged_vlan': self.vlans[0].pk,
'tagged_vlans': [self.vlans[1].pk, self.vlans[2].pk]
}
form = InterfaceCreateForm(data)
self.assertTrue(form.is_valid())
self.assertIn('untagged_vlan', form.cleaned_data.keys())
self.assertNotIn('tagged_vlans', form.cleaned_data.keys())
self.assertNotIn('qinq_svlan', form.cleaned_data.keys())
def test_edit_interface_mode_access_invalid_data(self):
"""
Test that saving invalid interface mode and tagged/untagged vlans works properly
"""
data = {
'device': self.device.pk,
'name': 'Ethernet 1/5',
'type': InterfaceTypeChoices.TYPE_1GE_GBIC,
'mode': InterfaceModeChoices.MODE_ACCESS,
'tagged_vlans': [self.vlans[0].pk, self.vlans[1].pk, self.vlans[2].pk]
}
form = InterfaceForm(data, instance=self.interface)
self.assertTrue(form.is_valid())
self.assertIn('untagged_vlan', form.cleaned_data.keys())
self.assertNotIn('tagged_vlans', form.cleaned_data.keys())
self.assertNotIn('qinq_svlan', form.cleaned_data.keys())
def test_create_interface_mode_tagged_all_invalid_data(self):
"""
Test that saving invalid interface mode and tagged/untagged vlans works properly
"""
data = {
'device': self.device.pk,
'name': 'ethernet1/6',
'type': InterfaceTypeChoices.TYPE_1GE_GBIC,
'mode': InterfaceModeChoices.MODE_TAGGED_ALL,
'tagged_vlans': [self.vlans[0].pk, self.vlans[1].pk, self.vlans[2].pk]
}
form = InterfaceCreateForm(data)
self.assertTrue(form.is_valid())
self.assertIn('untagged_vlan', form.cleaned_data.keys())
self.assertNotIn('tagged_vlans', form.cleaned_data.keys())
self.assertNotIn('qinq_svlan', form.cleaned_data.keys())
def test_edit_interface_mode_tagged_all_invalid_data(self):
"""
Test that saving invalid interface mode and tagged/untagged vlans works properly
"""
data = {
'device': self.device.pk,
'name': 'Ethernet 1/7',
'type': InterfaceTypeChoices.TYPE_1GE_GBIC,
'mode': InterfaceModeChoices.MODE_TAGGED_ALL,
'tagged_vlans': [self.vlans[0].pk, self.vlans[1].pk, self.vlans[2].pk]
}
form = InterfaceForm(data)
self.assertTrue(form.is_valid())
self.assertIn('untagged_vlan', form.cleaned_data.keys())
self.assertNotIn('tagged_vlans', form.cleaned_data.keys())
self.assertNotIn('qinq_svlan', form.cleaned_data.keys())
def test_create_interface_mode_routed_invalid_data(self):
"""
Test that saving invalid interface mode (routed) and tagged/untagged vlans works properly
"""
data = {
'device': self.device.pk,
'name': 'ethernet1/6',
'type': InterfaceTypeChoices.TYPE_1GE_GBIC,
'mode': None,
'untagged_vlan': self.vlans[0].pk,
'tagged_vlans': [self.vlans[0].pk, self.vlans[1].pk, self.vlans[2].pk]
}
form = InterfaceCreateForm(data)
self.assertTrue(form.is_valid())
self.assertNotIn('untagged_vlan', form.cleaned_data.keys())
self.assertNotIn('tagged_vlans', form.cleaned_data.keys())
self.assertNotIn('qinq_svlan', form.cleaned_data.keys())
def test_edit_interface_mode_routed_invalid_data(self):
"""
Test that saving invalid interface mode (routed) and tagged/untagged vlans works properly
"""
data = {
'device': self.device.pk,
'name': 'Ethernet 1/7',
'type': InterfaceTypeChoices.TYPE_1GE_GBIC,
'mode': None,
'untagged_vlan': self.vlans[0].pk,
'tagged_vlans': [self.vlans[0].pk, self.vlans[1].pk, self.vlans[2].pk]
}
form = InterfaceForm(data)
self.assertTrue(form.is_valid())
self.assertNotIn('untagged_vlan', form.cleaned_data.keys())
self.assertNotIn('tagged_vlans', form.cleaned_data.keys())
self.assertNotIn('qinq_svlan', form.cleaned_data.keys())

View File

@@ -1,5 +1,5 @@
from django.core.exceptions import ValidationError
from django.test import TestCase
from django.test import tag, TestCase
from circuits.models import *
from core.models import ObjectType
@@ -12,6 +12,43 @@ from utilities.data import drange
from virtualization.models import Cluster, ClusterType
class MACAddressTestCase(TestCase):
@classmethod
def setUpTestData(cls):
site = Site.objects.create(name='Test Site 1', slug='test-site-1')
manufacturer = Manufacturer.objects.create(name='Test Manufacturer 1', slug='test-manufacturer-1')
device_type = DeviceType.objects.create(
manufacturer=manufacturer, model='Test Device Type 1', slug='test-device-type-1'
)
device_role = DeviceRole.objects.create(name='Test Role 1', slug='test-role-1')
device = Device.objects.create(
name='Device 1', device_type=device_type, role=device_role, site=site,
)
cls.interface = Interface.objects.create(
device=device,
name='Interface 1',
type=InterfaceTypeChoices.TYPE_1GE_FIXED,
mgmt_only=True
)
cls.mac_a = MACAddress.objects.create(mac_address='1234567890ab', assigned_object=cls.interface)
cls.mac_b = MACAddress.objects.create(mac_address='1234567890ba', assigned_object=cls.interface)
cls.interface.primary_mac_address = cls.mac_a
cls.interface.save()
@tag('regression')
def test_clean_will_not_allow_removal_of_assigned_object_if_primary(self):
self.mac_a.assigned_object = None
with self.assertRaisesMessage(ValidationError, 'Cannot unassign MAC Address while'):
self.mac_a.clean()
@tag('regression')
def test_clean_will_allow_removal_of_assigned_object_if_not_primary(self):
self.mac_b.assigned_object = None
self.mac_b.clean()
class LocationTestCase(TestCase):
def test_change_location_site(self):
@@ -590,6 +627,32 @@ class DeviceTestCase(TestCase):
device2.full_clean()
device2.save()
def test_device_label(self):
device1 = Device(
site=Site.objects.first(),
device_type=DeviceType.objects.first(),
role=DeviceRole.objects.first(),
name=None,
)
self.assertEqual(device1.label, None)
device1.name = 'Test Device 1'
self.assertEqual(device1.label, 'Test Device 1')
virtual_chassis = VirtualChassis.objects.create(name='VC 1')
device2 = Device(
site=Site.objects.first(),
device_type=DeviceType.objects.first(),
role=DeviceRole.objects.first(),
name=None,
virtual_chassis=virtual_chassis,
vc_position=2,
)
self.assertEqual(device2.label, 'VC 1:2')
device2.name = 'Test Device 2'
self.assertEqual(device2.label, 'Test Device 2')
def test_device_mismatched_site_cluster(self):
cluster_type = ClusterType.objects.create(name='Cluster Type 1', slug='cluster-type-1')
Cluster.objects.create(name='Cluster 1', type=cluster_type)

View File

@@ -3470,3 +3470,54 @@ class VirtualDeviceContextTestCase(ViewTestCases.PrimaryObjectViewTestCase):
cls.bulk_edit_data = {
'status': VirtualDeviceContextStatusChoices.STATUS_OFFLINE,
}
class MACAddressTestCase(ViewTestCases.PrimaryObjectViewTestCase):
model = MACAddress
@classmethod
def setUpTestData(cls):
device = create_test_device(name='Device 1')
interfaces = (
Interface(device=device, name='Interface 1', type='1000base-t'),
Interface(device=device, name='Interface 2', type='1000base-t'),
Interface(device=device, name='Interface 3', type='1000base-t'),
Interface(device=device, name='Interface 4', type='1000base-t'),
Interface(device=device, name='Interface 5', type='1000base-t'),
Interface(device=device, name='Interface 6', type='1000base-t'),
)
Interface.objects.bulk_create(interfaces)
mac_addresses = (
MACAddress(mac_address='00:00:00:00:00:01', assigned_object=interfaces[0]),
MACAddress(mac_address='00:00:00:00:00:02', assigned_object=interfaces[1]),
MACAddress(mac_address='00:00:00:00:00:03', assigned_object=interfaces[2]),
)
MACAddress.objects.bulk_create(mac_addresses)
tags = create_tags('Alpha', 'Bravo', 'Charlie')
cls.form_data = {
'mac_address': EUI('00:00:00:00:00:04'),
'description': 'New MAC address',
'interface_id': interfaces[3].pk,
'tags': [t.pk for t in tags],
}
cls.csv_data = (
"mac_address,device,interface",
"00:00:00:00:00:04,Device 1,Interface 4",
"00:00:00:00:00:05,Device 1,Interface 5",
"00:00:00:00:00:06,Device 1,Interface 6",
)
cls.csv_update_data = (
"id,mac_address",
f"{mac_addresses[0].pk},00:00:00:00:00:0a",
f"{mac_addresses[1].pk},00:00:00:00:00:0b",
f"{mac_addresses[2].pk},00:00:00:00:00:0c",
)
cls.bulk_edit_data = {
'description': 'New description',
}

View File

@@ -4,18 +4,16 @@ from django.core.paginator import EmptyPage, PageNotAnInteger
from django.db import transaction
from django.db.models import Prefetch
from django.forms import ModelMultipleChoiceField, MultipleHiddenInput, modelformset_factory
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from django.views.generic import View
from jinja2.exceptions import TemplateError
from circuits.models import Circuit, CircuitTermination
from extras.views import ObjectConfigContextView
from ipam.models import ASN, IPAddress, VLANGroup
from extras.views import ObjectConfigContextView, ObjectRenderConfigView
from ipam.models import ASN, IPAddress, Prefix, VLANGroup, VLAN
from ipam.tables import InterfaceVLANTable, VLANTranslationRuleTable
from netbox.constants import DEFAULT_ACTION_PERMISSIONS
from netbox.views import generic
@@ -30,8 +28,9 @@ from utilities.views import (
)
from virtualization.filtersets import VirtualMachineFilterSet
from virtualization.forms import VirtualMachineFilterForm
from virtualization.models import VirtualMachine
from virtualization.models import Cluster, VirtualMachine
from virtualization.tables import VirtualMachineTable
from wireless.models import WirelessLAN
from . import filtersets, forms, tables
from .choices import DeviceFaceChoices, InterfaceModeChoices
from .models import *
@@ -238,6 +237,7 @@ class RegionView(GetRelatedModelsMixin, generic.ObjectView):
'related_models': self.get_related_models(
request,
regions,
omit=(Cluster, CircuitTermination, Prefix, WirelessLAN),
extra=(
(Location.objects.restrict(request.user, 'view').filter(site__region__in=regions), 'region_id'),
(Rack.objects.restrict(request.user, 'view').filter(site__region__in=regions), 'region_id'),
@@ -247,6 +247,22 @@ class RegionView(GetRelatedModelsMixin, generic.ObjectView):
).distinct(),
'region_id'
),
(
VLANGroup.objects.restrict(request.user, 'view').filter(
scope_type=ContentType.objects.get_for_model(Region),
scope_id__in=regions
).distinct(),
'region'
),
# Handle these relations manually to avoid erroneous filter name resolution
(
CircuitTermination.objects.restrict(request.user, 'view').filter(_region__in=regions),
'region_id'
),
(Cluster.objects.restrict(request.user, 'view').filter(_region__in=regions), 'region_id'),
(Prefix.objects.restrict(request.user, 'view').filter(_region__in=regions), 'region_id'),
(WirelessLAN.objects.restrict(request.user, 'view').filter(_region__in=regions), 'region_id'),
),
),
}
@@ -331,15 +347,53 @@ class SiteGroupView(GetRelatedModelsMixin, generic.ObjectView):
'related_models': self.get_related_models(
request,
groups,
omit=(Cluster, CircuitTermination, Prefix, WirelessLAN),
extra=(
(Location.objects.restrict(request.user, 'view').filter(site__group__in=groups), 'site_group_id'),
(Rack.objects.restrict(request.user, 'view').filter(site__group__in=groups), 'site_group_id'),
(Device.objects.restrict(request.user, 'view').filter(site__group__in=groups), 'site_group_id'),
(VLAN.objects.restrict(request.user, 'view').filter(site__group__in=groups), 'site_group_id'),
(
ASN.objects.restrict(request.user, 'view').filter(
sites__group__in=groups
).distinct(),
'site_group_id'),
(
VirtualMachine.objects.restrict(request.user, 'view').filter(
site__group__in=groups),
'site_group_id'
),
(
VLANGroup.objects.restrict(request.user, 'view').filter(
scope_type=ContentType.objects.get_for_model(SiteGroup),
scope_id__in=groups
).distinct(),
'site_group'
),
(
Circuit.objects.restrict(request.user, 'view').filter(
terminations___site_group=instance
).distinct(),
'site_group_id'
),
# Handle these relations manually to avoid erroneous filter name resolution
(
CircuitTermination.objects.restrict(request.user, 'view').filter(_site_group__in=groups),
'site_group_id'
),
(
Cluster.objects.restrict(request.user, 'view').filter(_site_group__in=groups),
'site_group_id'
),
(
Prefix.objects.restrict(request.user, 'view').filter(_site_group__in=groups),
'site_group_id'
),
(
WirelessLAN.objects.restrict(request.user, 'view').filter(_site_group__in=groups),
'site_group_id'
),
),
),
}
@@ -402,7 +456,8 @@ class SiteGroupContactsView(ObjectContactsView):
@register_model_view(Site, 'list', path='', detail=False)
class SiteListView(generic.ObjectListView):
queryset = Site.objects.annotate(
device_count=count_related(Device, 'site')
device_count=count_related(Device, 'site'),
asn_count=count_related(ASN, 'sites')
)
filterset = filtersets.SiteFilterSet
filterset_form = forms.SiteFilterForm
@@ -418,8 +473,8 @@ class SiteView(GetRelatedModelsMixin, generic.ObjectView):
'related_models': self.get_related_models(
request,
instance,
[CableTermination, CircuitTermination],
(
omit=(CableTermination, CircuitTermination, Cluster, Prefix, WirelessLAN),
extra=(
(VLANGroup.objects.restrict(request.user, 'view').filter(
scope_type=ContentType.objects.get_for_model(Site),
scope_id=instance.pk
@@ -429,6 +484,12 @@ class SiteView(GetRelatedModelsMixin, generic.ObjectView):
Circuit.objects.restrict(request.user, 'view').filter(terminations___site=instance).distinct(),
'site_id'
),
# Handle these relations manually to avoid erroneous filter name resolution
(Cluster.objects.restrict(request.user, 'view').filter(_site=instance), 'site_id'),
(Prefix.objects.restrict(request.user, 'view').filter(_site=instance), 'site_id'),
(WirelessLAN.objects.restrict(request.user, 'view').filter(_site=instance), 'site_id'),
(CircuitTermination.objects.restrict(request.user, 'view').filter(_site=instance), 'site_id'),
),
),
}
@@ -479,18 +540,24 @@ class SiteContactsView(ObjectContactsView):
@register_model_view(Location, 'list', path='', detail=False)
class LocationListView(generic.ObjectListView):
queryset = Location.objects.add_related_count(
Location.objects.add_related_count(
Location.objects.all(),
Device,
'location',
'device_count',
cumulative=True
),
Rack,
'location',
'rack_count',
cumulative=True
)
Location.objects.add_related_count(
Location.objects.add_related_count(
Location.objects.all(),
Device,
'location',
'device_count',
cumulative=True
),
Rack,
'location',
'rack_count',
cumulative=True
),
VLANGroup,
'location',
'vlangroup_count',
cumulative=True
)
filterset = filtersets.LocationFilterSet
filterset_form = forms.LocationFilterForm
table = tables.LocationTable
@@ -502,18 +569,30 @@ class LocationView(GetRelatedModelsMixin, generic.ObjectView):
def get_extra_context(self, request, instance):
locations = instance.get_descendants(include_self=True)
location_content_type = ContentType.objects.get_for_model(instance)
return {
'related_models': self.get_related_models(
request,
locations,
[CableTermination],
(
omit=[CableTermination, CircuitTermination, Cluster, Prefix, WirelessLAN],
extra=(
(
Circuit.objects.restrict(request.user, 'view').filter(
terminations___location=instance
).distinct(),
'location_id'
),
# Handle these relations manually to avoid erroneous filter name resolution
(
CircuitTermination.objects.restrict(request.user, 'view').filter(_location=instance),
'location_id'
),
(Cluster.objects.restrict(request.user, 'view').filter(_location=instance), 'location_id'),
(Prefix.objects.restrict(request.user, 'view').filter(_location=instance), 'location_id'),
(WirelessLAN.objects.restrict(request.user, 'view').filter(_location=instance), 'location_id'),
(VLANGroup.objects.restrict(request.user, 'view').filter(
scope_type_id=location_content_type.id, scope_id=instance.id), 'location'),
),
),
}
@@ -774,7 +853,18 @@ class RackView(GetRelatedModelsMixin, generic.ObjectView):
])
return {
'related_models': self.get_related_models(request, instance, [CableTermination]),
'related_models': self.get_related_models(
request,
instance,
omit=(CableTermination,),
extra=(
(
VLANGroup.objects.restrict(request.user, 'view').filter(
scope_type=ContentType.objects.get_for_model(Rack),
scope_id=instance.pk
), 'rack'),
),
),
'next_rack': next_rack,
'prev_rack': prev_rack,
'svg_extra': svg_extra,
@@ -934,6 +1024,7 @@ class RackReservationBulkDeleteView(generic.BulkDeleteView):
@register_model_view(Manufacturer, 'list', path='', detail=False)
class ManufacturerListView(generic.ObjectListView):
queryset = Manufacturer.objects.annotate(
racktype_count=count_related(RackType, 'manufacturer'),
devicetype_count=count_related(DeviceType, 'manufacturer'),
moduletype_count=count_related(ModuleType, 'manufacturer'),
inventoryitem_count=count_related(InventoryItem, 'manufacturer'),
@@ -1993,7 +2084,7 @@ class PlatformBulkDeleteView(generic.BulkDeleteView):
@register_model_view(Device, 'list', path='', detail=False)
class DeviceListView(generic.ObjectListView):
queryset = Device.objects.all()
queryset = Device.objects.select_related('virtual_chassis')
filterset = filtersets.DeviceFilterSet
filterset_form = forms.DeviceFilterForm
table = tables.DeviceTable
@@ -2221,54 +2312,14 @@ class DeviceConfigContextView(ObjectConfigContextView):
@register_model_view(Device, 'render-config')
class DeviceRenderConfigView(generic.ObjectView):
class DeviceRenderConfigView(ObjectRenderConfigView):
queryset = Device.objects.all()
template_name = 'dcim/device/render_config.html'
base_template = 'dcim/device/base.html'
tab = ViewTab(
label=_('Render Config'),
weight=2100
weight=2100,
)
def get(self, request, **kwargs):
instance = self.get_object(**kwargs)
context = self.get_extra_context(request, instance)
# If a direct export has been requested, return the rendered template content as a
# downloadable file.
if request.GET.get('export'):
content = context['rendered_config'] or context['error_message']
response = HttpResponse(content, content_type='text')
filename = f"{instance.name or 'config'}.txt"
response['Content-Disposition'] = f'attachment; filename="{filename}"'
return response
return render(request, self.get_template_name(), {
'object': instance,
'tab': self.tab,
**context,
})
def get_extra_context(self, request, instance):
# Compile context data
context_data = instance.get_config_context()
context_data.update({'device': instance})
# Render the config template
rendered_config = None
error_message = None
if config_template := instance.get_config_template():
try:
rendered_config = config_template.render(context=context_data)
except TemplateError as e:
error_message = _("An error occurred while rendering the template: {error}").format(error=e)
return {
'config_template': config_template,
'context_data': context_data,
'rendered_config': rendered_config,
'error_message': error_message,
}
@register_model_view(Device, 'virtual-machines')
class DeviceVirtualMachinesView(generic.ObjectChildrenView):

View File

@@ -155,7 +155,6 @@ class JournalEntryKindChoices(ChoiceSet):
class LogLevelChoices(ChoiceSet):
LOG_DEBUG = 'debug'
LOG_DEFAULT = 'default'
LOG_INFO = 'info'
LOG_SUCCESS = 'success'
LOG_WARNING = 'warning'
@@ -163,16 +162,15 @@ class LogLevelChoices(ChoiceSet):
CHOICES = (
(LOG_DEBUG, _('Debug'), 'teal'),
(LOG_DEFAULT, _('Default'), 'gray'),
(LOG_INFO, _('Info'), 'cyan'),
(LOG_SUCCESS, _('Success'), 'green'),
(LOG_WARNING, _('Warning'), 'yellow'),
(LOG_FAILURE, _('Failure'), 'red'),
)
SYSTEM_LEVELS = {
LOG_DEBUG: logging.DEBUG,
LOG_DEFAULT: logging.INFO,
LOG_INFO: logging.INFO,
LOG_SUCCESS: logging.INFO,
LOG_WARNING: logging.WARNING,
@@ -180,17 +178,6 @@ class LogLevelChoices(ChoiceSet):
}
class DurationChoices(ChoiceSet):
CHOICES = (
(60, _('Hourly')),
(720, _('12 hours')),
(1440, _('Daily')),
(10080, _('Weekly')),
(43200, _('30 days')),
)
#
# Webhooks
#

View File

@@ -76,7 +76,7 @@ DEFAULT_DASHBOARD = [
'height': 4,
'title': 'NetBox News',
'config': {
'feed_url': 'http://netbox.dev/rss/',
'feed_url': 'https://api.netbox.oss.netboxlabs.com/v1/newsfeed/',
'max_entries': 10,
'cache_timeout': 14400,
'requires_internet': True,
@@ -138,9 +138,8 @@ DEFAULT_DASHBOARD = [
LOG_LEVEL_RANK = {
LogLevelChoices.LOG_DEBUG: 0,
LogLevelChoices.LOG_DEFAULT: 1,
LogLevelChoices.LOG_INFO: 2,
LogLevelChoices.LOG_SUCCESS: 3,
LogLevelChoices.LOG_WARNING: 4,
LogLevelChoices.LOG_FAILURE: 5,
LogLevelChoices.LOG_INFO: 1,
LogLevelChoices.LOG_SUCCESS: 2,
LogLevelChoices.LOG_WARNING: 3,
LogLevelChoices.LOG_FAILURE: 4,
}

View File

@@ -9,6 +9,7 @@ import requests
from django import forms
from django.conf import settings
from django.core.cache import cache
from django.db.models import Model
from django.template.loader import render_to_string
from django.urls import NoReverseMatch, resolve, reverse
from django.utils.translation import gettext as _
@@ -42,6 +43,27 @@ def get_object_type_choices():
]
def object_list_widget_supports_model(model: Model) -> bool:
"""Test whether a model is supported by the ObjectListWidget
In theory there could be more than one reason why a model isn't supported by the
ObjectListWidget, although we've only identified one so far--there's no resolve-able 'list' URL
for the model. Add more tests if more conditions arise.
"""
def can_resolve_model_list_view(model: Model) -> bool:
try:
reverse(get_viewname(model, action='list'))
return True
except Exception:
return False
tests = [
can_resolve_model_list_view,
]
return all(test(model) for test in tests)
def get_bookmarks_object_type_choices():
return [
(object_type_identifier(ot), object_type_name(ot))
@@ -234,6 +256,17 @@ class ObjectListWidget(DashboardWidget):
raise forms.ValidationError(_("Invalid format. URL parameters must be passed as a dictionary."))
return data
def clean_model(self):
if model_info := self.cleaned_data['model']:
app_label, model_name = model_info.split('.')
model = ObjectType.objects.get_by_natural_key(app_label, model_name).model_class()
if not object_list_widget_supports_model(model):
raise forms.ValidationError(
_(f"Invalid model selection: {self['model'].data} is not supported.")
)
return model_info
def render(self, request):
app_label, model_name = self.config['model'].split('.')
model = ObjectType.objects.get_by_natural_key(app_label, model_name).model_class()
@@ -257,7 +290,7 @@ class ObjectListWidget(DashboardWidget):
parameters['per_page'] = page_size
parameters['embedded'] = True
if parameters:
if parameters and htmx_url is not None:
try:
htmx_url = f'{htmx_url}?{urlencode(parameters, doseq=True)}'
except ValueError:
@@ -284,7 +317,8 @@ class RSSFeedWidget(DashboardWidget):
class ConfigForm(WidgetConfigForm):
feed_url = forms.URLField(
label=_('Feed URL')
label=_('Feed URL'),
assume_scheme='https'
)
requires_internet = forms.BooleanField(
label=_('Requires external connection'),
@@ -314,7 +348,7 @@ class RSSFeedWidget(DashboardWidget):
return f'dashboard_rss_{url_checksum}'
def get_feed(self):
if self.config['requires_internet'] and settings.ISOLATED_DEPLOYMENT:
if self.config.get('requires_internet') and settings.ISOLATED_DEPLOYMENT:
return {
'isolated_deployment': True,
}

View File

@@ -96,7 +96,7 @@ class CustomFieldChoiceSetImportForm(CSVModelForm):
class Meta:
model = CustomFieldChoiceSet
fields = (
'name', 'description', 'extra_choices', 'order_alphabetically',
'name', 'description', 'base_choices', 'extra_choices', 'order_alphabetically',
)
def clean_extra_choices(self):

View File

@@ -37,6 +37,7 @@ __all__ = (
class CustomFieldFilterForm(SavedFiltersMixin, FilterForm):
model = CustomField
fieldsets = (
FieldSet('q', 'filter_id'),
FieldSet(
@@ -115,6 +116,7 @@ class CustomFieldFilterForm(SavedFiltersMixin, FilterForm):
class CustomFieldChoiceSetFilterForm(SavedFiltersMixin, FilterForm):
model = CustomFieldChoiceSet
fieldsets = (
FieldSet('q', 'filter_id'),
FieldSet('base_choices', 'choice', name=_('Choices')),
@@ -129,6 +131,7 @@ class CustomFieldChoiceSetFilterForm(SavedFiltersMixin, FilterForm):
class CustomLinkFilterForm(SavedFiltersMixin, FilterForm):
model = CustomLink
fieldsets = (
FieldSet('q', 'filter_id'),
FieldSet('object_type', 'enabled', 'new_window', 'weight', name=_('Attributes')),
@@ -159,6 +162,7 @@ class CustomLinkFilterForm(SavedFiltersMixin, FilterForm):
class ExportTemplateFilterForm(SavedFiltersMixin, FilterForm):
model = ExportTemplate
fieldsets = (
FieldSet('q', 'filter_id'),
FieldSet('data_source_id', 'data_file_id', name=_('Data')),
@@ -200,6 +204,7 @@ class ExportTemplateFilterForm(SavedFiltersMixin, FilterForm):
class ImageAttachmentFilterForm(SavedFiltersMixin, FilterForm):
model = ImageAttachment
fieldsets = (
FieldSet('q', 'filter_id'),
FieldSet('object_type_id', 'name', name=_('Attributes')),
@@ -216,6 +221,7 @@ class ImageAttachmentFilterForm(SavedFiltersMixin, FilterForm):
class SavedFilterFilterForm(SavedFiltersMixin, FilterForm):
model = SavedFilter
fieldsets = (
FieldSet('q', 'filter_id'),
FieldSet('object_type', 'enabled', 'shared', 'weight', name=_('Attributes')),
@@ -314,6 +320,7 @@ class TagFilterForm(SavedFiltersMixin, FilterForm):
class ConfigContextFilterForm(SavedFiltersMixin, FilterForm):
model = ConfigContext
fieldsets = (
FieldSet('q', 'filter_id', 'tag_id'),
FieldSet('data_source_id', 'data_file_id', name=_('Data')),
@@ -403,6 +410,7 @@ class ConfigContextFilterForm(SavedFiltersMixin, FilterForm):
class ConfigTemplateFilterForm(SavedFiltersMixin, FilterForm):
model = ConfigTemplate
fieldsets = (
FieldSet('q', 'filter_id', 'tag'),
FieldSet('data_source_id', 'data_file_id', name=_('Data')),
@@ -469,6 +477,7 @@ class JournalEntryFilterForm(NetBoxModelFilterSetForm):
class NotificationGroupFilterForm(SavedFiltersMixin, FilterForm):
model = NotificationGroup
user_id = DynamicModelMultipleChoiceField(
queryset=User.objects.all(),
required=False,

View File

@@ -14,7 +14,7 @@ from netbox.events import get_event_type_choices
from netbox.forms import NetBoxModelForm
from tenancy.models import Tenant, TenantGroup
from users.models import Group, User
from utilities.forms import add_blank_choice, get_field_value
from utilities.forms import get_field_value
from utilities.forms.fields import (
CommentField, ContentTypeChoiceField, ContentTypeMultipleChoiceField, DynamicModelChoiceField,
DynamicModelMultipleChoiceField, JSONField, SlugField,
@@ -162,6 +162,7 @@ class CustomFieldForm(forms.ModelForm):
class CustomFieldChoiceSetForm(forms.ModelForm):
# TODO: The extra_choices field definition diverge from the CustomFieldChoiceSet model
extra_choices = forms.CharField(
widget=ChoicesWidget(),
required=False,
@@ -178,12 +179,25 @@ class CustomFieldChoiceSetForm(forms.ModelForm):
def __init__(self, *args, initial=None, **kwargs):
super().__init__(*args, initial=initial, **kwargs)
# Escape colons in extra_choices
# TODO: The check for str / list below is to handle difference in extra_choices field definition
# In CustomFieldChoiceSetForm, extra_choices is a CharField but in CustomFieldChoiceSet, it is an ArrayField
# if standardize these, we can simplify this code
# Convert extra_choices Array Field from model to CharField for form
if 'extra_choices' in self.initial and self.initial['extra_choices']:
choices = []
for choice in self.initial['extra_choices']:
choice = (choice[0].replace(':', '\\:'), choice[1].replace(':', '\\:'))
choices.append(choice)
extra_choices = self.initial['extra_choices']
if isinstance(extra_choices, str):
extra_choices = [extra_choices]
choices = ""
for choice in extra_choices:
# Setup choices in Add Another use case
if isinstance(choice, str):
choice_str = ":".join(choice.replace("'", "").replace(" ", "")[1:-1].split(","))
choices += choice_str + "\n"
# Setup choices in Edit use case
elif isinstance(choice, list):
choice_str = ":".join(choice)
choices += choice_str + "\n"
self.initial['extra_choices'] = choices
@@ -673,8 +687,7 @@ class ImageAttachmentForm(forms.ModelForm):
class JournalEntryForm(NetBoxModelForm):
kind = forms.ChoiceField(
label=_('Kind'),
choices=add_blank_choice(JournalEntryKindChoices),
required=False
choices=JournalEntryKindChoices
)
comments = CommentField()

View File

@@ -1,7 +1,7 @@
from django import forms
from django.utils.translation import gettext_lazy as _
from extras.choices import DurationChoices
from core.choices import JobIntervalChoices
from utilities.forms.widgets import DateTimePicker, NumberWithOptions
from utilities.datetime import local_now
@@ -22,7 +22,7 @@ class ReportForm(forms.Form):
min_value=1,
label=_("Recurs every"),
widget=NumberWithOptions(
options=DurationChoices
options=JobIntervalChoices
),
help_text=_("Interval at which this report is re-run (in minutes)")
)

View File

@@ -1,7 +1,7 @@
from django import forms
from django.utils.translation import gettext_lazy as _
from extras.choices import DurationChoices
from core.choices import JobIntervalChoices
from utilities.forms.widgets import DateTimePicker, NumberWithOptions
from utilities.datetime import local_now
@@ -28,7 +28,7 @@ class ScriptForm(forms.Form):
min_value=1,
label=_("Recurs every"),
widget=NumberWithOptions(
options=DurationChoices
options=JobIntervalChoices
),
help_text=_("Interval at which this script is re-run (in minutes)")
)

View File

@@ -100,7 +100,10 @@ class ScriptJob(JobRunner):
# Execute the script. If commit is True, wrap it with the event_tracking context manager to ensure we process
# change logging, event rules, etc.
with ExitStack() as stack:
for request_processor in registry['request_processors']:
stack.enter_context(request_processor(request))
if commit:
with ExitStack() as stack:
for request_processor in registry['request_processors']:
stack.enter_context(request_processor(request))
self.run_script(script, request, data, commit)
else:
self.run_script(script, request, data, commit)

View File

@@ -5,7 +5,6 @@ import requests
from django.conf import settings
from django.core.cache import cache
from django.core.management.base import BaseCommand
from django.db import DEFAULT_DB_ALIAS
from django.utils import timezone
from packaging import version
@@ -53,7 +52,7 @@ class Command(BaseCommand):
ending=""
)
self.stdout.flush()
ObjectChange.objects.filter(time__lt=cutoff)._raw_delete(using=DEFAULT_DB_ALIAS)
ObjectChange.objects.filter(time__lt=cutoff).delete()
if options['verbosity']:
self.stdout.write("Done.", self.style.SUCCESS)
elif options['verbosity']:

View File

@@ -81,12 +81,17 @@ class Command(BaseCommand):
logger.error(f'\t{field}: {error.get("message")}')
raise CommandError()
# Remove extra fields from ScriptForm before passng data to script
form.cleaned_data.pop('_schedule_at')
form.cleaned_data.pop('_interval')
form.cleaned_data.pop('_commit')
# Execute the script.
job = ScriptJob.enqueue(
instance=script_obj,
user=user,
immediate=True,
data=data,
data=form.cleaned_data,
request=NetBoxFakeRequest({
'META': {},
'POST': data,

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