Compare commits

...

179 Commits

Author SHA1 Message Date
Jeremy Stretch
5f184f2435 Merge pull request #12507 from netbox-community/develop
Release v3.5.1
2023-05-05 12:50:30 -04:00
jeremystretch
56a4d0333e Formatting fix 2023-05-05 12:31:12 -04:00
jeremystretch
6794742213 Release v3.5.1 2023-05-05 12:29:10 -04:00
jeremystretch
a29a07ed26 Fixes #12463: Fix the association of completed jobs with reports & scripts in the REST API 2023-05-05 10:17:13 -04:00
jeremystretch
42c80f69e6 Changelog for #11715, #11801, #11932, #12122, #12245, #12416, #12476, #12483, #12496 2023-05-05 10:01:54 -04:00
Abhimanyu Saharan
ca0e7be637 Adds bulk import for journal entry (#12485)
* adds bulk import for journal entry #12122

* lint fix

* Add kind as CSVChoiceField on JournalEntryImportForm

---------

Co-authored-by: jeremystretch <jstretch@netboxlabs.com>
2023-05-05 09:57:09 -04:00
Abhimanyu Saharan
42346702a1 Adds image attachment list view (#12487)
* adds image attachment list view #11932

* fixed typo

* Update netbox/extras/tables/tables.py

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>

* Update netbox/extras/forms/filtersets.py

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>

* changes as per review

* Disable ordering by size (not stored in database)

---------

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>
2023-05-05 09:48:13 -04:00
Arthur Hanson
9909213c0d 12416 warning for missing script file (#12456)
* 12416 warning for missing script file

* 12416 widen exception catching for internal script error

* Update netbox/extras/models/scripts.py

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>

* 12416 update from review feedback

---------

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>
2023-05-05 09:37:38 -04:00
Daniel Sheppard
7a38f601de Fixes: #11715 - Fix Parent Prefix table display (#12448)
* Fixes: #11715 - Fix Parent Prefix table display of global vrf prefixes that are **not** containers.

* Combine AND into a single Q object

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>

---------

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>
2023-05-05 09:35:05 -04:00
Abhimanyu Saharan
abdcfdecf5 Adds description to elevation device tooltip (#12488)
* adds description to elevation device tooltip #11801

* changes as per review

* changes as per review

* Rearrange attrs, add headings, and update docstring

---------

Co-authored-by: jeremystretch <jstretch@netboxlabs.com>
2023-05-05 09:09:21 -04:00
Luke Anderson
9d62174e1e Fix #12245 - Add WLAN to InterfaceBulkEditForm 2023-05-05 08:41:40 -04:00
Patrick Hurrelmann
a96b76a8d1 Fixes #12496: Remove account field from provider template 2023-05-05 08:27:29 -04:00
Tobias Genannt
ab69faab87 Fix #12483: Using mutable dulwich configuration 2023-05-04 16:56:45 -04:00
Arthur
f3826e6235 fix runscript command 2023-05-04 16:18:44 -04:00
jeremystretch
3eba65b5c2 Changelog for #10757, #11652, #11791, #11190, #12363, #12464 2023-05-04 14:14:21 -04:00
Arthur Hanson
683ef30af4 12363 update paragraph spacing on journal table (#12435)
* 12363 update paragraph spacing on journal table

* 12363 make css rule generic

* 12363 change p tag to only effect last-child

* 12363 change p table spacing to .5em

* 12363 move comment
2023-05-04 14:05:32 -04:00
Daniel Sheppard
46914d9479 Fixes: #10757 - Change IP interface assignment to use new selector (#12452)
* Fixes: #10757 - Change interface assignment to use new selector.  Perform the same change to the NAT assignment as well.

* Remove nat_vrf from form and remove query_params that are not required anymore
2023-05-04 13:59:28 -04:00
Abhimanyu Saharan
ea8a0135ad Adds module status to module bay table (#12455)
* adds module status to module bay table #11652

* removed the extra line

* updated field name
2023-05-04 13:46:31 -04:00
Abhimanyu Saharan
25142e037a Adds housekeeping systemd files (#12457)
* adds housekeeping systemd files #11190

* Clean up Markdown

---------

Co-authored-by: jeremystretch <jstretch@netboxlabs.com>
2023-05-04 13:43:40 -04:00
Abhimanyu Saharan
93b912c2da Adds ENGINE to database config (#12458)
* adds ENGINE to database config #11791

* fixed lint issues

* updated doc
2023-05-04 13:36:52 -04:00
Tobias Genannt
4df517e4da Fix #12464: Only set username, password for HTTP/s (#12482) 2023-05-04 13:34:04 -04:00
jeremystretch
2c756873aa Fix broken links 2023-05-04 08:43:17 -04:00
jeremystretch
01fa6e28cd Changelog for #10759, #11422, #11504, #12433 2023-05-03 09:32:48 -04:00
Arthur Hanson
5036020dc0 12433 update object list widget to correctly parameterize urls (#12434)
* 12433 update object list widget to correctly parameterize urls

* Update netbox/extras/dashboard/widgets.py

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>

* 12433 fix indent

* Correct per_page query parameter

---------

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>
2023-05-03 09:20:53 -04:00
Arthur
78ec3a6411 11504 add rack filter to elevation 2023-05-03 08:40:43 -04:00
Arthur
24650d9118 11422 add power-panel-name to quick search of power feeds 2023-05-03 08:36:12 -04:00
Austin de Coup-Crank
b14a514b47 Closes 10759: Enable markdown support for custom field descriptions (#12344)
* enable markdown in custom field descriptions

* Closes #10759: Enable markdown support for custom field descriptions

---------

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>
2023-05-02 16:47:22 -04:00
jeremystretch
7aa8434575 Changelog for #12367, #12410, #12436 2023-05-02 16:40:56 -04:00
Arthur
fbcf4c268b 12436 remove add button from contactassignment list view 2023-05-02 16:35:23 -04:00
Abhimanyu Saharan
a566a56a64 fixes RelatedObjectDoesNotExist #12367 2023-05-02 09:48:16 -04:00
jeremystretch
cc3b95bdb0 Fixes #12400: Validate default values for object and multi-object custom fields 2023-05-02 09:35:25 -04:00
jeremystretch
2099cd0fdc #12415: Bump django-rq to v2.8.0 2023-05-02 09:35:25 -04:00
Jop Zinkweg
3bdbf67b8f Update examples to reflect obj rename to object
#8684 missed some references to ```obj```
2023-05-02 08:31:33 -04:00
jeremystretch
20f0464824 Fix OpanAPI schema base path 2023-05-01 17:01:51 -04:00
jeremystretch
1952707702 Fixes #12401: Support the creation of front ports without a pre-populated device ID 2023-05-01 16:51:10 -04:00
jeremystretch
9319cffb1c Fixes #12384: Add a three-second timeout for RSS reader widget 2023-05-01 16:19:39 -04:00
jeremystretch
261f5e4995 Fixes #12415: Pin rq to v1.13.0 to fix ImportError exception from django-rq 2023-05-01 14:38:51 -04:00
jeremystretch
8cede0daf8 Changelog for #12380, #12395, #12396, #12405, #12412 2023-05-01 14:19:56 -04:00
jeremystretch
139ef7ef4c Fixes #12395: Fix "create & add another" action for objects with custom fields 2023-05-01 14:17:50 -04:00
jeremystretch
47f3023401 Fixes #12412: Device/VM interface MAC addresses can be nullified via REST API 2023-05-01 13:06:10 -04:00
Jeremy Stretch
a0f0b29432 Merge pull request #12382 from kkthxbye-code/12380-widget-fix-missing-ct
Fixes #12380 - Add ObjectChange as a valid option for ObjectListWidget and ObjectCountsWidget
2023-05-01 10:17:11 -04:00
Jeremy Stretch
f86f4f9257 Merge pull request #12406 from kkthxbye-code/12405-fix-related-vlangroup
Fixes #12405 - Fix the filtervar being set to site_id instead of site in SiteView related_models
2023-05-01 10:14:29 -04:00
Jeremy Stretch
3fc7c0edc7 Merge pull request #12407 from kkthxbye-code/12396-fix-provideraccount
Fixes #12396 - Mark provider_account as not required in API and bulk import
2023-05-01 10:12:10 -04:00
kkthxbye-code
528fb21a7e Mark provider_account as not required in API and bulk import 2023-05-01 07:44:15 +02:00
kkthxbye-code
6206d226ae Fix the filtervar being set to site_id instead of site in SiteView related_models 2023-05-01 07:15:00 +02:00
kkthxbye-code
aabaeec1d7 Add ObjectChange as a valid option for ObjectListWidget and ObjectCountsWidget 2023-04-28 12:17:39 +02:00
jeremystretch
25dc7e234d PRVB 2023-04-27 14:52:07 -04:00
Jeremy Stretch
eac7d01977 Merge pull request #12371 from netbox-community/develop
Release v3.5.0
2023-04-27 14:38:56 -04:00
jeremystretch
a5bc9d4a2d Release v3.5.0 2023-04-27 14:24:44 -04:00
jeremystretch
b3efb14176 Remove pinned version dependencies 2023-04-27 14:09:16 -04:00
Jeremy Stretch
a2f4fce5b3 Merge pull request #12370 from netbox-community/feature
Prepare for v3.5.0 release
2023-04-27 14:01:23 -04:00
jeremystretch
6109bef700 Merge branch 'develop' into feature 2023-04-27 12:11:08 -04:00
Jeremy Stretch
72767fb5b7 Merge pull request #12366 from netbox-community/develop
Release v3.4.10
2023-04-27 12:03:16 -04:00
jeremystretch
84089ab8c5 Release v3.4.10 2023-04-27 11:47:42 -04:00
Arthur Hanson
9a788349a9 12252 allow sorting on object in search (#12357)
* 12252 allow sorting on object in search

* 12252 code review changes
2023-04-27 11:26:14 -04:00
jeremystretch
b7140a0e4a Closes #12343: Enforce a minimum length for SECRET_KEY configuration parameter 2023-04-27 10:35:39 -04:00
Jeremy Stretch
d39c796828 Merge pull request #12356 from netbox-community/11607-custom-field-cable
11607 make CableSerializer use WritableNestedSerializer
2023-04-27 09:30:30 -04:00
Jeremy Stretch
4a92f6867a Merge pull request #12358 from x64x6a/develop
Add additional characters to exclude from url encode
2023-04-27 08:50:45 -04:00
x64x6a
4355085124 Fixes #12355: Exclude additional characters from url encode 2023-04-26 15:53:14 -07:00
Arthur
5d4ef5e9e5 11607 make CableSerializer WritableNestedSerializer for to_internal value instantiation 2023-04-26 13:27:55 -07:00
jeremystretch
f49e4ee512 Merge branch 'develop' into feature 2023-04-26 15:09:51 -04:00
Jeremy Stretch
f867cb3ae0 Merge pull request #12354 from netbox-community/develop
Release v3.4.9
2023-04-26 14:54:08 -04:00
jeremystretch
a49fdad5e1 Release v3.4.9 2023-04-26 14:33:23 -04:00
Arthur
1ad029712e #11902 validate device on inventory item import 2023-04-26 14:22:37 -04:00
jeremystretch
d87235af2f Closes #12337: Enable anonymized reporting of census data 2023-04-26 10:44:56 -04:00
jeremystretch
99af126fac Closes #11386: Introduce CSRF_COOKIE_SECURE, SECURE_SSL_REDIRECT, and SESSION_COOKIE_SECURE configuration parameters 2023-04-25 16:29:01 -04:00
jeremystretch
83cea218b5 Changelog for #12195, #12218, #12278 2023-04-25 14:49:43 -04:00
jeremystretch
9eb38ab7b2 Delete obsolete static resources 2023-04-25 14:48:00 -04:00
Abhimanyu Saharan
d3206d9bf9 Added method to update viewset description (#12218)
* wip

* wip

* updated description on viewset

* fixed model name

* Update schema.py

* Update schema.py
2023-04-25 14:37:05 -04:00
Austin de Coup-Crank
adb9673f09 Fixes #11623: obfuscate Wi-Fi PSKs (#12244)
* Fixes #11623: obfuscate Wi-Fi PSKs

* yarn linting fixes

* include static files
2023-04-24 12:13:28 -04:00
PieterL75
b693123f6e Fixes #10987: Show rack-list dropdown in rack (#11779)
* Intial. 2 ways the racknavigation displayed

* show active rack in dropdown

* auto hide/show when viewport reduces

* Dropdown only

* Update links to use get_absolute_url()

---------

Co-authored-by: Pieter Lambrecht <pieter.lambrecht@sentia.com>
Co-authored-by: jeremystretch <jstretch@netboxlabs.com>
2023-04-24 12:01:33 -04:00
jeremystretch
e7663b7e39 Mark Provider.account as deprecated 2023-04-21 16:21:04 -04:00
jeremystretch
053be952ba Fixes #12238: Improve error message for API token IP prefix validation failures 2023-04-21 16:06:33 -04:00
jeremystretch
390619ca99 Changelog for #11383, #12205, #12226, #12255 2023-04-21 15:40:34 -04:00
jeremystretch
b1130ff9b6 Add an issue template for deprecations 2023-04-21 15:38:27 -04:00
Darek
89fa546a14 Merge pull request from GHSA-92x4-vfjf-rmf7 2023-04-21 15:08:04 -04:00
jeremystretch
c8988bac8a Add graphics 2023-04-21 13:46:07 -04:00
Arthur Hanson
55385dd0db 12278 add ipaddressfield serializer for OpenAPI spectacular typing (#12285)
* #12278 add serializer for ipaddressfield to remove spectacular warnings

* #12278 add ipaddressfieldserializer to nested serializers

* #12278 fix to_internal_value to_representation in serializer

* #12278 to_internal_value is called before validation! need to raise validation error if incorrect format

* #12278 to_internal_value needs to return value doh

* #12278 move IPAddressField to field_serializers

* #12278 remove old import

* 12278 remove validator
2023-04-21 12:41:03 -04:00
Arthur Hanson
38a0ed5e24 12255 inventory item device change (#12311)
* #12255 allow inventory items to change devices

* #12255 allow inventory item template to change devices

* #12255 fix init

* 12255 remove can_swtich from template model

* 12255 change to check module list
2023-04-21 12:36:11 -04:00
Arthur
15d80f4e1b 12195 remove incorrect null=True on choice fields 2023-04-21 12:23:07 -04:00
jeremystretch
2fe5592c3c Fixes #12299: Fix object list widget support for filtering by multiple values 2023-04-21 11:54:28 -04:00
jeremystretch
8cf0a79dee Changelog for #12149, #12256, #12288 2023-04-21 11:40:28 -04:00
jeremystretch
183c5ca667 Update screenshots 2023-04-21 11:35:35 -04:00
jeremystretch
d5c4b1e27c #10520: Remove obsolete NAPALM documentation 2023-04-21 11:22:38 -04:00
jeremystretch
2fcdc0ae6a #10520: Restore ability to edit platform NAPALM fields via UI 2023-04-21 11:21:42 -04:00
Janik H
12bb0ec1fe Fix typo in api token auth 2023-04-21 10:01:13 -04:00
Austin de Coup-Crank
8b7ee0a0db 11383 fix search order (#12251)
* Fixes #11383: Sorting search by type doesn't work

* Fixes #11383: Sorting search by type doesn't work; more reliable approach
2023-04-20 17:04:47 -04:00
Arthur Hanson
274cd5d56c 12288 add servers to spectacular settings (#12300)
* 12288 add servers to spectacular settings

* 12288 standardize quotes

* Account for BASE_PATH

---------

Co-authored-by: jeremystretch <jstretch@netboxlabs.com>
2023-04-20 15:56:21 -04:00
Luke Anderson
ab3531558a Closes #12226: Add Profile Data Headers to Remote Authentication Middleware (#12253)
* Closes #12226: Add Profile Data Headers to Remote Authentication Middleware

* Tweak documentation

---------

Co-authored-by: jeremystretch <jstretch@netboxlabs.com>
2023-04-20 15:49:54 -04:00
Arthur
dda56f21f3 #12256 remove read-only fields from writable serializers 2023-04-20 14:11:55 -04:00
Arthur
31c909c368 #12149 remove spectacular choice mapping fixup internal one 2023-04-20 14:10:05 -04:00
jeremystretch
164b2a5016 Fixes #12270: Fix pre-population of list values when creating a saved filter 2023-04-19 17:41:38 -04:00
jeremystretch
7b374e4cf6 Fixes #12296: Fix 'mark connected' form field for bulk editing front & rear ports 2023-04-19 17:25:32 -04:00
jeremystretch
13625325f5 #8684: Fix test 2023-04-19 11:31:26 -04:00
jeremystretch
b84ac184c2 #8684: Remove obsolete 'obj' var from custom link context 2023-04-19 09:58:18 -04:00
jeremystretch
d5d2431cbd Docs cleanup for v3.5 2023-04-18 16:58:53 -04:00
jeremystretch
c08c7dda50 Closes #12292: Replace SelectSpeedWidget and SelectDurationWidget with NumberWithOptions 2023-04-18 16:33:43 -04:00
jeremystretch
b807198e6d Rename ImportForm to BulkImportForm 2023-04-18 15:27:05 -04:00
jeremystretch
9caa7f6b7c Move SyncedDataMixin from extras to core 2023-04-18 15:18:19 -04:00
jeremystretch
4452f57f90 Release v3.5-beta2 2023-04-18 09:21:15 -04:00
jeremystretch
b167153186 Enable scheduling_enabled parameter for reports 2023-04-18 08:45:31 -04:00
jeremystretch
197c6a1cbf Add scheduling_enabled parameter for scripts 2023-04-18 08:45:31 -04:00
jeremystretch
014a5d10d1 Closes #12187: Add button to download rendered config from UI 2023-04-17 16:37:02 -04:00
jeremystretch
86d185fe05 Fix validation of DataSource URL 2023-04-17 16:00:35 -04:00
Tobias Genannt
9ef1fb1e3a Use dulwich as Git client 2023-04-17 15:53:50 -04:00
jeremystretch
7ecf3be33c Clean up script & report job views 2023-04-17 15:27:12 -04:00
jeremystretch
a0893c2e8b Add general purpose view for individual jobs 2023-04-17 15:08:18 -04:00
Jeremy Stretch
8b040ff930 Closes #12129: Enable automatic synchronization of objects when DataFiles are updated (#12262)
* Closes #12129: Enable automatic synchronization of objects when DataFiles are updated

* Cleanup
2023-04-17 10:35:17 -04:00
Jeremy Stretch
d470848b29 Closes #12246: General cleanup of utilities modules
* Clean up base modules

* Clean up forms modules

* Clean up templatetags modules

* Replace custom simplify_decimal filter with floatformat

* Misc cleanup

* Merge ReturnURLForm into ConfirmationForm

* Clean up import statements for utilities.forms

* Fix field class references in docs
2023-04-14 10:33:53 -04:00
jeremystretch
59a6b3e71b Merge branch 'develop' into feature 2023-04-12 17:38:16 -04:00
jeremystretch
c1c98f9883 Closes #12232: Annotate direct URL for release notes for all projects 2023-04-12 17:30:00 -04:00
jeremystretch
dd8112c30e PRVB 2023-04-12 15:33:22 -04:00
Jeremy Stretch
3c91331e16 Merge pull request #12234 from netbox-community/develop
Release v3.4.8
2023-04-12 15:29:09 -04:00
jeremystretch
eef38257b9 Release v3.4.8 2023-04-12 14:06:09 -04:00
Austin de Coup-Crank
bb9a125934 Closes #12040: fix bulk import tab selection 2023-04-12 13:01:04 -04:00
Arthur Hanson
8de252e34e 11432 device field (#11567)
* 11432 make device field on interface read-only on api edit call

* 11432 make device field on interface read-only on api edit call

* 11432 extend serializer change to mixin

* 11432 add readonlydevicemixin to template serializers

* 11432 change subclass ordering

* 11432 fix device_type for template serializers

* 11432 DRY

* 11432 DRY

* 11432 make internal var

* 11432 change to model-level validation

* 11432 fix fk accessor

* Clean up validation error messages

---------

Co-authored-by: jeremystretch <jstretch@netboxlabs.com>
2023-04-12 10:25:54 -04:00
Arthur Hanson
9e305c6181 Closes #12207: Establish a permission for creating API tokens on behalf of other users (#12192)
* 11091 add permission to allow user to create api tokens for other users

* 11091 update docs

* 11091 fix for test

* 11091 fix for test

* 11091 test case for invalid token creation

* 11091 add test for permission grant

* Cleanup & fix serializer validation

---------

Co-authored-by: jeremystretch <jstretch@netboxlabs.com>
2023-04-12 10:25:06 -04:00
pobradovic08
97ed6439ce Fixes #12227: L2VPN Bulk import not setting Tenant field 2023-04-12 09:24:31 -04:00
jeremystretch
15a615d3a3 Optimize migrations 2023-04-11 16:08:41 -04:00
jeremystretch
3528aaee2c Update release notes 2023-04-11 15:56:34 -04:00
jeremystretch
46d7bf02ac Add tests for ConfigTemplate 2023-04-11 15:25:48 -04:00
jeremystretch
6820796c10 Closes #10414: Enable general purpose image attachments for device types 2023-04-10 16:43:40 -04:00
jeremystretch
4a331b560f Closes #11015: Remove unit from commit rate column header in circuits table 2023-04-10 16:35:21 -04:00
jeremystretch
4c9cf9032c Changelog for #10221, #10600, #11431, #11454 2023-04-10 14:06:36 -04:00
jeremystretch
ada01b39cc #10221: Tweak variable names & error message 2023-04-10 14:03:59 -04:00
Abhimanyu Saharan
b41f8755df Fixes GenericForeignKey validation (#11550)
* added model validation for GenericForeignKey

* added ct_field and fk_field null validation

* applied suggestion
2023-04-10 14:02:32 -04:00
Abhimanyu Saharan
2c07762b7a Added optional user and group on custom field (#12206)
* added group and user model to object_type

* Update netbox/utilities/utils.py

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>

---------

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>
2023-04-10 12:40:13 -04:00
jeremystretch
f68a63255b #11029: Cleanup & changelog 2023-04-10 10:40:56 -04:00
kkthxbye
278f2b173a Fixes #11431 - Disallow changing customfield type after creation (#11449)
* Disallow changing customfield type after creation

* Fix test_api.CustomFieldTest

---------

Co-authored-by: kkthxbye-code <>
2023-04-10 10:13:08 -04:00
Arthur Hanson
00714b23a2 11029 add changelog on CableTermination (#11407)
* 11209 add changelog on CableTermination

* Rename migration

---------

Co-authored-by: jeremystretch <jstretch@netboxlabs.com>
2023-04-10 10:11:58 -04:00
jeremystretch
768d6f624e Fixes #12191: Change absolute image path to relative 2023-04-10 09:17:13 -04:00
jeremystretch
1146aaff89 Closes #11453: Display a warning banner when DEBUG is enabled 2023-04-10 09:12:04 -04:00
Arthur Hanson
5a4feb7099 10615 filter cable termination_id with cable_end (#12182)
* 10615 filter cable termination_id with cable_end

* 10615 filter distinct

* 10615 filter distinct
2023-04-07 14:13:58 -04:00
jeremystretch
589d51e028 Merge branch 'develop' into feature 2023-04-07 13:58:56 -04:00
jeremystretch
a6fd0ab09a #12007: Move vlan & vlan_id filter methods to CommonInterfaceFilterSet 2023-04-07 13:58:12 -04:00
jeremystretch
08017c51f6 Merge branch 'develop' into feature 2023-04-07 13:00:00 -04:00
jeremystretch
9f71cf79e6 Changelog for #12007, #12118 2023-04-07 11:54:43 -04:00
Abhimanyu Saharan
c26fe266cc Moved interface filterset under common class (#12200)
* moved interface filterset under common class #12007

* lint fix
2023-04-07 10:54:39 -04:00
jeremystretch
085cfc58f4 Fixes #12184: Fix filtered bulk deletion for various models 2023-04-07 10:25:36 -04:00
jeremystretch
63a0ec7a79 Fixes #12190: Fix form layout for plugin textarea fields 2023-04-07 10:03:47 -04:00
jeremystretch
ccfdc216a5 Fixes #12118: Refactor bulk creation logic under _instantiate_components() 2023-04-06 17:01:46 -04:00
Jeremy Stretch
2bf9acfb19 Closes #12193: Clean up tests (#12197)
* Fix skipped API tests

* Remove invalid tests

* Correct logger name
2023-04-06 16:35:27 -04:00
jeremystretch
74d8baea30 Remove NS1 from sponsors list 2023-04-06 14:32:57 -04:00
jeremystretch
f8d40ae824 Changelog for #11746, #12011, #12087 2023-04-05 13:32:18 -04:00
Daniel Sheppard
41c92483a0 #12087 - Fix Bulk Edit update when M2M operations are present. (#12169)
* #12087 - Fix Bulk Edit update when M2M operations are present.

* #12087 - Minor tweaks

* Change .set() to .clear()

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>

* #12087 - Update comments

---------

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>
2023-04-05 13:29:32 -04:00
jeremystretch
6d6299f0cb #11584: Linkify assigment counts in contacts table 2023-04-05 12:53:39 -04:00
jeremystretch
f44a2ba0ee Closes #12119: Lock & unlock dashboard layout 2023-04-05 09:59:22 -04:00
jeremystretch
29fbe6e4ee Closes #12126: Introduce a DEFAULT_DASHBOARD config parameter 2023-04-05 08:32:18 -04:00
Arthur Hanson
94c2a2e56c 11746 fix delete custom field (#12092)
* 11746 delete custom field

* 11746 use filter instead of exclude
2023-04-04 16:38:48 -04:00
Arthur
0a2ae90411 12011 fix module bay bulk create 2023-04-04 16:34:51 -04:00
jeremystretch
1b5f926e17 Fixes #12167: Catch and report on exceptions raised when rendering a config template 2023-04-04 08:47:01 -04:00
Arthur Hanson
13cbb33c98 12148 add swagger-sidecar for self-hosted swagger docs (#12159)
* 12148 add swagger-sidecar for self-hosted swagger docs

* 12149 add to base_requirements
2023-04-04 08:23:56 -04:00
jeremystretch
b032742418 Closes #12133: Move any instance mutations inside clean() to save() 2023-04-03 16:26:07 -04:00
jeremystretch
8a684adf66 Changelog for #12074, #12117 2023-04-03 15:38:05 -04:00
Arthur Hanson
bca00cd97a 12117 remove clone from cable (#12130)
* 12117 remove clone from cable

* 12117 remove clone button if no params

* Update clone.html

* Update clone.html

* Update clone.html

---------

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>
2023-04-03 15:27:13 -04:00
Arthur Hanson
2883fa14de Fixes #12074: Move automatic location assignment out of clean()
* 12074 fix full clean

* 12074 move device location setting to save from clean

* 12074 fix set location only if present in rack

* Update base.py

---------

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>
2023-04-03 15:22:36 -04:00
Arthur
56d2a9aa11 12151 remove choice field str mapping for OpenAPI 2023-04-03 15:09:34 -04:00
jeremystretch
53abcc0f5c Closes #12136: Extend object count & list widgets to support filters 2023-04-03 15:02:11 -04:00
jeremystretch
0676ed45c7 Closes #12107: Document support for plugin-provided dashboard widgets 2023-04-03 14:15:18 -04:00
jeremystretch
872b70c2b5 Fixes #12145: Employ HTMXSelect widget to fix inclusion of <select> field values during form regeneration 2023-04-03 12:49:26 -04:00
jeremystretch
2805633b16 Fixes #12144: Ensure consistent treatment of context data when rendering config templates via UI & API 2023-04-03 09:50:07 -04:00
jeremystretch
f245f07fd9 Fixes #12146: Do not display object selector for disabled fields 2023-04-03 09:39:03 -04:00
kkthxbye
e966d1df47 Merge pull request #12139 from tobiasge/fix-data-source-logs
Fix #12138: Log correct count when files were deleted
2023-04-02 22:29:59 +02:00
kkthxbye
e4b2d87ce6 Merge pull request #12143 from tobiasge/fix-missing-s3backend
Fixes #12142: Add S3Backend to __all__
2023-04-02 22:28:08 +02:00
kkthxbye
b3a347e6fb Merge pull request #12141 from tobiasge/fix-typo-in-datasource
Fixes: #12140: Typo in Synchronized Data documentation
2023-04-02 22:24:41 +02:00
Tobias Genannt
e7d1a43541 Fixes #12142: Add S3Backend to __all__ 2023-04-01 11:28:33 +02:00
Tobias Genannt
5ff9483d13 Log correct count when files were deleted 2023-04-01 10:51:33 +02:00
Tobias Genannt
ac07b33602 Fixed typo in Synchronized Data documentation 2023-04-01 10:45:45 +02:00
jeremystretch
8d6c591535 Fixes #12103: Limit the types of objects available for object count & list widgets 2023-03-31 15:30:40 -04:00
jeremystretch
6a85c5b3ce Fixes #12115: Fix rendering config templates from a data file 2023-03-31 10:37:12 -04:00
jeremystretch
bd38b50e5e Fixes #12105: Prevent data sources from becoming stuck in syncing status when an exception is raised 2023-03-31 09:52:07 -04:00
jeremystretch
eb77c0e920 Fixes #12106: Fix exception when saving dashboard widget with minimum width/height 2023-03-31 09:34:50 -04:00
jeremystretch
198c004c1d Fixes #12108: Limit the draggable area of widgets to their headers 2023-03-31 09:26:58 -04:00
jeremystretch
730eb2e83b Fixes #12112: Do not link data source URL for local paths 2023-03-31 09:06:16 -04:00
jeremystretch
cdad50e051 Fixes #12109: Fix migration error when replicating more than 100 job results 2023-03-31 08:59:15 -04:00
jeremystretch
3264636b7a Changelog for #12084, #12095 2023-03-30 17:02:23 -04:00
gdprdatasubect
fbc23424a6 Update models.py
Change default MIME-Type as discussed under #12095
2023-03-30 16:58:41 -04:00
jeremystretch
6f08c4a4be Fixes #11846: Update database creation instructions for PostgreSQL 14+ 2023-03-30 16:35:56 -04:00
jeremystretch
0ac8419005 Fixes #12104: Restore copy-to-clipboard & footer navigation in docs 2023-03-30 16:29:54 -04:00
280 changed files with 3031 additions and 1496 deletions

View File

@@ -14,7 +14,7 @@ body:
attributes:
label: NetBox version
description: What version of NetBox are you currently running?
placeholder: v3.4.7
placeholder: v3.5.1
validations:
required: true
- type: dropdown

24
.github/ISSUE_TEMPLATE/deprecation.yaml vendored Normal file
View File

@@ -0,0 +1,24 @@
---
name: 🗑️ Deprecation
description: The removal of an existing feature or resource
labels: ["type: deprecation"]
body:
- type: textarea
attributes:
label: Proposed Changes
description: >
Describe in detail the proposed changes. What is being removed?
validations:
required: true
- type: textarea
attributes:
label: Justification
description: Please provide justification for the proposed change(s).
validations:
required: true
- type: textarea
attributes:
label: Impact
description: List all areas of the application that will be affected by this change.
validations:
required: true

View File

@@ -14,7 +14,7 @@ body:
attributes:
label: NetBox version
description: What version of NetBox are you currently running?
placeholder: v3.4.7
placeholder: v3.5.1
validations:
required: true
- type: dropdown

View File

@@ -29,9 +29,18 @@ as the cornerstone for network automation in thousands of organizations.
## Getting Started
<div align="center">
[![NetBox logo](https://raw.githubusercontent.com/wiki/netbox-community/netbox/images/deploy/deploy1.png)](https://github.com/netbox-community/netbox)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
[![Docker logo](https://raw.githubusercontent.com/wiki/netbox-community/netbox/images/deploy/deploy2.png)](https://github.com/netbox-community/netbox-docker)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
[![NetBox Labs logo](https://raw.githubusercontent.com/wiki/netbox-community/netbox/images/deploy/deploy3.png)](https://netboxlabs.com/netbox-cloud/)
</div>
* Just want to explore? Check out [our public demo](https://demo.netbox.dev/) right now!
* The [official documentation](https://docs.netbox.dev) offers a comprehensive introduction.
* Choose your deployment: [self-hosted](https://github.com/netbox-community/netbox), [Docker](https://github.com/netbox-community/netbox-docker), or [NetBox Cloud](https://netboxlabs.com/netbox-cloud/).
* Check out [our wiki](https://github.com/netbox-community/netbox/wiki/Community-Contributions) for even more projects to get the most out of NetBox!
## Get Involved
@@ -58,8 +67,6 @@ as the cornerstone for network automation in thousands of organizations.
[![NetBox Labs](https://raw.githubusercontent.com/wiki/netbox-community/netbox/images/sponsors/netbox_labs.png)](https://netboxlabs.com)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
[![DigitalOcean](https://raw.githubusercontent.com/wiki/netbox-community/netbox/images/sponsors/digitalocean.png)](https://try.digitalocean.com/developer-cloud)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
[![NS1](https://raw.githubusercontent.com/wiki/netbox-community/netbox/images/sponsors/ns1.png)](https://ns1.com)
<br />
[![Sentry](https://raw.githubusercontent.com/wiki/netbox-community/netbox/images/sponsors/sentry.png)](https://sentry.io)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

View File

@@ -1,61 +1,61 @@
# HTML sanitizer
# https://github.com/mozilla/bleach
bleach<6.0
# https://github.com/mozilla/bleach/blob/main/CHANGES
bleach
# Python client for Amazon AWS API
# https://github.com/boto/boto3
# https://github.com/boto/boto3/blob/develop/CHANGELOG.rst
boto3
# The Python web framework on which NetBox is built
# https://github.com/django/django
# https://docs.djangoproject.com/en/stable/releases/
Django<4.2
# Django middleware which permits cross-domain API requests
# https://github.com/OttoYiu/django-cors-headers
# https://github.com/adamchainz/django-cors-headers/blob/main/CHANGELOG.rst
django-cors-headers
# Runtime UI tool for debugging Django
# https://github.com/jazzband/django-debug-toolbar
# https://github.com/jazzband/django-debug-toolbar/blob/main/docs/changes.rst
django-debug-toolbar
# Library for writing reusable URL query filters
# https://github.com/carltongibson/django-filter
# https://github.com/carltongibson/django-filter/blob/main/CHANGES.rst
django-filter
# Django debug toolbar extension with support for GraphiQL
# https://github.com/flavors/django-graphiql-debug-toolbar/
# https://github.com/flavors/django-graphiql-debug-toolbar/blob/main/CHANGES.rst
django-graphiql-debug-toolbar
# Modified Preorder Tree Traversal (recursive nesting of objects)
# https://github.com/django-mptt/django-mptt
# https://github.com/django-mptt/django-mptt/blob/main/CHANGELOG.rst
django-mptt
# Context managers for PostgreSQL advisory locks
# https://github.com/Xof/django-pglocks
# https://github.com/Xof/django-pglocks/blob/master/CHANGES.txt
django-pglocks
# Prometheus metrics library for Django
# https://github.com/korfuri/django-prometheus
# https://github.com/korfuri/django-prometheus/blob/master/CHANGELOG.md
django-prometheus
# Django caching backend using Redis
# https://github.com/jazzband/django-redis
# https://github.com/jazzband/django-redis/blob/master/CHANGELOG.rst
django-redis
# Django extensions for Rich (terminal text rendering)
# https://github.com/adamchainz/django-rich
# https://github.com/adamchainz/django-rich/blob/main/CHANGELOG.rst
django-rich
# Django integration for RQ (Reqis queuing)
# https://github.com/rq/django-rq
# https://github.com/rq/django-rq/blob/master/CHANGELOG.md
django-rq
# Abstraction models for rendering and paginating HTML tables
# https://github.com/jieter/django-tables2
# https://github.com/jieter/django-tables2/blob/master/CHANGELOG.md
django-tables2
# User-defined tags for objects
# https://github.com/alex/django-taggit
# https://github.com/jazzband/django-taggit/blob/master/CHANGELOG.rst
django-taggit
# A Django field for representing time zones
@@ -63,31 +63,39 @@ django-taggit
django-timezone-field
# A REST API framework for Django projects
# https://github.com/encode/django-rest-framework
# https://www.django-rest-framework.org/community/release-notes/
djangorestframework
# Sane and flexible OpenAPI 3 schema generation for Django REST framework.
# https://github.com/tfranzel/drf-spectacular
# https://github.com/tfranzel/drf-spectacular/blob/master/CHANGELOG.rst
drf-spectacular
# Serve self-contained distribution builds of Swagger UI and Redoc with Django.
# https://github.com/tfranzel/drf-spectacular-sidecar
drf-spectacular-sidecar
# Git client for file sync
# https://github.com/jelmer/dulwich/releases
dulwich
# RSS feed parser
# https://github.com/kurtmckee/feedparser
# https://github.com/kurtmckee/feedparser/blob/develop/CHANGELOG.rst
feedparser
# Django wrapper for Graphene (GraphQL support)
# https://github.com/graphql-python/graphene-django
# https://github.com/graphql-python/graphene-django/releases
graphene_django
# WSGI HTTP server
# https://gunicorn.org/
# https://docs.gunicorn.org/en/latest/news.html
gunicorn
# Platform-agnostic template rendering engine
# https://github.com/pallets/jinja
# https://jinja.palletsprojects.com/changes/
Jinja2
# Simple markup language for rendering HTML
# https://github.com/Python-Markdown/markdown
# https://python-markdown.github.io/change_log/
# mkdocs currently requires Markdown v3.3
Markdown<3.4
@@ -96,50 +104,49 @@ Markdown<3.4
markdown-include
# MkDocs Material theme (for documentation build)
# https://github.com/squidfunk/mkdocs-material
# https://squidfunk.github.io/mkdocs-material/changelog/
mkdocs-material
# Introspection for embedded code
# https://github.com/mkdocstrings/mkdocstrings
# https://github.com/mkdocstrings/mkdocstrings/blob/master/CHANGELOG.md
mkdocstrings[python-legacy]
# Library for manipulating IP prefixes and addresses
# https://github.com/netaddr/netaddr
# https://github.com/netaddr/netaddr/blob/master/CHANGELOG
netaddr
# Fork of PIL (Python Imaging Library) for image processing
# https://github.com/python-pillow/Pillow
# https://github.com/python-pillow/Pillow/blob/main/CHANGES.rst
Pillow
# PostgreSQL database adapter for Python
# https://github.com/psycopg/psycopg2
# https://www.psycopg.org/docs/news.html
psycopg2-binary
# YAML rendering library
# https://github.com/yaml/pyyaml
# https://github.com/yaml/pyyaml/blob/master/CHANGES
PyYAML
# Sentry SDK
# https://github.com/getsentry/sentry-python
# https://github.com/getsentry/sentry-python/blob/master/CHANGELOG.md
sentry-sdk
# Social authentication framework
# https://github.com/python-social-auth/social-core
# https://github.com/python-social-auth/social-core/blob/master/CHANGELOG.md
social-auth-core
# Django app for social-auth-core
# https://github.com/python-social-auth/social-app-django
# See https://github.com/python-social-auth/social-app-django/issues/429
social-auth-app-django==5.0.0
# https://github.com/python-social-auth/social-app-django/blob/master/CHANGELOG.md
social-auth-app-django
# SVG image rendering (used for rack elevations)
# https://github.com/mozman/svgwrite
# hhttps://github.com/mozman/svgwrite/blob/master/NEWS.rst
svgwrite
# Tabular dataset library (for table-based exports)
# https://github.com/jazzband/tablib
# https://github.com/jazzband/tablib/blob/master/HISTORY.md
tablib
# Timezone data (required by django-timezone-field on Python 3.9+)
# https://github.com/python/tzdata
# https://github.com/python/tzdata/blob/master/NEWS.md
tzdata

View File

@@ -0,0 +1,17 @@
[Unit]
Description=NetBox Housekeeping Service
Documentation=https://docs.netbox.dev/
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=netbox
Group=netbox
WorkingDirectory=/opt/netbox
ExecStart=/opt/netbox/venv/bin/python /opt/netbox/netbox/manage.py housekeeping
[Install]
WantedBy=multi-user.target

View File

@@ -0,0 +1,13 @@
[Unit]
Description=NetBox Housekeeping Timer
Documentation=https://docs.netbox.dev/
After=network-online.target
Wants=network-online.target
[Timer]
OnCalendar=daily
AccuracySec=1h
Persistent=true
[Install]
WantedBy=multi-user.target

View File

@@ -26,6 +26,8 @@ REMOTE_AUTH_BACKEND = 'netbox.authentication.RemoteUserBackend'
Another option for remote authentication in NetBox is to enable HTTP header-based user assignment. The front end HTTP server (e.g. nginx or Apache) performs client authentication as a process external to NetBox, and passes information about the authenticated user via HTTP headers. By default, the user is assigned via the `REMOTE_USER` header, but this can be customized via the `REMOTE_AUTH_HEADER` configuration parameter.
Optionally, user profile information can be supplied by `REMOTE_USER_FIRST_NAME`, `REMOTE_USER_LAST_NAME` and `REMOTE_USER_EMAIL` headers. These are saved to the users profile during the authentication process. These headers can be customized like the `REMOTE_USER` header.
### Single Sign-On (SSO)
```python

View File

@@ -4,7 +4,7 @@
### Enabling Error Reporting
NetBox v3.2.3 and later support native integration with [Sentry](https://sentry.io/) for automatic error reporting. To enable this functionality, simply set `SENTRY_ENABLED` to True in `configuration.py`. Errors will be sent to a Sentry ingestor maintained by the NetBox team for analysis.
NetBox supports native integration with [Sentry](https://sentry.io/) for automatic error reporting. To enable this functionality, simply set `SENTRY_ENABLED` to True in `configuration.py`. Errors will be sent to a Sentry ingestor maintained by the NetBox team for analysis.
```python
SENTRY_ENABLED = True

View File

@@ -7,7 +7,13 @@ NetBox includes a `housekeeping` management command that should be run nightly.
* Deleting job result records older than the configured [retention time](../configuration/miscellaneous.md#job_retention)
* Check for new NetBox releases (if [`RELEASE_CHECK_URL`](../configuration/miscellaneous.md#release_check_url) is set)
This command can be invoked directly, or by using the shell script provided at `/opt/netbox/contrib/netbox-housekeeping.sh`. This script can be linked from your cron scheduler's daily jobs directory (e.g. `/etc/cron.daily`) or referenced directly within the cron configuration file.
This command can be invoked directly, or by using the shell script provided at `/opt/netbox/contrib/netbox-housekeeping.sh`.
## Scheduling
### Using Cron
This script can be linked from your cron scheduler's daily jobs directory (e.g. `/etc/cron.daily`) or referenced directly within the cron configuration file.
```shell
sudo ln -s /opt/netbox/contrib/netbox-housekeeping.sh /etc/cron.daily/netbox-housekeeping
@@ -16,4 +22,28 @@ sudo ln -s /opt/netbox/contrib/netbox-housekeeping.sh /etc/cron.daily/netbox-hou
!!! note
On Debian-based systems, be sure to omit the `.sh` file extension when linking to the script from within a cron directory. Otherwise, the task may not run.
The `housekeeping` command can also be run manually at any time: Running the command outside scheduled execution times will not interfere with its operation.
### Using Systemd
First, create symbolic links for the systemd service and timer files. Link the existing service and timer files from the `/opt/netbox/contrib/` directory to the `/etc/systemd/system/` directory:
```bash
sudo ln -s /opt/netbox/contrib/netbox-housekeeping.service /etc/systemd/system/netbox-housekeeping.service
sudo ln -s /opt/netbox/contrib/netbox-housekeeping.timer /etc/systemd/system/netbox-housekeeping.timer
```
Then, reload the systemd configuration and enable the timer to start automatically at boot:
```bash
sudo systemctl daemon-reload
sudo systemctl enable --now netbox-housekeeping.timer
```
Check the status of your timer by running:
```bash
sudo systemctl list-timers --all
```
This command will show a list of all timers, including your `netbox-housekeeping.timer`. Make sure the timer is active and properly scheduled.
That's it! Your NetBox housekeeping service is now configured to run daily using systemd.

View File

@@ -1,6 +1,6 @@
# Object-Based Permissions
NetBox v2.9 introduced a new object-based permissions framework, which replaces Django's built-in permissions model. Object-based permissions enable an administrator to grant users or groups the ability to perform an action on arbitrary subsets of objects in NetBox, rather than all objects of a certain type. For example, it is possible to grant a user permission to view only sites within a particular region, or to modify only VLANs with a numeric ID within a certain range.
NetBox employs a new object-based permissions framework, which replaces Django's built-in permissions model. Object-based permissions enable an administrator to grant users or groups the ability to perform an action on arbitrary subsets of objects in NetBox, rather than all objects of a certain type. For example, it is possible to grant a user permission to view only sites within a particular region, or to modify only VLANs with a numeric ID within a certain range.
A permission in NetBox represents a relationship shared by several components:
@@ -20,7 +20,7 @@ There are four core actions that can be permitted for each type of object within
* **Change** - Modify an existing object
* **Delete** - Delete an existing object
In addition to these, permissions can also grant custom actions that may be required by a specific model or plugin. For example, the `napalm_read` permission on the device model allows a user to execute NAPALM queries on a device via NetBox's REST API. These can be specified when granting a permission in the "additional actions" field.
In addition to these, permissions can also grant custom actions that may be required by a specific model or plugin. For example, the `run` permission for scripts allows a user to execute custom scripts. These can be specified when granting a permission in the "additional actions" field.
!!! note
Internally, all actions granted by a permission (both built-in and custom) are stored as strings in an array field named `actions`.

View File

@@ -1,5 +1,50 @@
# Default Value Parameters
## DEFAULT_DASHBOARD
This parameter controls the content and layout of user's default dashboard. Once the dashboard has been created, the user is free to customize it as they please by adding, removing, and reconfiguring widgets.
This parameter must specify an iterable of dictionaries, each representing a discrete dashboard widget and its configuration. The follow widget attributes are supported:
* `widget`: Dotted path to the Python class (required)
* `width`: Default widget width (between 1 and 12, inclusive)
* `height`: Default widget height, in rows
* `title`: Widget title
* `color`: Color of the widget's title bar, specified by name
* `config`: Dictionary mapping of any widget configuration parameters
A brief example configuration is provided below.
```python
DEFAULT_DASHBOARD = [
{
'widget': 'extras.ObjectCountsWidget',
'width': 4,
'height': 2,
'title': 'Organization',
'config': {
'models': [
'dcim.site',
'tenancy.tenant',
'tenancy.contact',
]
}
},
{
'widget': 'extras.ObjectCountsWidget',
'title': 'IPAM',
'color': 'blue',
'config': {
'models': [
'ipam.prefix',
'ipam.iprange',
'ipam.ipaddress',
]
}
},
]
```
## DEFAULT_USER_PREFERENCES
!!! tip "Dynamic Configuration Parameter"

View File

@@ -18,4 +18,4 @@ interface.
Default: False
This parameter serves as a safeguard to prevent some potentially dangerous behavior, such as generating new database schema migrations. Set this to `True` **only** if you are actively developing the NetBox code base.
This parameter serves as a safeguard to prevent some potentially dangerous behavior, such as generating new database schema migrations. Additionally, enabling this setting disables the debug warning banner in the UI. Set this to `True` **only** if you are actively developing the NetBox code base.

View File

@@ -30,10 +30,6 @@ Some configuration parameters are primarily controlled via NetBox's admin interf
* [`MAINTENANCE_MODE`](./miscellaneous.md#maintenance_mode)
* [`MAPS_URL`](./miscellaneous.md#maps_url)
* [`MAX_PAGE_SIZE`](./miscellaneous.md#max_page_size)
* [`NAPALM_ARGS`](./napalm.md#napalm_args)
* [`NAPALM_PASSWORD`](./napalm.md#napalm_password)
* [`NAPALM_TIMEOUT`](./napalm.md#napalm_timeout)
* [`NAPALM_USERNAME`](./napalm.md#napalm_username)
* [`PAGINATE_COUNT`](./default-values.md#paginate_count)
* [`POWERFEED_DEFAULT_AMPERAGE`](./default-values.md#powerfeed_default_amperage)
* [`POWERFEED_DEFAULT_MAX_UTILIZATION`](./default-values.md#powerfeed_default_max_utilization)

View File

@@ -45,6 +45,16 @@ Sets content for the top banner in the user interface.
---
## CENSUS_REPORTING_ENABLED
Default: True
Enables anonymous census reporting. To opt out of census reporting, set this to False.
This data enables the project maintainers to estimate how many NetBox deployments exist and track the adoption of new versions over time. Census reporting effects a single HTTP request each time a worker starts. The only data reported by this function are the NetBox version, Python version, and a pseudorandom unique identifier.
---
## CHANGELOG_RETENTION
!!! tip "Dynamic Configuration Parameter"

View File

@@ -1,53 +0,0 @@
# NAPALM Parameters
!!! **Note:** As of NetBox v3.5, NAPALM integration has been moved to a plugin and these configuration parameters are now deprecated.
## NAPALM_USERNAME
## NAPALM_PASSWORD
!!! tip "Dynamic Configuration Parameter"
NetBox will use these credentials when authenticating to remote devices via the supported [NAPALM integration](../integrations/napalm.md), if installed. Both parameters are optional.
!!! note
If SSH public key authentication has been set up on the remote device(s) for the system account under which NetBox runs, these parameters are not needed.
---
## NAPALM_ARGS
!!! tip "Dynamic Configuration Parameter"
A dictionary of optional arguments to pass to NAPALM when instantiating a network driver. See the NAPALM documentation for a [complete list of optional arguments](https://napalm.readthedocs.io/en/latest/support/#optional-arguments). An example:
```python
NAPALM_ARGS = {
'api_key': '472071a93b60a1bd1fafb401d9f8ef41',
'port': 2222,
}
```
Some platforms (e.g. Cisco IOS) require an argument named `secret` to be passed in addition to the normal password. If desired, you can use the configured `NAPALM_PASSWORD` as the value for this argument:
```python
NAPALM_USERNAME = 'username'
NAPALM_PASSWORD = 'MySecretPassword'
NAPALM_ARGS = {
'secret': NAPALM_PASSWORD,
# Include any additional args here
}
```
---
## NAPALM_TIMEOUT
!!! tip "Dynamic Configuration Parameter"
Default: 30 seconds
The amount of time (in seconds) to wait for NAPALM to connect to a device.
---

View File

@@ -79,6 +79,30 @@ When remote user authentication is in use, this is the name of the HTTP header w
---
## REMOTE_AUTH_USER_EMAIL
Default: `'HTTP_REMOTE_USER_EMAIL'`
When remote user authentication is in use, this is the name of the HTTP header which informs NetBox of the email address of the currently authenticated user. For example, to use the request header `X-Remote-User-Email` it needs to be set to `HTTP_X_REMOTE_USER_EMAIL`. (Requires `REMOTE_AUTH_ENABLED`.)
---
## REMOTE_AUTH_USER_FIRST_NAME
Default: `'HTTP_REMOTE_USER_FIRST_NAME'`
When remote user authentication is in use, this is the name of the HTTP header which informs NetBox of the first name of the currently authenticated user. For example, to use the request header `X-Remote-User-First-Name` it needs to be set to `HTTP_X_REMOTE_USER_FIRST_NAME`. (Requires `REMOTE_AUTH_ENABLED`.)
---
## REMOTE_AUTH_USER_LAST_NAME
Default: `'HTTP_REMOTE_USER_LAST_NAME'`
When remote user authentication is in use, this is the name of the HTTP header which informs NetBox of the last name of the currently authenticated user. For example, to use the request header `X-Remote-User-Last-Name` it needs to be set to `HTTP_X_REMOTE_USER_LAST_NAME`. (Requires `REMOTE_AUTH_ENABLED`.)
---
## REMOTE_AUTH_SUPERUSER_GROUPS
Default: `[]` (Empty list)

View File

@@ -33,11 +33,13 @@ NetBox requires access to a PostgreSQL 11 or later database service to store dat
* `HOST` - Name or IP address of the database server (use `localhost` if running locally)
* `PORT` - TCP port of the PostgreSQL service; leave blank for default port (TCP/5432)
* `CONN_MAX_AGE` - Lifetime of a [persistent database connection](https://docs.djangoproject.com/en/stable/ref/databases/#persistent-connections), in seconds (300 is the default)
* `ENGINE` - The database backend to use; must be a PostgreSQL-compatible backend (e.g. `django.db.backends.postgresql`)
Example:
```python
DATABASE = {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'netbox', # Database name
'USER': 'netbox', # PostgreSQL username
'PASSWORD': 'J5brHrAXFLQSif0K', # PostgreSQL password
@@ -50,6 +52,9 @@ DATABASE = {
!!! note
NetBox supports all PostgreSQL database options supported by the underlying Django framework. For a complete list of available parameters, please see [the Django documentation](https://docs.djangoproject.com/en/stable/ref/settings/#databases).
!!! warning
Make sure to use a PostgreSQL-compatible backend for the ENGINE setting. If you don't specify an ENGINE, the default will be django.db.backends.postgresql.
---
## REDIS
@@ -144,8 +149,6 @@ REDIS = {
## SECRET_KEY
This is a secret, random string used to assist in the creation new cryptographic hashes for passwords and HTTP cookies. The key defined here should not be shared outside of the configuration file. `SECRET_KEY` can be changed at any time, however be aware that doing so will invalidate all existing sessions.
This is a secret, pseudorandom string used to assist in the creation new cryptographic hashes for passwords and HTTP cookies. The key defined here should not be shared outside the configuration file. `SECRET_KEY` can be changed at any time without impacting stored data, however be aware that doing so will invalidate all existing user sessions. NetBox deployments comprising multiple nodes must have the same secret key configured on all nodes.
Please note that this key is **not** used directly for hashing user passwords or for the encrypted storage of secret data in NetBox.
`SECRET_KEY` should be at least 50 characters in length and contain a random mix of letters, digits, and symbols. The script located at `$INSTALL_ROOT/netbox/generate_secret_key.py` may be used to generate a suitable key.
`SECRET_KEY` **must** be at least 50 characters in length, and should contain a mix of letters, digits, and symbols. The script located at `$INSTALL_ROOT/netbox/generate_secret_key.py` may be used to generate a suitable key. Please note that this key is **not** used directly for hashing user passwords or for the encrypted storage of secret data in NetBox.

View File

@@ -67,6 +67,12 @@ The name of the cookie to use for the cross-site request forgery (CSRF) authenti
---
## CSRF_COOKIE_SECURE
Default: False
If true, the cookie employed for cross-site request forgery (CSRF) protection will be marked as secure, meaning that it can only be sent across an HTTPS connection.
---
## CSRF_TRUSTED_ORIGINS
@@ -145,6 +151,17 @@ The view name or URL to which a user is redirected after logging out.
---
## SECURE_SSL_REDIRECT
Default: False
If true, all non-HTTPS requests will be automatically redirected to use HTTPS.
!!! warning
Ensure that your frontend HTTP daemon has been configured to forward the HTTP scheme correctly before enabling this option. An incorrectly configured frontend may result in a looping redirect.
---
## SESSION_COOKIE_NAME
Default: `sessionid`
@@ -153,6 +170,14 @@ The name used for the session cookie. See the [Django documentation](https://doc
---
## SESSION_COOKIE_SECURE
Default: False
If true, the cookie employed for session authentication will be marked as secure, meaning that it can only be sent across an HTTPS connection.
---
## SESSION_FILE_PATH
Default: None

View File

@@ -2,12 +2,12 @@
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 `obj`, and custom fields through `obj.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 [Jinja2 template code](https://jinja2docs.readthedocs.io/en/stable/) through the variable `object`, and custom fields through `object.cf`.
For example, you might define a link like this:
* Text: `View NMS`
* URL: `https://nms.example.com/nodes/?name={{ obj.name }}`
* URL: `https://nms.example.com/nodes/?name={{ object.name }}`
When viewing a device named Router4, this link would render as:
@@ -27,7 +27,6 @@ The following context data is available within the template when rendering a cus
| Variable | Description |
|-----------|-------------------------------------------------------------------------------------------------------------------|
| `object` | The NetBox object being displayed |
| `obj` | Same as `object`; maintained for backward compatability until NetBox v3.5 |
| `debug` | A boolean indicating whether debugging is enabled |
| `request` | The current WSGI request |
| `user` | The current user (if authenticated) |
@@ -44,7 +43,7 @@ Only links which render with non-empty text are included on the page. You can em
For example, if you only want to display a link for active devices, you could set the link text to
```jinja2
{% if obj.status == 'active' %}View NMS{% endif %}
{% if object.status == 'active' %}View NMS{% endif %}
```
The link will not appear when viewing a device with any status other than "active."
@@ -52,7 +51,7 @@ The link will not appear when viewing a device with any status other than "activ
As another example, if you wanted to show only devices belonging to a certain manufacturer, you could do something like this:
```jinja2
{% if obj.device_type.manufacturer.name == 'Cisco' %}View NMS{% endif %}
{% if object.device_type.manufacturer.name == 'Cisco' %}View NMS{% endif %}
```
The link will only appear when viewing a device with a manufacturer name of "Cisco."

View File

@@ -35,12 +35,9 @@ class MyScript(Script):
The `run()` method should accept two arguments:
* `data` - A dictionary containing all of the variable data passed via the web form.
* `data` - A dictionary containing all the variable data passed via the web form.
* `commit` - A boolean indicating whether database changes will be committed.
!!! note
The `commit` argument was introduced in NetBox v2.7.8. Backward compatibility is maintained for scripts which accept only the `data` argument, however beginning with v2.10 NetBox will require the `run()` method of every script to accept both arguments. (Either argument may still be ignored within the method.)
Defining script variables is optional: You may create a script with only a `run()` method if no user input is needed.
Any output generated by the script during its execution will be displayed under the "output" tab in the UI.
@@ -104,6 +101,10 @@ The checkbox to commit database changes when executing a script is checked by de
commit_default = False
```
### `scheduling_enabled`
By default, a script can be scheduled for execution at a later time. Setting `scheduling_enabled` to False disables this ability: Only immediate execution will be possible. (This also disables the ability to set a recurring execution interval.)
### `job_timeout`
Set the maximum allowed runtime for the script. If not set, `RQ_DEFAULT_TIMEOUT` will be used.

View File

@@ -91,6 +91,10 @@ As you can see, reports are completely customizable. Validation logic can be as
A human-friendly description of what your report does.
### `scheduling_enabled`
By default, a report can be scheduled for execution at a later time. Setting `scheduling_enabled` to False disables this ability: Only immediate execution will be possible. (This also disables the ability to set a recurring execution interval.)
### `job_timeout`
Set the maximum allowed runtime for the report. If not set, `RQ_DEFAULT_TIMEOUT` will be used.
@@ -130,7 +134,7 @@ Once you have created a report, it will appear in the reports list. Initially, r
!!! note
To run a report, a user must be assigned the `extras.run_report` permission. This is achieved by assigning the user (or group) a permission on the Report object and specifying the `run` action in the admin UI as shown below.
![Adding the run action to a permission](/media/admin_ui_run_permission.png)
![Adding the run action to a permission](../media/admin_ui_run_permission.png)
### Via the Web UI

View File

@@ -32,7 +32,7 @@ These are considered the "core" application models which are used to model netwo
* [circuits.Circuit](../models/circuits/circuit.md)
* [circuits.Provider](../models/circuits/provider.md)
* [circuits.ProviderAccount](../models/circuits/provideracount.md)
* [circuits.ProviderAccount](../models/circuits/provideraccount.md)
* [circuits.ProviderNetwork](../models/circuits/providernetwork.md)
* [core.DataSource](../models/core/datasource.md)
* [dcim.Cable](../models/dcim/cable.md)

View File

@@ -30,14 +30,6 @@ A webhook is a mechanism for conveying to some external system a change that too
To learn more about this feature, check out the [webhooks documentation](../integrations/webhooks.md).
## NAPALM
[NAPALM](https://github.com/napalm-automation/napalm) is a Python library which enables direct interaction with network devices of various platforms. When configured, NetBox supports fetching live operational and status data directly from network devices to be compared to what has been defined in NetBox. This allows for easily validating the device's operational state against its desired state. Additionally, NetBox's REST API can act as a sort of proxy for NAPALM commands, allowing external clients to interact with network devices by sending HTTP requests to the appropriate API endpoint.
To learn more about this feature, check out the [NAPALM documentation](../integrations/napalm.md).
As of NetBox v3.5, NAPALM integration has been moved to a plugin. Please see the [netbox_napalm_plugin](https://github.com/netbox-community/netbox-napalm) for installation instructions.
## Prometheus Metrics
NetBox includes a special `/metrics` view which exposes metrics for a [Prometheus](https://prometheus.io/) scraper, powered by the open source [django-prometheus](https://github.com/korfuri/django-prometheus) library. To learn more about this feature, check out the [Prometheus metrics documentation](../integrations/prometheus-metrics.md).

View File

@@ -1,5 +1,7 @@
# Configuration Rendering
!!! info "This feature was introduced in NetBox v3.5."
One of the critical aspects of operating a network is ensuring that every network node is configured correctly. By leveraging configuration templates and [context data](./context-data.md), NetBox can render complete configuration files for each device on your network.
```mermaid

View File

@@ -20,4 +20,4 @@ The following NetBox models can be associated with replicated data files:
* Config templates
* Export templates
Once a data has been designated for a local instance, its data will be replaced with the content of the replicated file. When the replicated file is updated in the future (via synchronization jobs), the local instance will be flagged as having out-of-date data. A user can then synchronize these objects individually or in bulk to effect the update. This two-stgae process ensures that automated synchronization tasks do not immediately affect production data.
Once a data has been designated for a local instance, its data will be replaced with the content of the replicated file. When the replicated file is updated in the future (via synchronization jobs), the local instance will be flagged as having out-of-date data. A user can then synchronize these objects individually or in bulk to effect the update. This two-stage process ensures that automated synchronization tasks do not immediately affect production data.

View File

@@ -54,7 +54,7 @@ Within the shell, enter the following commands to create the database and user (
```postgresql
CREATE DATABASE netbox;
CREATE USER netbox WITH PASSWORD 'J5brHrAXFLQSif0K';
GRANT ALL PRIVILEGES ON DATABASE netbox TO netbox;
ALTER DATABASE netbox OWNER TO netbox;
```
!!! danger "Use a strong password"

View File

@@ -4,9 +4,6 @@
[Redis](https://redis.io/) is an in-memory key-value store which NetBox employs for caching and queuing. This section entails the installation and configuration of a local Redis instance. If you already have a Redis service in place, skip to [the next section](3-netbox.md).
!!! warning "Redis v4.0 or later required"
NetBox v2.9.0 and later require Redis v4.0 or higher. If your distribution does not offer a recent enough release, you will need to build Redis from source. Please see [the Redis installation documentation](https://github.com/redis/redis) for further details.
=== "Ubuntu"
```no-highlight

View File

@@ -97,7 +97,7 @@ sudo git pull origin master
## 4. Run the Upgrade Script
Once the new code is in place, verify that any optional Python packages required by your deployment (e.g. `napalm` or `django-auth-ldap`) are listed in `local_requirements.txt`. Then, run the upgrade script:
Once the new code is in place, verify that any optional Python packages required by your deployment (e.g. `django-auth-ldap`) are listed in `local_requirements.txt`. Then, run the upgrade script:
```no-highlight
sudo ./upgrade.sh

View File

@@ -1,3 +0,0 @@
# NAPALM
As of NetBox v3.5, NAPALM integration has been moved to a plugin. Please see the [netbox_napalm_plugin](https://github.com/netbox-community/netbox-napalm) for installation instructions. **Note:** All previously entered NAPALM configuration data will be saved and automatically imported by the new plugin.

View File

@@ -586,6 +586,15 @@ Additionally, a token can be set to expire at a specific time. This can be usefu
Each API token can optionally be restricted by client IP address. If one or more allowed IP prefixes/addresses is defined for a token, authentication will fail for any client connecting from an IP address outside the defined range(s). This enables restricting the use a token to a specific client. (By default, any client IP address is permitted.)
#### Creating Tokens for Other Users
It is possible to provision authentication tokens for other users via the REST API. To do, so the requesting user must have the `users.grant_token` permission assigned. While all users have inherent permission to create their own tokens, this permission is required to enable the creation of tokens for other users.
![Adding the grant action to a permission](../media/admin_ui_grant_permission.png)
!!! warning "Exercise Caution"
The ability to create tokens on behalf of other users enables the requestor to access the created token. This ability is intended e.g. for the provisioning of tokens by automated services, and should be used with extreme caution to avoid a security compromise.
### Authenticating to the API
An authentication token is attached to a request by setting the `Authorization` header to the string `Token` followed by a space and the user's token:
@@ -629,7 +638,7 @@ $ curl -X POST \
https://netbox/api/users/tokens/provision/ \
--data '{
"username": "hankhill",
"password": "I<3C3H8",
"password": "I<3C3H8"
}'
```

View File

@@ -37,7 +37,6 @@ NetBox was built specifically to serve the needs of network engineers and operat
* Robust object-based permissions
* Detailed, automatic change logging
* Global search engine
* NAPALM integration
## What NetBox Is Not
@@ -78,4 +77,3 @@ NetBox is built on the [Django](https://djangoproject.com/) Python framework and
| Application | Django/Python |
| Database | PostgreSQL 11+ |
| Task queuing | Redis/django-rq |
| Live device access | NAPALM (optional) |

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 174 KiB

After

Width:  |  Height:  |  Size: 173 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 173 KiB

After

Width:  |  Height:  |  Size: 171 KiB

View File

@@ -1,17 +1,19 @@
# Provider Accounts
This model can be used to represent individual accounts associated with a provider.
## Fields
### Provider
The [provider](./provider.md) the account belongs to.
### Name
A human-friendly name, unique to the provider.
### Account Number
The administrative account identifier tied to this provider for your organization.
# Provider Accounts
!!! info "This model was introduced in NetBox v3.5."
This model can be used to represent individual accounts associated with a provider.
## Fields
### Provider
The [provider](./provider.md) the account belongs to.
### Name
A human-friendly name, unique to the provider.
### Account Number
The administrative account identifier tied to this provider for your organization.

View File

@@ -4,8 +4,6 @@ A platform defines the type of software running on a [device](./device.md) or [v
Platforms may optionally be limited by [manufacturer](./manufacturer.md): If a platform is assigned to a particular manufacturer, it can only be assigned to devices with a type belonging to that manufacturer.
The platform model is also used to indicate which [NAPALM driver](../../integrations/napalm.md) (if any) and any associated arguments NetBox should use when connecting to a remote device. The name of the driver along with optional parameters are stored with the platform.
The assignment of platforms to devices is an optional feature, and may be disregarded if not desired.
## Fields
@@ -28,8 +26,14 @@ The default [configuration template](../extras/configtemplate.md) for devices as
### NAPALM Driver
!!! warning "Deprecated Field"
NAPALM integration was removed from NetBox core in v3.5 and is now available as a [plugin](https://github.com/netbox-community/netbox-napalm). This field will be removed in NetBox v3.6.
The [NAPALM driver](https://napalm.readthedocs.io/en/latest/support/index.html) associated with this platform.
### NAPALM Arguments
!!! warning "Deprecated Field"
NAPALM integration was removed from NetBox core in v3.5 and is now available as a [plugin](https://github.com/netbox-community/netbox-napalm). This field will be removed in NetBox v3.6.
Any additional arguments to send when invoking the NAPALM driver assigned to this platform.

View File

@@ -1,5 +1,7 @@
# ASN Ranges
!!! info "This model was introduced in NetBox v3.5."
Ranges can be defined to group [AS numbers](./asn.md) numerically and to facilitate their automatic provisioning. Each range must be assigned to a [RIR](./rir.md).
## Fields

View File

@@ -0,0 +1,51 @@
# Dashboard Widgets
!!! info "This feature was introduced in NetBox v3.5."
Each NetBox user can customize his or her personal dashboard by adding and removing widgets and by manipulating the size and position of each. Plugins can register their own dashboard widgets to complement those already available natively.
## The DashboardWidget Class
All dashboard widgets must inherit from NetBox's `DashboardWidget` base class. Subclasses must provide a `render()` method, and may override the base class' default characteristics.
Widgets which require configuration by a user must also include a `ConfigForm` child class which inherits from `WidgetConfigForm`. This form is used to render the user configuration options for the widget.
::: extras.dashboard.widgets.DashboardWidget
## Widget Registration
To register a dashboard widget for use in NetBox, import the `register_widget()` decorator and use it to wrap each `DashboardWidget` subclass:
```python
from extras.dashboard.widgets import DashboardWidget, register_widget
@register_widget
class MyWidget1(DashboardWidget):
...
@register_widget
class MyWidget2(DashboardWidget):
...
```
## Example
```python
from django import forms
from extras.dashboard.utils import register_widget
from extras.dashboard.widgets import DashboardWidget, WidgetConfigForm
@register_widget
class ReminderWidget(DashboardWidget):
default_title = 'Reminder'
description = 'Add a virtual sticky note'
class ConfigForm(WidgetConfigForm):
content = forms.CharField(
widget=forms.Textarea()
)
def render(self, request):
return self.config.get('content')
```

View File

@@ -145,23 +145,23 @@ class MyModelFilterForm(NetBoxModelFilterSetForm):
In addition to the [form fields provided by Django](https://docs.djangoproject.com/en/stable/ref/forms/fields/), NetBox provides several field classes for use within forms to handle specific types of data. These can be imported from `utilities.forms.fields` and are documented below.
::: utilities.forms.ColorField
::: utilities.forms.fields.ColorField
options:
members: false
::: utilities.forms.CommentField
::: utilities.forms.fields.CommentField
options:
members: false
::: utilities.forms.JSONField
::: utilities.forms.fields.JSONField
options:
members: false
::: utilities.forms.MACAddressField
::: utilities.forms.fields.MACAddressField
options:
members: false
::: utilities.forms.SlugField
::: utilities.forms.fields.SlugField
options:
members: false
@@ -170,52 +170,52 @@ In addition to the [form fields provided by Django](https://docs.djangoproject.c
!!! warning "Obsolete Fields"
NetBox's custom `ChoiceField` and `MultipleChoiceField` classes are no longer necessary thanks to improvements made to the user interface. Django's native form fields can be used instead. These custom field classes will be removed in NetBox v3.6.
::: utilities.forms.ChoiceField
::: utilities.forms.fields.ChoiceField
options:
members: false
::: utilities.forms.MultipleChoiceField
::: utilities.forms.fields.MultipleChoiceField
options:
members: false
## Dynamic Object Fields
::: utilities.forms.DynamicModelChoiceField
::: utilities.forms.fields.DynamicModelChoiceField
options:
members: false
::: utilities.forms.DynamicModelMultipleChoiceField
::: utilities.forms.fields.DynamicModelMultipleChoiceField
options:
members: false
## Content Type Fields
::: utilities.forms.ContentTypeChoiceField
::: utilities.forms.fields.ContentTypeChoiceField
options:
members: false
::: utilities.forms.ContentTypeMultipleChoiceField
::: utilities.forms.fields.ContentTypeMultipleChoiceField
options:
members: false
## CSV Import Fields
::: utilities.forms.CSVChoiceField
::: utilities.forms.fields.CSVChoiceField
options:
members: false
::: utilities.forms.CSVMultipleChoiceField
::: utilities.forms.fields.CSVMultipleChoiceField
options:
members: false
::: utilities.forms.CSVModelChoiceField
::: utilities.forms.fields.CSVModelChoiceField
options:
members: false
::: utilities.forms.CSVContentTypeField
::: utilities.forms.fields.CSVContentTypeField
options:
members: false
::: utilities.forms.CSVMultipleContentTypeField
::: utilities.forms.fields.CSVMultipleContentTypeField
options:
members: false

View File

@@ -2,8 +2,6 @@
Plugins are packaged [Django](https://docs.djangoproject.com/) apps that can be installed alongside NetBox to provide custom functionality not present in the core application. Plugins can introduce their own models and views, but cannot interfere with existing components. A NetBox user may opt to install plugins provided by the community or build his or her own.
Plugins are supported on NetBox v2.8 and later.
## Capabilities
The NetBox plugin architecture allows for the following:

View File

@@ -10,6 +10,16 @@ Minor releases are published in April, August, and December of each calendar yea
This page contains a history of all major and minor releases since NetBox v2.0. For more detail on a specific patch release, please see the release notes page for that specific minor release.
#### [Version 3.5](./version-3.5.md) (April 2023)
* Customizable Dashboard ([#9416](https://github.com/netbox-community/netbox/issues/9416))
* Remote Data Sources ([#11558](https://github.com/netbox-community/netbox/issues/11558))
* Configuration Template Rendering ([#11559](https://github.com/netbox-community/netbox/issues/11559))
* NAPALM Integration Plugin ([#10520](https://github.com/netbox-community/netbox/issues/10520))
* ASN Ranges ([#8550](https://github.com/netbox-community/netbox/issues/8550))
* Provider Accounts ([#9047](https://github.com/netbox-community/netbox/issues/9047))
* Job-Triggered Webhooks ([#8958](https://github.com/netbox-community/netbox/issues/8958))
#### [Version 3.4](./version-3.4.md) (December 2022)
* New Global Search ([#10560](https://github.com/netbox-community/netbox/issues/10560))

View File

@@ -1,6 +1,66 @@
# NetBox v3.4
## v3.4.8 (FUTURE)
## v3.4.10 (2023-04-27)
### Bug Fixes
* [#11607](https://github.com/netbox-community/netbox/issues/11607) - Fix custom object field assignments made via REST API for for cables
* [#12252](https://github.com/netbox-community/netbox/issues/12252) - Fix ordering of search results when sorting by object name
* [#12355](https://github.com/netbox-community/netbox/issues/12355) - Fix escaping of certain characters in URL when rendering custom links
---
## v3.4.9 (2023-04-26)
### Enhancements
* [#10987](https://github.com/netbox-community/netbox/issues/10987) - Show peer racks as a dropdown list under rack view
* [#11386](https://github.com/netbox-community/netbox/issues/11386) - Introduce `CSRF_COOKIE_SECURE`, `SECURE_SSL_REDIRECT`, and `SESSION_COOKIE_SECURE` configuration parameters
* [#11623](https://github.com/netbox-community/netbox/issues/11623) - Hide PSK strings under wireless LAN & link views
* [#12205](https://github.com/netbox-community/netbox/issues/12205) - Sanitize rendered custom links to mitigate malicious links
* [#12226](https://github.com/netbox-community/netbox/issues/12226) - Enable setting user name & email values via remote authenticate headers
* [#12337](https://github.com/netbox-community/netbox/issues/12337) - Enable anonymized reporting of census data
### Bug Fixes
* [#11383](https://github.com/netbox-community/netbox/issues/11383) - Fix ordering of global search results by object type
* [#11902](https://github.com/netbox-community/netbox/issues/11902) - Fix import of inventory items for devices with duplicated names
* [#12238](https://github.com/netbox-community/netbox/issues/12238) - Improve error message for API token IP prefix validation failures
* [#12255](https://github.com/netbox-community/netbox/issues/12255) - Restore the ability to move inventory items among devices
* [#12270](https://github.com/netbox-community/netbox/issues/12270) - Fix pre-population of list values when creating a saved filter
* [#12296](https://github.com/netbox-community/netbox/issues/12296) - Fix "mark connected" form field for bulk editing front & rear ports
---
## v3.4.8 (2023-04-12)
### Enhancements
* [#10414](https://github.com/netbox-community/netbox/issues/10414) - Enable general purpose image attachments for device types
* [#10600](https://github.com/netbox-community/netbox/issues/10600) - Allow custom object fields to reference a user or group
* [#11015](https://github.com/netbox-community/netbox/issues/11015) - Remove unit from commit rate column header in circuits table
* [#11431](https://github.com/netbox-community/netbox/issues/11431) - Disallow changing custom field type after creation
* [#11453](https://github.com/netbox-community/netbox/issues/11453) - Display a warning banner when `DEBUG` is enabled
* [#12007](https://github.com/netbox-community/netbox/issues/12007) - Enable filtering of VM Interfaces by assigned VLAN
* [#12095](https://github.com/netbox-community/netbox/issues/12095) - Specify UTF-8 encoding for default export template MIME type
* [#12207](https://github.com/netbox-community/netbox/issues/12207) - Introduce the `grant_token` permission for controlling the creation of API tokens on behalf of other users
### Bug Fixes
* [#10221](https://github.com/netbox-community/netbox/issues/10221) - Validate generic foreign key relations assigned via REST API requests
* [#11432](https://github.com/netbox-community/netbox/issues/11432) - Prevent existing components & component templates from being reassigned to different devices/device types via the REST API
* [#11454](https://github.com/netbox-community/netbox/issues/11454) - Raise validation error if generic foreign key assignment does not specify both object type and ID
* [#11746](https://github.com/netbox-community/netbox/issues/11746) - Fix cleanup of object data when deleting a custom field
* [#12011](https://github.com/netbox-community/netbox/issues/12011) - Fix KeyError exception when attempting to add module bays in bulk
* [#12040](https://github.com/netbox-community/netbox/issues/12040) - Display relevant UI tab upon bulk import validation failure
* [#12074](https://github.com/netbox-community/netbox/issues/12074) - Fix the automatic assignment of racks to devices via the REST API
* [#12084](https://github.com/netbox-community/netbox/issues/12084) - Fix exception when attempting to create a saved filter for applied filters
* [#12087](https://github.com/netbox-community/netbox/issues/12087) - Fix bulk editing of many-to-many relationships
* [#12117](https://github.com/netbox-community/netbox/issues/12117) - Hide clone button for objects with no clonable attributes
* [#12118](https://github.com/netbox-community/netbox/issues/12118) - Fix instantiation of nested inventory item templates when creating a device
* [#12184](https://github.com/netbox-community/netbox/issues/12184) - Fix filtered bulk deletion for various models
* [#12190](https://github.com/netbox-community/netbox/issues/12190) - Fix form layout for plugin textarea fields
* [#12227](https://github.com/netbox-community/netbox/issues/12227) - Fix tenant assignment on bulk import of L2VPNs
---

View File

@@ -1,12 +1,57 @@
# NetBox v3.5
## v3.5-beta1 (2023-03-30)
## v3.5.1 (2023-05-05)
### Enhancements
* [#10759](https://github.com/netbox-community/netbox/issues/10759) - Support Markdown rendering for custom field descriptions
* [#11190](https://github.com/netbox-community/netbox/issues/11190) - Including systemd service & timer configurations for housekeeping tasks
* [#11422](https://github.com/netbox-community/netbox/issues/11422) - Match on power panel name when searching for power feeds
* [#11504](https://github.com/netbox-community/netbox/issues/11504) - Add filter to select individual racks under rack elevations view
* [#11652](https://github.com/netbox-community/netbox/issues/11652) - Add a module status column to module bay tables
* [#11791](https://github.com/netbox-community/netbox/issues/11791) - Enable configuration of custom database backend via `ENGINE` parameter
* [#11801](https://github.com/netbox-community/netbox/issues/11801) - Include device description within rack elevation tooltip
* [#11932](https://github.com/netbox-community/netbox/issues/11932) - Introduce a list view for image attachments, orderable by date and other attributes
* [#12122](https://github.com/netbox-community/netbox/issues/12122) - Enable bulk import oj journal entries
* [#12245](https://github.com/netbox-community/netbox/issues/12245) - Enable the assignment of wireless LANs to interfaces under bulk edit
### Bug Fixes
* [#10757](https://github.com/netbox-community/netbox/issues/10757) - Simplify IP address interface and NAT IP assignment form fields to avoid confusion
* [#11715](https://github.com/netbox-community/netbox/issues/11715) - Prefix within a VRF should list global prefixes as parents only if they are containers
* [#12363](https://github.com/netbox-community/netbox/issues/12363) - Fix whitespace for paragraph elements in Markdown-rendered table columns
* [#12367](https://github.com/netbox-community/netbox/issues/12367) - Fix `RelatedObjectDoesNotExist` exception under certain conditions (regression from #11550)
* [#12380](https://github.com/netbox-community/netbox/issues/12380) - Allow selecting object change as model under object list widget configuration
* [#12384](https://github.com/netbox-community/netbox/issues/12384) - Add a three-second timeout for RSS reader widget
* [#12395](https://github.com/netbox-community/netbox/issues/12395) - Fix "create & add another" action for objects with custom fields
* [#12396](https://github.com/netbox-community/netbox/issues/12396) - Provider account should not be a required field in REST API serializer
* [#12400](https://github.com/netbox-community/netbox/issues/12400) - Validate default values for object and multi-object custom fields
* [#12401](https://github.com/netbox-community/netbox/issues/12401) - Support the creation of front ports without a pre-populated device ID
* [#12405](https://github.com/netbox-community/netbox/issues/12405) - Fix filtering for VLAN groups displayed under site view
* [#12410](https://github.com/netbox-community/netbox/issues/12410) - Fix base path for OpenAPI schema (fixes Swagger UI requests)
* [#12416](https://github.com/netbox-community/netbox/issues/12416) - Fix `FileNotFoundError` exception when a managed script file is missing from disk
* [#12412](https://github.com/netbox-community/netbox/issues/12412) - Device/VM interface MAC addresses can be nullified via REST API
* [#12415](https://github.com/netbox-community/netbox/issues/12415) - Fix `ImportError` exception when running RQ worker
* [#12433](https://github.com/netbox-community/netbox/issues/12433) - Correct the application of URL query parameters for object list dashboard widgets
* [#12436](https://github.com/netbox-community/netbox/issues/12436) - Remove extraneous "add" button from contact assignments list
* [#12463](https://github.com/netbox-community/netbox/issues/12463) - Fix the association of completed jobs with reports & scripts in the REST API
* [#12464](https://github.com/netbox-community/netbox/issues/12464) - Apply credentials for git data source only when connecting via HTTP/S
* [#12476](https://github.com/netbox-community/netbox/issues/12476) - Fix `TypeError` exception when running the `runscript` management command
* [#12483](https://github.com/netbox-community/netbox/issues/12483) - Fix git remote data syncing when with HTTP proxies defined
* [#12496](https://github.com/netbox-community/netbox/issues/12496) - Remove obsolete account field from provider UI view
---
## v3.5.0 (2023-04-27)
### Breaking Changes
* The `account` field has been removed from the provider model. This information is now tracked using the new provider account model. Multiple accounts can be assigned per provider.
* A minimum length of 50 characters is now enforced for the `SECRET_KEY` configuration parameter.
* The JobResult model has been moved from the `extras` app to `core` and renamed to Job. Accordingly, its REST API endpoint has been moved from `/api/extras/job-results/` to `/api/core/jobs/`.
* The `obj_type` field on the Job model (previously JobResult) has been renamed to `object_type` for consistency with other models.
* The `JOBRESULT_RETENTION` configuration parameter has been renamed to `JOB_RETENTION`.
* The `obj` context variable is no longer passed when rendering custom links: Use `object` instead.
* The REST API schema is now generated using the OpenAPI 3.0 spec
* The URLs for the REST API schema documentation have changed:
* `/api/docs/` is now `/api/schema/swagger-ui/`
@@ -26,7 +71,7 @@ NetBox now has the ability to synchronize arbitrary data from external sources t
This release introduces the ability to render device configurations from Jinja2 templates natively within NetBox, via both the UI and REST API. The new [ConfigTemplate](../models/extras/configtemplate.md) model stores template code (which may be defined locally or sourced from remote data files). The rendering engine passes data gleaned from both config contexts and request parameters to generate complete configurations suitable for direct application to network devices.
#### NAPALM Plugin ([#10520](https://github.com/netbox-community/netbox/issues/10520))
#### NAPALM Integration Plugin ([#10520](https://github.com/netbox-community/netbox/issues/10520))
The NAPALM integration feature found in previous NetBox releases has been moved from the core application to a [dedicated plugin](https://github.com/netbox-community/netbox-napalm). This allows greater control over the feature's configuration and will unlock additional potential as a separate project.
@@ -54,7 +99,9 @@ Two new webhook trigger events have been introduced: `job_start` and `job_end`.
* [#10242](https://github.com/netbox-community/netbox/issues/10242) - Redirect to filtered objects list after bulk import
* [#10374](https://github.com/netbox-community/netbox/issues/10374) - Require unique tenant names & slugs per group
* [#10729](https://github.com/netbox-community/netbox/issues/10729) - Add date & time custom field type
* [#11029](https://github.com/netbox-community/netbox/issues/11029) - Enable change logging for cable terminations
* [#11254](https://github.com/netbox-community/netbox/issues/11254) - Introduce the `X-Request-ID` HTTP header to annotate the unique ID of each request for change logging
* [#11255](https://github.com/netbox-community/netbox/issues/11255) - Introduce the `scheduling_enabled` settings for reports & scripts
* [#11291](https://github.com/netbox-community/netbox/issues/11291) - Optimized GraphQL API request handling
* [#11440](https://github.com/netbox-community/netbox/issues/11440) - Add an `enabled` field for device type interfaces
* [#11494](https://github.com/netbox-community/netbox/issues/11494) - Enable filtering objects by create/update request IDs
@@ -67,12 +114,24 @@ Two new webhook trigger events have been introduced: `job_start` and `job_end`.
* [#11968](https://github.com/netbox-community/netbox/issues/11968) - Add navigation menu buttons to create device & VM components
* [#12068](https://github.com/netbox-community/netbox/issues/12068) - Enable generic foreign key relationships from jobs to NetBox objects
* [#12085](https://github.com/netbox-community/netbox/issues/12085) - Add a file source view for reports
* [#12218](https://github.com/netbox-community/netbox/issues/12218) - Provide more relevant API endpoint descriptions in schema
* [#12343](https://github.com/netbox-community/netbox/issues/12343) - Enforce a minimum length for `SECRET_KEY` configuration parameter
### Bug Fixes (From Beta2)
* [#12149](https://github.com/netbox-community/netbox/issues/12149) - Fix OpenAPI schema warnings relating to enum collisions
* [#12195](https://github.com/netbox-community/netbox/issues/12195) - Fix exception when setting IP address role to null via REST API
* [#12256](https://github.com/netbox-community/netbox/issues/12256) - Fix OpenAPI schema warnings relating to nested serializers
* [#12278](https://github.com/netbox-community/netbox/issues/12278) - Fix schema warnings related to IPAddressField
* [#12288](https://github.com/netbox-community/netbox/issues/12288) - Include `servers` definition in OpenAPI spec
* [#12299](https://github.com/netbox-community/netbox/issues/12299) - Fix object list widget support for filtering by multiple values
### Other Changes
* [#9608](https://github.com/netbox-community/netbox/issues/9608) - Upgrade REST API schema to OpenAPI 3.0
* [#10604](https://github.com/netbox-community/netbox/issues/10604) - Remove unused `extra_tabs` block from `object.html` generic template
* [#10923](https://github.com/netbox-community/netbox/issues/10923) - Remove unused `NetBoxModelCSVForm` class (replaced by `NetBoxModelImportForm`)
* [#11489](https://github.com/netbox-community/netbox/issues/11489) - Consoldated several middleware classes
* [#11489](https://github.com/netbox-community/netbox/issues/11489) - Consolidated several middleware classes
* [#11611](https://github.com/netbox-community/netbox/issues/11611) - Refactor API viewset classes and introduce NetBoxReadOnlyModelViewSet
* [#11694](https://github.com/netbox-community/netbox/issues/11694) - Remove obsolete `SmallTextarea` form widget
* [#11737](https://github.com/netbox-community/netbox/issues/11737) - `ChangeLoggedModel` now inherits `WebhooksMixin`
@@ -96,6 +155,8 @@ Two new webhook trigger events have been introduced: `job_start` and `job_end`.
* Added the optional `account` foreign key to ProviderAccount
* circuits.Provider
* Removed the `account` field
* dcim.CableTermination
* Added `default_platform` foreign key (optional)
* dcim.DeviceType
* Added `default_platform` foreign key (optional)
* dcim.InterfaceTemplate

View File

@@ -8,6 +8,9 @@ theme:
custom_dir: docs/_theme/
icon:
repo: fontawesome/brands/github
features:
- content.code.copy
- navigation.footer
palette:
- media: "(prefers-color-scheme: light)"
scheme: default
@@ -20,7 +23,8 @@ theme:
icon: material/lightbulb
name: Switch to Light Mode
plugins:
- search
- search:
lang: en
- mkdocstrings:
handlers:
python:
@@ -104,7 +108,6 @@ nav:
- Default Values: 'configuration/default-values.md'
- Error Reporting: 'configuration/error-reporting.md'
- Plugins: 'configuration/plugins.md'
- NAPALM: 'configuration/napalm.md'
- Date & Time: 'configuration/date-time.md'
- Miscellaneous: 'configuration/miscellaneous.md'
- Development: 'configuration/development.md'
@@ -120,7 +123,6 @@ nav:
- GraphQL API: 'integrations/graphql-api.md'
- Webhooks: 'integrations/webhooks.md'
- Synchronized Data: 'integrations/synchronized-data.md'
- NAPALM: 'integrations/napalm.md'
- Prometheus Metrics: 'integrations/prometheus-metrics.md'
- Plugins:
- Using Plugins: 'plugins/index.md'
@@ -137,6 +139,7 @@ nav:
- REST API: 'plugins/development/rest-api.md'
- GraphQL API: 'plugins/development/graphql-api.md'
- Background Tasks: 'plugins/development/background-tasks.md'
- Dashboard Widgets: 'plugins/development/dashboard-widgets.md'
- Staged Changes: 'plugins/development/staged-changes.md'
- Exceptions: 'plugins/development/exceptions.md'
- Administration:

View File

@@ -106,7 +106,7 @@ class CircuitCircuitTerminationSerializer(WritableNestedSerializer):
class CircuitSerializer(NetBoxModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name='circuits-api:circuit-detail')
provider = NestedProviderSerializer()
provider_account = NestedProviderAccountSerializer()
provider_account = NestedProviderAccountSerializer(required=False, allow_null=True)
status = ChoiceField(choices=CircuitStatusChoices, required=False)
type = NestedCircuitTypeSerializer()
tenant = NestedTenantSerializer(required=False, allow_null=True)

View File

@@ -25,6 +25,22 @@ class CircuitStatusChoices(ChoiceSet):
]
class CircuitCommitRateChoices(ChoiceSet):
key = 'Circuit.commit_rate'
CHOICES = [
(10000, '10 Mbps'),
(100000, '100 Mbps'),
(1000000, '1 Gbps'),
(10000000, '10 Gbps'),
(25000000, '25 Gbps'),
(40000000, '40 Gbps'),
(100000000, '100 Gbps'),
(1544, 'T1 (1.544 Mbps)'),
(2048, 'E1 (2.048 Mbps)'),
]
#
# CircuitTerminations
#
@@ -38,3 +54,19 @@ class CircuitTerminationSideChoices(ChoiceSet):
(SIDE_A, 'A'),
(SIDE_Z, 'Z')
)
class CircuitTerminationPortSpeedChoices(ChoiceSet):
key = 'CircuitTermination.port_speed'
CHOICES = [
(10000, '10 Mbps'),
(100000, '100 Mbps'),
(1000000, '1 Gbps'),
(10000000, '10 Gbps'),
(25000000, '25 Gbps'),
(40000000, '40 Gbps'),
(100000000, '100 Gbps'),
(1544, 'T1 (1.544 Mbps)'),
(2048, 'E1 (2.048 Mbps)'),
]

View File

@@ -1,14 +1,14 @@
from django import forms
from django.utils.translation import gettext as _
from circuits.choices import CircuitStatusChoices
from circuits.choices import CircuitCommitRateChoices, CircuitStatusChoices
from circuits.models import *
from ipam.models import ASN
from netbox.forms import NetBoxModelBulkEditForm
from tenancy.models import Tenant
from utilities.forms import (
add_blank_choice, CommentField, DatePicker, DynamicModelChoiceField, DynamicModelMultipleChoiceField,
)
from utilities.forms import add_blank_choice
from utilities.forms.fields import CommentField, DynamicModelChoiceField, DynamicModelMultipleChoiceField
from utilities.forms.widgets import DatePicker, NumberWithOptions
__all__ = (
'CircuitBulkEditForm',
@@ -139,7 +139,10 @@ class CircuitBulkEditForm(NetBoxModelBulkEditForm):
)
commit_rate = forms.IntegerField(
required=False,
label=_('Commit rate (Kbps)')
label=_('Commit rate (Kbps)'),
widget=NumberWithOptions(
options=CircuitCommitRateChoices
)
)
description = forms.CharField(
max_length=100,

View File

@@ -6,7 +6,8 @@ from dcim.models import Site
from django.utils.translation import gettext as _
from netbox.forms import NetBoxModelImportForm
from tenancy.models import Tenant
from utilities.forms import BootstrapMixin, CSVChoiceField, CSVModelChoiceField, SlugField
from utilities.forms import BootstrapMixin
from utilities.forms.fields import CSVChoiceField, CSVModelChoiceField, SlugField
__all__ = (
'CircuitImportForm',
@@ -73,7 +74,8 @@ class CircuitImportForm(NetBoxModelImportForm):
provider_account = CSVModelChoiceField(
queryset=ProviderAccount.objects.all(),
to_field_name='name',
help_text=_('Assigned provider account')
help_text=_('Assigned provider account'),
required=False
)
type = CSVModelChoiceField(
queryset=CircuitType.objects.all(),

View File

@@ -1,13 +1,14 @@
from django import forms
from django.utils.translation import gettext as _
from circuits.choices import CircuitStatusChoices
from circuits.choices import CircuitCommitRateChoices, CircuitStatusChoices
from circuits.models import *
from dcim.models import Region, Site, SiteGroup
from ipam.models import ASN
from netbox.forms import NetBoxModelFilterSetForm
from tenancy.forms import TenancyFilterForm, ContactModelFilterForm
from utilities.forms import DatePicker, DynamicModelMultipleChoiceField, TagFilterField
from utilities.forms.fields import DynamicModelMultipleChoiceField, TagFilterField
from utilities.forms.widgets import DatePicker, NumberWithOptions
__all__ = (
'CircuitFilterForm',
@@ -167,6 +168,9 @@ class CircuitFilterForm(TenancyFilterForm, ContactModelFilterForm, NetBoxModelFi
commit_rate = forms.IntegerField(
required=False,
min_value=0,
label=_('Commit rate (Kbps)')
label=_('Commit rate (Kbps)'),
widget=NumberWithOptions(
options=CircuitCommitRateChoices
)
)
tag = TagFilterField(model)

View File

@@ -1,13 +1,13 @@
from django.utils.translation import gettext as _
from circuits.choices import CircuitCommitRateChoices, CircuitTerminationPortSpeedChoices
from circuits.models import *
from dcim.models import Site
from ipam.models import ASN
from netbox.forms import NetBoxModelForm
from tenancy.forms import TenancyForm
from utilities.forms import (
CommentField, DatePicker, DynamicModelChoiceField, DynamicModelMultipleChoiceField, SelectSpeedWidget, SlugField,
)
from utilities.forms.fields import CommentField, DynamicModelChoiceField, DynamicModelMultipleChoiceField, SlugField
from utilities.forms.widgets import DatePicker, NumberWithOptions
__all__ = (
'CircuitForm',
@@ -117,7 +117,9 @@ class CircuitForm(TenancyForm, NetBoxModelForm):
widgets = {
'install_date': DatePicker(),
'termination_date': DatePicker(),
'commit_rate': SelectSpeedWidget(),
'commit_rate': NumberWithOptions(
options=CircuitCommitRateChoices
),
}
@@ -144,6 +146,10 @@ class CircuitTerminationForm(NetBoxModelForm):
'xconnect_id', 'pp_info', 'description', 'tags',
]
widgets = {
'port_speed': SelectSpeedWidget(),
'upstream_speed': SelectSpeedWidget(),
'port_speed': NumberWithOptions(
options=CircuitTerminationPortSpeedChoices
),
'upstream_speed': NumberWithOptions(
options=CircuitTerminationPortSpeedChoices
),
}

View File

@@ -64,7 +64,9 @@ class CircuitTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable):
template_code=CIRCUITTERMINATION_LINK,
verbose_name='Side Z'
)
commit_rate = CommitRateColumn()
commit_rate = CommitRateColumn(
verbose_name='Commit Rate'
)
comments = columns.MarkdownColumn()
tags = columns.TagColumn(
url_name='circuits:circuit_list'

View File

@@ -247,6 +247,7 @@ class CircuitTypeBulkDeleteView(generic.BulkDeleteView):
queryset = CircuitType.objects.annotate(
circuit_count=count_related(Circuit, 'type')
)
filterset = filtersets.CircuitTypeFilterSet
table = tables.CircuitTypeTable

View File

@@ -1,21 +1,12 @@
import re
import typing
from drf_spectacular.extensions import (
OpenApiSerializerFieldExtension,
OpenApiViewExtension,
)
from drf_spectacular.extensions import OpenApiSerializerFieldExtension
from drf_spectacular.openapi import AutoSchema
from drf_spectacular.plumbing import (
ComponentRegistry,
ResolvedComponent,
build_basic_type,
build_media_type_object,
build_object_type,
is_serializer,
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 extend_schema
from rest_framework.relations import ManyRelatedField
from netbox.api.fields import ChoiceField, SerializedPKRelatedField
@@ -38,7 +29,7 @@ class ChoiceFieldFix(OpenApiSerializerFieldExtension):
def map_serializer_field(self, auto_schema, direction):
if direction == 'request':
return build_basic_type(OpenApiTypes.STR)
return build_choice_field(self.target)
elif direction == "response":
return build_object_type(
@@ -150,8 +141,12 @@ class NetBoxAutoSchema(AutoSchema):
def get_writable_class(self, serializer):
properties = {}
fields = {} if hasattr(serializer, 'child') else serializer.fields
remove_fields = []
for child_name, child in fields.items():
# read_only fields don't need to be in writable (write only) serializers
if 'read_only' in dir(child) and child.read_only:
remove_fields.append(child_name)
if isinstance(child, (ChoiceField, WritableNestedSerializer)):
properties[child_name] = None
elif isinstance(child, ManyRelatedField) and isinstance(child.child_relation, SerializedPKRelatedField):
@@ -165,7 +160,12 @@ class NetBoxAutoSchema(AutoSchema):
meta_class = getattr(type(serializer), 'Meta', None)
if meta_class:
ref_name = 'Writable' + self.get_serializer_ref_name(serializer)
writable_meta = type('Meta', (meta_class,), {'ref_name': ref_name})
# remove read_only fields from write-only serializers
fields = list(meta_class.fields)
for field in remove_fields:
fields.remove(field)
writable_meta = type('Meta', (meta_class,), {'ref_name': ref_name, 'fields': fields})
properties['Meta'] = writable_meta
self.writable_serializers[type(serializer)] = type(writable_name, (type(serializer),), properties)
@@ -222,3 +222,31 @@ class NetBoxAutoSchema(AutoSchema):
if request_body_required:
request_body['required'] = request_body_required
return request_body
def get_description(self):
"""
Return a string description for the ViewSet.
"""
# If a docstring is provided, use it.
if self.view.__doc__:
return get_doc(self.view.__class__)
# When the action method is decorated with @action, use the docstring of the method.
action_or_method = getattr(self.view, getattr(self.view, 'action', self.method.lower()), None)
if action_or_method and action_or_method.__doc__:
return get_doc(action_or_method)
# Else, generate a description from the class name.
return self._generate_description()
def _generate_description(self):
"""
Generate a docstring for the method. It also takes into account whether the method is for list or detail.
"""
model_name = self.view.queryset.model._meta.verbose_name
# Determine if the method is for list or detail.
if '{id}' in self.path:
return f"{self.method.capitalize()} a {model_name} object."
return f"{self.method.capitalize()} a list of {model_name} objects."

View File

@@ -1,17 +1,18 @@
import logging
import os
import re
import subprocess
import tempfile
from contextlib import contextmanager
from pathlib import Path
from urllib.parse import quote, urlunparse, urlparse
from urllib.parse import urlparse
import boto3
from botocore.config import Config as Boto3Config
from django import forms
from django.conf import settings
from django.utils.translation import gettext as _
from dulwich import porcelain
from dulwich.config import ConfigDict
from netbox.registry import registry
from .choices import DataSourceTypeChoices
@@ -20,6 +21,7 @@ from .exceptions import SyncError
__all__ = (
'LocalBackend',
'GitBackend',
'S3Backend',
)
logger = logging.getLogger('netbox.data_backends')
@@ -29,6 +31,7 @@ def register_backend(name):
"""
Decorator for registering a DataBackend class.
"""
def _wrapper(cls):
registry['data_backends'][name] = cls
return cls
@@ -54,7 +57,6 @@ class DataBackend:
@register_backend(DataSourceTypeChoices.LOCAL)
class LocalBackend(DataBackend):
@contextmanager
def fetch(self):
logger.debug(f"Data source type is local; skipping fetch")
@@ -69,12 +71,14 @@ class GitBackend(DataBackend):
'username': forms.CharField(
required=False,
label=_('Username'),
widget=forms.TextInput(attrs={'class': 'form-control'})
widget=forms.TextInput(attrs={'class': 'form-control'}),
help_text=_("Only used for cloning with HTTP / HTTPS"),
),
'password': forms.CharField(
required=False,
label=_('Password'),
widget=forms.TextInput(attrs={'class': 'form-control'})
widget=forms.TextInput(attrs={'class': 'form-control'}),
help_text=_("Only used for cloning with HTTP / HTTPS"),
),
'branch': forms.CharField(
required=False,
@@ -87,37 +91,32 @@ class GitBackend(DataBackend):
def fetch(self):
local_path = tempfile.TemporaryDirectory()
# Add authentication credentials to URL (if specified)
username = self.params.get('username')
password = self.params.get('password')
if username and password:
# Add username & password to URL
parsed = urlparse(self.url)
url = f'{parsed.scheme}://{quote(username)}:{quote(password)}@{parsed.netloc}{parsed.path}'
else:
url = self.url
config = ConfigDict()
clone_args = {
"branch": self.params.get('branch'),
"config": config,
"depth": 1,
"errstream": porcelain.NoneStream(),
"quiet": True,
}
# Compile git arguments
args = [settings.GIT_PATH, 'clone', '--depth', '1']
if branch := self.params.get('branch'):
args.extend(['--branch', branch])
args.extend([url, local_path.name])
# Prep environment variables
env_vars = {}
if settings.HTTP_PROXIES and self.url_scheme in ('http', 'https'):
env_vars['http_proxy'] = settings.HTTP_PROXIES.get(self.url_scheme)
logger.debug(f"Cloning git repo: {' '.join(args)}")
try:
subprocess.run(args, check=True, capture_output=True, env=env_vars)
except FileNotFoundError as e:
raise SyncError(
f"Unable to fetch: git executable not found. Check that the git executable exists at the "
f"configured path: {settings.GIT_PATH}"
if self.url_scheme in ('http', 'https'):
clone_args.update(
{
"username": self.params.get('username'),
"password": self.params.get('password'),
}
)
except subprocess.CalledProcessError as e:
raise SyncError(f"Fetching remote data failed: {e.stderr}")
if settings.HTTP_PROXIES and self.url_scheme in ('http', 'https'):
if proxy := settings.HTTP_PROXIES.get(self.url_scheme):
config.set("http", "proxy", proxy)
logger.debug(f"Cloning git repo: {self.url}")
try:
porcelain.clone(self.url, local_path.name, **clone_args)
except BaseException as e:
raise SyncError(f"Fetching remote data failed ({type(e).__name__}): {e}")
yield local_path.name

View File

@@ -4,7 +4,9 @@ from django.utils.translation import gettext as _
from core.choices import DataSourceTypeChoices
from core.models import *
from netbox.forms import NetBoxModelBulkEditForm
from utilities.forms import add_blank_choice, BulkEditNullBooleanSelect, CommentField
from utilities.forms import add_blank_choice
from utilities.forms.fields import CommentField
from utilities.forms.widgets import BulkEditNullBooleanSelect
__all__ = (
'DataSourceBulkEditForm',

View File

@@ -8,10 +8,9 @@ from core.models import *
from extras.forms.mixins import SavedFiltersMixin
from extras.utils import FeatureQuery
from netbox.forms import NetBoxModelFilterSetForm
from utilities.forms import (
APISelectMultiple, BOOLEAN_WITH_BLANK_CHOICES, ContentTypeChoiceField, DateTimePicker,
DynamicModelMultipleChoiceField, FilterForm,
)
from utilities.forms import BOOLEAN_WITH_BLANK_CHOICES, FilterForm
from utilities.forms.fields import ContentTypeChoiceField, DynamicModelMultipleChoiceField
from utilities.forms.widgets import APISelectMultiple, DateTimePicker
__all__ = (
'DataFileFilterForm',

View File

@@ -0,0 +1,25 @@
from django import forms
from django.utils.translation import gettext as _
from core.models import DataFile, DataSource
from utilities.forms.fields import DynamicModelChoiceField
__all__ = (
'SyncedDataMixin',
)
class SyncedDataMixin(forms.Form):
data_source = DynamicModelChoiceField(
queryset=DataSource.objects.all(),
required=False,
label=_('Data source')
)
data_file = DynamicModelChoiceField(
queryset=DataFile.objects.all(),
required=False,
label=_('File'),
query_params={
'source_id': '$data_source',
}
)

View File

@@ -2,11 +2,13 @@ import copy
from django import forms
from core.forms.mixins import SyncedDataMixin
from core.models import *
from extras.forms.mixins import SyncedDataMixin
from netbox.forms import NetBoxModelForm
from netbox.registry import registry
from utilities.forms import CommentField, get_field_value
from utilities.forms import get_field_value
from utilities.forms.fields import CommentField
from utilities.forms.widgets import HTMXSelect
__all__ = (
'DataSourceForm',
@@ -23,13 +25,7 @@ class DataSourceForm(NetBoxModelForm):
'name', 'type', 'source_url', 'enabled', 'description', 'comments', 'ignore_rules', 'tags',
]
widgets = {
'type': forms.Select(
attrs={
'hx-get': '.',
'hx-include': '#form_fields input',
'hx-target': '#form_fields',
}
),
'type': HTMXSelect(),
'ignore_rules': forms.Textarea(
attrs={
'rows': 5,
@@ -84,12 +80,12 @@ class ManagedFileForm(SyncedDataMixin, NetBoxModelForm):
fieldsets = (
('File Upload', ('upload_file',)),
('Data Source', ('data_source', 'data_file')),
('Data Source', ('data_source', 'data_file', 'auto_sync_enabled')),
)
class Meta:
model = ManagedFile
fields = ('data_source', 'data_file')
fields = ('data_source', 'data_file', 'auto_sync_enabled')
def clean(self):
super().clean()

View File

@@ -24,7 +24,10 @@ def sync_datasource(job, *args, **kwargs):
job.terminate()
except (SyncError, JobTimeoutException) as e:
except Exception as e:
job.terminate(status=JobStatusChoices.STATUS_ERRORED)
DataSource.objects.filter(pk=datasource.pk).update(status=DataSourceStatusChoices.FAILED)
logging.error(e)
if type(e) in (SyncError, JobTimeoutException):
logging.error(e)
else:
raise e

View File

@@ -63,4 +63,21 @@ class Migration(migrations.Migration):
model_name='datafile',
index=models.Index(fields=['source', 'path'], name='core_datafile_source_path'),
),
migrations.CreateModel(
name='AutoSyncRecord',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False)),
('object_id', models.PositiveBigIntegerField()),
('datafile', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='+', to='core.datafile')),
('object_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='+', to='contenttypes.contenttype')),
],
),
migrations.AddIndex(
model_name='autosyncrecord',
index=models.Index(fields=['object_type', 'object_id'], name='core_autosy_object__c17bac_idx'),
),
migrations.AddConstraint(
model_name='autosyncrecord',
constraint=models.UniqueConstraint(fields=('object_type', 'object_id'), name='core_autosyncrecord_object'),
),
]

View File

@@ -23,6 +23,7 @@ class Migration(migrations.Migration):
('file_path', models.FilePathField(editable=False)),
('data_file', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='core.datafile')),
('data_source', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='+', to='core.datasource')),
('auto_sync_enabled', models.BooleanField(default=False)),
],
options={
'ordering': ('file_root', 'file_path'),

View File

@@ -27,6 +27,7 @@ def replicate_jobresults(apps, schema_editor):
)
if len(jobs) == 100:
Job.objects.bulk_create(jobs)
jobs = []
if jobs:
Job.objects.bulk_create(jobs)

View File

@@ -5,7 +5,8 @@ from fnmatch import fnmatchcase
from urllib.parse import urlparse
from django.conf import settings
from django.contrib.contenttypes.fields import GenericRelation
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django.db import models
@@ -25,6 +26,7 @@ from ..signals import post_sync, pre_sync
from .jobs import Job
__all__ = (
'AutoSyncRecord',
'DataFile',
'DataSource',
)
@@ -95,6 +97,10 @@ class DataSource(JobsMixin, PrimaryModel):
def url_scheme(self):
return urlparse(self.source_url).scheme.lower()
@property
def is_local(self):
return self.type == DataSourceTypeChoices.LOCAL
@property
def ready_for_sync(self):
return self.enabled and self.status not in (
@@ -107,7 +113,7 @@ class DataSource(JobsMixin, PrimaryModel):
# Ensure URL scheme matches selected type
if self.type == DataSourceTypeChoices.LOCAL and self.url_scheme not in ('file', ''):
raise ValidationError({
'url': f"URLs for local sources must start with file:// (or omit the scheme)"
'source_url': f"URLs for local sources must start with file:// (or specify no scheme)"
})
def enqueue_sync_job(self, request):
@@ -172,7 +178,7 @@ class DataSource(JobsMixin, PrimaryModel):
# Bulk delete deleted files
deleted_count, _ = DataFile.objects.filter(pk__in=deleted_file_ids).delete()
logger.debug(f"Deleted {updated_count} files")
logger.debug(f"Deleted {deleted_count} files")
# Walk the local replication to find new files
new_paths = self._walk(local_path) - known_paths
@@ -323,3 +329,35 @@ class DataFile(models.Model):
with open(path, 'wb+') as new_file:
new_file.write(self.data)
class AutoSyncRecord(models.Model):
"""
Maps a DataFile to a synced object for efficient automatic updating.
"""
datafile = models.ForeignKey(
to=DataFile,
on_delete=models.CASCADE,
related_name='+'
)
object_type = models.ForeignKey(
to=ContentType,
on_delete=models.CASCADE,
related_name='+'
)
object_id = models.PositiveBigIntegerField()
object = GenericForeignKey(
ct_field='object_type',
fk_field='object_id'
)
class Meta:
constraints = (
models.UniqueConstraint(
fields=('object_type', 'object_id'),
name='%(app_label)s_%(class)s_object'
),
)
indexes = (
models.Index(fields=('object_type', 'object_id')),
)

View File

@@ -102,6 +102,7 @@ class Job(models.Model):
return reverse(f'extras:report_result', kwargs={'job_pk': self.pk})
if self.object_type.model == 'scriptmodule':
return reverse(f'extras:script_result', kwargs={'job_pk': self.pk})
return reverse('core:job', args=[self.pk])
def get_status_color(self):
return JobStatusChoices.colors.get(self.status)

View File

@@ -1,4 +1,4 @@
import django.dispatch
from django.dispatch import Signal, receiver
__all__ = (
'post_sync',
@@ -6,5 +6,16 @@ __all__ = (
)
# DataSource signals
pre_sync = django.dispatch.Signal()
post_sync = django.dispatch.Signal()
pre_sync = Signal()
post_sync = Signal()
@receiver(post_sync)
def auto_sync(instance, **kwargs):
"""
Automatically synchronize any DataFiles with AutoSyncRecords after synchronizing a DataSource.
"""
from .models import AutoSyncRecord
for autosync in AutoSyncRecord.objects.filter(datafile__source=instance).prefetch_related('object'):
autosync.object.sync(save=True)

View File

@@ -22,6 +22,7 @@ urlpatterns = (
# Job results
path('jobs/', views.JobListView.as_view(), name='job_list'),
path('jobs/delete/', views.JobBulkDeleteView.as_view(), name='job_bulk_delete'),
path('jobs/<int:pk>/', views.JobView.as_view(), name='job'),
path('jobs/<int:pk>/delete/', views.JobDeleteView.as_view(), name='job_delete'),
)

View File

@@ -3,7 +3,6 @@ from django.shortcuts import get_object_or_404, redirect
from netbox.views import generic
from netbox.views.generic.base import BaseObjectView
from utilities.rqworker import get_queue_for_model, get_workers_for_queue
from utilities.utils import count_related
from utilities.views import register_model_view
from . import filtersets, forms, tables
@@ -127,7 +126,11 @@ class JobListView(generic.ObjectListView):
filterset = filtersets.JobFilterSet
filterset_form = forms.JobFilterForm
table = tables.JobTable
actions = ('export', 'delete', 'bulk_delete', )
actions = ('export', 'delete', 'bulk_delete')
class JobView(generic.ObjectView):
queryset = Job.objects.all()
class JobDeleteView(generic.ObjectDeleteView):

View File

@@ -456,7 +456,7 @@ class NestedInventoryItemRoleSerializer(WritableNestedSerializer):
# Cables
#
class NestedCableSerializer(BaseModelSerializer):
class NestedCableSerializer(WritableNestedSerializer):
url = serializers.HyperlinkedIdentityField(view_name='dcim-api:cable-detail')
class Meta:

View File

@@ -904,7 +904,11 @@ class InterfaceSerializer(NetBoxModelSerializer, CabledObjectSerializer, Connect
)
count_ipaddresses = serializers.IntegerField(read_only=True)
count_fhrp_groups = serializers.IntegerField(read_only=True)
mac_address = serializers.CharField(required=False, default=None)
mac_address = serializers.CharField(
required=False,
default=None,
allow_null=True
)
wwn = serializers.CharField(required=False, default=None)
class Meta:
@@ -1097,7 +1101,8 @@ class CableTerminationSerializer(NetBoxModelSerializer):
class Meta:
model = CableTermination
fields = [
'id', 'url', 'display', 'cable', 'cable_end', 'termination_type', 'termination_id', 'termination'
'id', 'url', 'display', 'cable', 'cable_end', 'termination_type', 'termination_id', 'termination',
'created', 'last_updated',
]
@extend_schema_field(serializers.JSONField(allow_null=True))

View File

@@ -423,9 +423,13 @@ class DeviceViewSet(ConfigContextQuerySetMixin, ConfigTemplateRenderMixin, NetBo
configtemplate = device.get_config_template()
if not configtemplate:
return Response({'error': 'No config template found for this device.'}, status=HTTP_400_BAD_REQUEST)
context = {**request.data, 'device': device}
return self.render_configtemplate(request, configtemplate, context)
# Compile context data
context_data = device.get_config_context()
context_data.update(request.data)
context_data.update({'device': device})
return self.render_configtemplate(request, configtemplate, context_data)
class VirtualDeviceContextViewSet(NetBoxModelViewSet):

View File

@@ -1096,6 +1096,20 @@ class InterfaceTypeChoices(ChoiceSet):
)
class InterfaceSpeedChoices(ChoiceSet):
key = 'Interface.speed'
CHOICES = [
(10000, '10 Mbps'),
(100000, '100 Mbps'),
(1000000, '1 Gbps'),
(10000000, '10 Gbps'),
(25000000, '25 Gbps'),
(40000000, '40 Gbps'),
(100000000, '100 Gbps'),
]
class InterfaceDuplexChoices(ChoiceSet):
DUPLEX_HALF = 'half'

View File

@@ -25,6 +25,7 @@ __all__ = (
'CableFilterSet',
'CabledObjectFilterSet',
'CableTerminationFilterSet',
'CommonInterfaceFilterSet',
'ConsoleConnectionFilterSet',
'ConsolePortFilterSet',
'ConsolePortTemplateFilterSet',
@@ -810,7 +811,7 @@ class PlatformFilterSet(OrganizationalModelFilterSet):
class Meta:
model = Platform
fields = ['id', 'name', 'slug', 'description']
fields = ['id', 'name', 'slug', 'napalm_driver', 'description']
class DeviceFilterSet(NetBoxModelFilterSet, TenancyFilterSet, ContactModelFilterSet, LocalConfigContextFilterSet):
@@ -1348,11 +1349,63 @@ class PowerOutletFilterSet(
fields = ['id', 'name', 'label', 'feed_leg', 'description', 'cable_end']
class CommonInterfaceFilterSet(django_filters.FilterSet):
vlan_id = django_filters.CharFilter(
method='filter_vlan_id',
label=_('Assigned VLAN')
)
vlan = django_filters.CharFilter(
method='filter_vlan',
label=_('Assigned VID')
)
vrf_id = django_filters.ModelMultipleChoiceFilter(
field_name='vrf',
queryset=VRF.objects.all(),
label=_('VRF'),
)
vrf = django_filters.ModelMultipleChoiceFilter(
field_name='vrf__rd',
queryset=VRF.objects.all(),
to_field_name='rd',
label=_('VRF (RD)'),
)
l2vpn_id = django_filters.ModelMultipleChoiceFilter(
field_name='l2vpn_terminations__l2vpn',
queryset=L2VPN.objects.all(),
label=_('L2VPN (ID)'),
)
l2vpn = django_filters.ModelMultipleChoiceFilter(
field_name='l2vpn_terminations__l2vpn__identifier',
queryset=L2VPN.objects.all(),
to_field_name='identifier',
label=_('L2VPN'),
)
def filter_vlan_id(self, queryset, name, value):
value = value.strip()
if not value:
return queryset
return queryset.filter(
Q(untagged_vlan_id=value) |
Q(tagged_vlans=value)
)
def filter_vlan(self, queryset, name, value):
value = value.strip()
if not value:
return queryset
return queryset.filter(
Q(untagged_vlan_id__vid=value) |
Q(tagged_vlans__vid=value)
)
class InterfaceFilterSet(
ModularDeviceComponentFilterSet,
NetBoxModelFilterSet,
CabledObjectFilterSet,
PathEndpointFilterSet
PathEndpointFilterSet,
CommonInterfaceFilterSet
):
# Override device and device_id filters from DeviceComponentFilterSet to match against any peer virtual chassis
# members
@@ -1397,14 +1450,6 @@ class InterfaceFilterSet(
poe_type = django_filters.MultipleChoiceFilter(
choices=InterfacePoETypeChoices
)
vlan_id = django_filters.CharFilter(
method='filter_vlan_id',
label=_('Assigned VLAN')
)
vlan = django_filters.CharFilter(
method='filter_vlan',
label=_('Assigned VID')
)
type = django_filters.MultipleChoiceFilter(
choices=InterfaceTypeChoices,
null_value=None
@@ -1415,17 +1460,6 @@ class InterfaceFilterSet(
rf_channel = django_filters.MultipleChoiceFilter(
choices=WirelessChannelChoices
)
vrf_id = django_filters.ModelMultipleChoiceFilter(
field_name='vrf',
queryset=VRF.objects.all(),
label=_('VRF'),
)
vrf = django_filters.ModelMultipleChoiceFilter(
field_name='vrf__rd',
queryset=VRF.objects.all(),
to_field_name='rd',
label=_('VRF (RD)'),
)
vdc_id = django_filters.ModelMultipleChoiceFilter(
field_name='vdcs',
queryset=VirtualDeviceContext.objects.all(),
@@ -1443,17 +1477,6 @@ class InterfaceFilterSet(
to_field_name='name',
label='Virtual Device Context',
)
l2vpn_id = django_filters.ModelMultipleChoiceFilter(
field_name='l2vpn_terminations__l2vpn',
queryset=L2VPN.objects.all(),
label=_('L2VPN (ID)'),
)
l2vpn = django_filters.ModelMultipleChoiceFilter(
field_name='l2vpn_terminations__l2vpn__identifier',
queryset=L2VPN.objects.all(),
to_field_name='identifier',
label=_('L2VPN'),
)
class Meta:
model = Interface
@@ -1483,24 +1506,6 @@ class InterfaceFilterSet(
except Device.DoesNotExist:
return queryset.none()
def filter_vlan_id(self, queryset, name, value):
value = value.strip()
if not value:
return queryset
return queryset.filter(
Q(untagged_vlan_id=value) |
Q(tagged_vlans=value)
)
def filter_vlan(self, queryset, name, value):
value = value.strip()
if not value:
return queryset
return queryset.filter(
Q(untagged_vlan_id__vid=value) |
Q(tagged_vlans__vid=value)
)
def filter_kind(self, queryset, name, value):
value = value.strip().lower()
return {
@@ -1689,12 +1694,14 @@ class CableFilterSet(TenancyFilterSet, NetBoxModelFilterSet):
field_name='terminations__termination_type'
)
termination_a_id = MultiValueNumberFilter(
method='filter_by_cable_end_a',
field_name='terminations__termination_id'
)
termination_b_type = ContentTypeFilter(
field_name='terminations__termination_type'
)
termination_b_id = MultiValueNumberFilter(
method='filter_by_cable_end_b',
field_name='terminations__termination_id'
)
type = django_filters.MultipleChoiceFilter(
@@ -1752,6 +1759,18 @@ class CableFilterSet(TenancyFilterSet, NetBoxModelFilterSet):
# Supported objects: device, rack, location, site
return queryset.filter(**{f'terminations___{name}__in': value}).distinct()
def filter_by_cable_end(self, queryset, name, value, side):
# Filter by termination id and cable_end type
return queryset.filter(**{f'{name}__in': value, 'terminations__cable_end': side}).distinct()
def filter_by_cable_end_a(self, queryset, name, value):
# Filter by termination id and cable_end type
return self.filter_by_cable_end(queryset, name, value, CableEndChoices.SIDE_A)
def filter_by_cable_end_b(self, queryset, name, value):
# Filter by termination id and cable_end type
return self.filter_by_cable_end(queryset, name, value, CableEndChoices.SIDE_B)
class CableTerminationFilterSet(BaseFilterSet):
termination_type = ContentTypeFilter()
@@ -1881,6 +1900,7 @@ class PowerFeedFilterSet(NetBoxModelFilterSet, CabledObjectFilterSet, PathEndpoi
return queryset
qs_filter = (
Q(name__icontains=value) |
Q(power_panel__name__icontains=value) |
Q(comments__icontains=value)
)
return queryset.filter(qs_filter)

View File

@@ -4,7 +4,8 @@ from dcim.models import *
from django.utils.translation import gettext as _
from extras.forms import CustomFieldsMixin
from extras.models import Tag
from utilities.forms import BootstrapMixin, DynamicModelMultipleChoiceField, ExpandableNameField, form_from_model
from utilities.forms import BootstrapMixin, form_from_model
from utilities.forms.fields import DynamicModelMultipleChoiceField, ExpandableNameField
from .object_create import ComponentCreateForm
__all__ = (
@@ -103,9 +104,9 @@ class RearPortBulkCreateForm(
class ModuleBayBulkCreateForm(DeviceBulkAddComponentForm):
model = ModuleBay
field_order = ('name', 'label', 'position_pattern', 'description', 'tags')
field_order = ('name', 'label', 'position', 'description', 'tags')
replication_fields = ('name', 'label', 'position')
position_pattern = ExpandableNameField(
position = ExpandableNameField(
label=_('Position'),
required=False,
help_text=_('Alphanumeric ranges are supported. (Must match the number of names being created.)')

View File

@@ -10,10 +10,10 @@ from extras.models import ConfigTemplate
from ipam.models import ASN, VLAN, VLANGroup, VRF
from netbox.forms import NetBoxModelBulkEditForm
from tenancy.models import Tenant
from utilities.forms import (
add_blank_choice, BulkEditForm, BulkEditNullBooleanSelect, ColorField, CommentField, DynamicModelChoiceField,
DynamicModelMultipleChoiceField, form_from_model, SelectSpeedWidget,
)
from utilities.forms import BulkEditForm, add_blank_choice, form_from_model
from utilities.forms.fields import ColorField, CommentField, DynamicModelChoiceField, DynamicModelMultipleChoiceField
from utilities.forms.widgets import BulkEditNullBooleanSelect, NumberWithOptions
from wireless.models import WirelessLAN, WirelessLANGroup
__all__ = (
'CableBulkEditForm',
@@ -471,6 +471,10 @@ class PlatformBulkEditForm(NetBoxModelBulkEditForm):
queryset=Manufacturer.objects.all(),
required=False
)
napalm_driver = forms.CharField(
max_length=50,
required=False
)
config_template = DynamicModelChoiceField(
queryset=ConfigTemplate.objects.all(),
required=False
@@ -482,9 +486,9 @@ class PlatformBulkEditForm(NetBoxModelBulkEditForm):
model = Platform
fieldsets = (
(None, ('manufacturer', 'config_template', 'description')),
(None, ('manufacturer', 'config_template', 'napalm_driver', 'description')),
)
nullable_fields = ('manufacturer', 'config_template', 'description')
nullable_fields = ('manufacturer', 'config_template', 'napalm_driver', 'description')
class DeviceBulkEditForm(NetBoxModelBulkEditForm):
@@ -1136,7 +1140,7 @@ class InterfaceBulkEditForm(
form_from_model(Interface, [
'label', 'type', 'parent', 'bridge', 'lag', 'speed', 'duplex', 'mac_address', 'wwn', 'mtu', 'mgmt_only',
'mark_connected', 'description', 'mode', 'rf_role', 'rf_channel', 'rf_channel_frequency', 'rf_channel_width',
'tx_power',
'tx_power', 'wireless_lans'
]),
ComponentBulkEditForm
):
@@ -1170,8 +1174,9 @@ class InterfaceBulkEditForm(
)
speed = forms.IntegerField(
required=False,
widget=SelectSpeedWidget(),
label=_('Speed')
widget=NumberWithOptions(
options=InterfaceSpeedChoices
)
)
mgmt_only = forms.NullBooleanField(
required=False,
@@ -1225,6 +1230,19 @@ class InterfaceBulkEditForm(
required=False,
label=_('VRF')
)
wireless_lan_group = DynamicModelChoiceField(
queryset=WirelessLANGroup.objects.all(),
required=False,
label=_('Wireless LAN group')
)
wireless_lans = DynamicModelMultipleChoiceField(
queryset=WirelessLAN.objects.all(),
required=False,
label=_('Wireless LANs'),
query_params={
'group_id': '$wireless_lan_group',
}
)
model = Interface
fieldsets = (
@@ -1234,12 +1252,14 @@ class InterfaceBulkEditForm(
('PoE', ('poe_mode', 'poe_type')),
('Related Interfaces', ('parent', 'bridge', 'lag')),
('802.1Q Switching', ('mode', 'vlan_group', 'untagged_vlan', 'tagged_vlans')),
('Wireless', ('rf_role', 'rf_channel', 'rf_channel_frequency', 'rf_channel_width')),
('Wireless', (
'rf_role', 'rf_channel', 'rf_channel_frequency', 'rf_channel_width', 'wireless_lan_group', 'wireless_lans',
)),
)
nullable_fields = (
'module', 'label', 'parent', 'bridge', 'lag', 'speed', 'duplex', 'mac_address', 'wwn', 'vdcs', 'mtu', 'description',
'poe_mode', 'poe_type', 'mode', 'rf_channel', 'rf_channel_frequency', 'rf_channel_width', 'tx_power',
'vlan_group', 'untagged_vlan', 'tagged_vlans', 'vrf',
'vlan_group', 'untagged_vlan', 'tagged_vlans', 'vrf', 'wireless_lans'
)
def __init__(self, *args, **kwargs):
@@ -1306,6 +1326,11 @@ class FrontPortBulkEditForm(
form_from_model(FrontPort, ['label', 'type', 'color', 'mark_connected', 'description']),
ComponentBulkEditForm
):
mark_connected = forms.NullBooleanField(
required=False,
widget=BulkEditNullBooleanSelect
)
model = FrontPort
fieldsets = (
(None, ('module', 'type', 'label', 'color', 'description', 'mark_connected')),
@@ -1317,6 +1342,11 @@ class RearPortBulkEditForm(
form_from_model(RearPort, ['label', 'type', 'color', 'mark_connected', 'description']),
ComponentBulkEditForm
):
mark_connected = forms.NullBooleanField(
required=False,
widget=BulkEditNullBooleanSelect
)
model = RearPort
fieldsets = (
(None, ('module', 'type', 'label', 'color', 'description', 'mark_connected')),

View File

@@ -12,8 +12,9 @@ from extras.models import ConfigTemplate
from ipam.models import VRF
from netbox.forms import NetBoxModelImportForm
from tenancy.models import Tenant
from utilities.forms import (
CSVChoiceField, CSVContentTypeField, CSVModelChoiceField, CSVTypedChoiceField, SlugField, CSVModelMultipleChoiceField
from utilities.forms.fields import (
CSVChoiceField, CSVContentTypeField, CSVModelChoiceField, CSVModelMultipleChoiceField, CSVTypedChoiceField,
SlugField,
)
from virtualization.models import Cluster
from wireless.choices import WirelessRoleChoices
@@ -346,7 +347,7 @@ class PlatformImportForm(NetBoxModelImportForm):
class Meta:
model = Platform
fields = (
'name', 'slug', 'manufacturer', 'config_template', 'description', 'tags',
'name', 'slug', 'manufacturer', 'config_template', 'napalm_driver', 'napalm_args', 'description', 'tags',
)
@@ -946,7 +947,7 @@ class InventoryItemImportForm(NetBoxModelImportForm):
component_name = self.cleaned_data.get('component_name')
device = self.cleaned_data.get("device")
if not device and hasattr(self, 'instance'):
if not device and hasattr(self, 'instance') and hasattr(self.instance, 'device'):
device = self.instance.device
if not all([device, content_type, component_name]):

View File

@@ -3,7 +3,7 @@ from django.utils.translation import gettext as _
from dcim.choices import *
from dcim.constants import *
from utilities.forms.utils import get_field_value
from utilities.forms import get_field_value
__all__ = (
'InterfaceCommonForm',

View File

@@ -1,9 +1,9 @@
from django import forms
from django.utils.translation import gettext as _
from circuits.models import Circuit, CircuitTermination, Provider
from circuits.models import Circuit, CircuitTermination
from dcim.models import *
from utilities.forms import DynamicModelChoiceField, DynamicModelMultipleChoiceField
from utilities.forms.fields import DynamicModelChoiceField, DynamicModelMultipleChoiceField
from .model_forms import CableForm

View File

@@ -10,10 +10,9 @@ from extras.models import ConfigTemplate
from ipam.models import ASN, L2VPN, VRF
from netbox.forms import NetBoxModelFilterSetForm
from tenancy.forms import ContactModelFilterForm, TenancyFilterForm
from utilities.forms import (
APISelectMultiple, add_blank_choice, ColorField, DynamicModelMultipleChoiceField, FilterForm,
TagFilterField, BOOLEAN_WITH_BLANK_CHOICES, SelectSpeedWidget,
)
from utilities.forms import BOOLEAN_WITH_BLANK_CHOICES, FilterForm, add_blank_choice
from utilities.forms.fields import ColorField, DynamicModelMultipleChoiceField, TagFilterField
from utilities.forms.widgets import APISelectMultiple, NumberWithOptions
from wireless.choices import *
__all__ = (
@@ -299,6 +298,15 @@ class RackFilterForm(TenancyFilterForm, ContactModelFilterForm, NetBoxModelFilte
class RackElevationFilterForm(RackFilterForm):
fieldsets = (
(None, ('q', 'filter_id', 'tag')),
('Location', ('region_id', 'site_group_id', 'site_id', 'location_id', 'id')),
('Function', ('status', 'role_id')),
('Hardware', ('type', 'width', 'serial', 'asset_tag')),
('Tenant', ('tenant_group_id', 'tenant_id')),
('Contacts', ('contact', 'contact_role', 'contact_group')),
('Weight', ('weight', 'max_weight', 'weight_unit')),
)
id = DynamicModelMultipleChoiceField(
queryset=Rack.objects.all(),
label=_('Rack'),
@@ -1155,8 +1163,9 @@ class InterfaceFilterForm(PathEndpointFilterForm, DeviceComponentFilterForm):
)
speed = forms.IntegerField(
required=False,
label='Speed',
widget=SelectSpeedWidget()
widget=NumberWithOptions(
options=InterfaceSpeedChoices
)
)
duplex = forms.MultipleChoiceField(
choices=InterfaceDuplexChoices,

View File

@@ -11,11 +11,12 @@ from extras.models import ConfigTemplate
from ipam.models import ASN, IPAddress, VLAN, VLANGroup, VRF
from netbox.forms import NetBoxModelForm
from tenancy.forms import TenancyForm
from utilities.forms import (
APISelect, add_blank_choice, BootstrapMixin, ClearableFileInput, CommentField, ContentTypeChoiceField,
DynamicModelChoiceField, DynamicModelMultipleChoiceField, JSONField, NumericArrayField, SelectWithPK,
SlugField, SelectSpeedWidget
from utilities.forms import BootstrapMixin, add_blank_choice
from utilities.forms.fields import (
CommentField, ContentTypeChoiceField, DynamicModelChoiceField, DynamicModelMultipleChoiceField, JSONField,
NumericArrayField, SlugField,
)
from utilities.forms.widgets import APISelect, ClearableFileInput, HTMXSelect, NumberWithOptions, SelectWithPK
from virtualization.models import Cluster
from wireless.models import WirelessLAN, WirelessLANGroup
from .common import InterfaceCommonForm, ModuleCommonForm
@@ -360,15 +361,18 @@ class PlatformForm(NetBoxModelForm):
fieldsets = (
('Platform', (
'name', 'slug', 'manufacturer', 'config_template', 'description', 'tags',
'name', 'slug', 'manufacturer', 'config_template', 'napalm_driver', 'napalm_args', 'description', 'tags',
)),
)
class Meta:
model = Platform
fields = [
'name', 'slug', 'manufacturer', 'config_template', 'description', 'tags',
'name', 'slug', 'manufacturer', 'config_template', 'napalm_driver', 'napalm_args', 'description', 'tags',
]
widgets = {
'napalm_args': forms.Textarea(),
}
class DeviceForm(TenancyForm, NetBoxModelForm):
@@ -1135,14 +1139,10 @@ class InterfaceForm(InterfaceCommonForm, ModularDeviceComponentForm):
'untagged_vlan', 'tagged_vlans', 'vrf', 'tags',
]
widgets = {
'speed': SelectSpeedWidget(),
'mode': forms.Select(
attrs={
'hx-get': '.',
'hx-include': '#form_fields input',
'hx-target': '#form_fields',
}
'speed': NumberWithOptions(
options=InterfaceSpeedChoices
),
'mode': HTMXSelect(),
}
labels = {
'mode': '802.1Q Mode',

View File

@@ -3,7 +3,8 @@ from django.utils.translation import gettext as _
from dcim.models import *
from netbox.forms import NetBoxModelForm
from utilities.forms import DynamicModelChoiceField, DynamicModelMultipleChoiceField, ExpandableNameField
from utilities.forms.fields import DynamicModelChoiceField, DynamicModelMultipleChoiceField, ExpandableNameField
from utilities.forms.widgets import APISelect
from . import model_forms
__all__ = (
@@ -225,6 +226,18 @@ class InterfaceCreateForm(ComponentCreateForm, model_forms.InterfaceForm):
class FrontPortCreateForm(ComponentCreateForm, model_forms.FrontPortForm):
device = DynamicModelChoiceField(
queryset=Device.objects.all(),
selector=True,
widget=APISelect(
# TODO: Clean up the application of HTMXSelect attributes
attrs={
'hx-get': '.',
'hx-include': f'#form_fields',
'hx-target': f'#form_fields',
}
)
)
rear_port = forms.MultipleChoiceField(
choices=[],
label=_('Rear ports'),
@@ -244,9 +257,10 @@ class FrontPortCreateForm(ComponentCreateForm, model_forms.FrontPortForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
device = Device.objects.get(
pk=self.initial.get('device') or self.data.get('device')
)
if device_id := self.data.get('device') or self.initial.get('device'):
device = Device.objects.get(pk=device_id)
else:
return
# Determine which rear port positions are occupied. These will be excluded from the list of available
# mappings.

View File

@@ -1,6 +1,5 @@
# Generated by Django 4.1.5 on 2023-01-09 07:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
@@ -15,4 +14,9 @@ class Migration(migrations.Migration):
name='enabled',
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name='interfacetemplate',
name='bridge',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='bridge_interfaces', to='dcim.interfacetemplate'),
),
]

View File

@@ -0,0 +1,21 @@
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dcim', '0170_configtemplate'),
]
operations = [
migrations.AddField(
model_name='cabletermination',
name='created',
field=models.DateTimeField(auto_now_add=True, null=True),
),
migrations.AddField(
model_name='cabletermination',
name='last_updated',
field=models.DateTimeField(auto_now=True, null=True),
),
]

View File

@@ -1,19 +0,0 @@
# Generated by Django 4.1.6 on 2023-03-01 13:42
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dcim', '0170_configtemplate'),
]
operations = [
migrations.AddField(
model_name='interfacetemplate',
name='bridge',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='bridge_interfaces', to='dcim.interfacetemplate'),
),
]

View File

@@ -13,7 +13,8 @@ from dcim.choices import *
from dcim.constants import *
from dcim.fields import PathField
from dcim.utils import decompile_path_node, object_to_path_node
from netbox.models import PrimaryModel
from netbox.models import ChangeLoggedModel, PrimaryModel
from utilities.fields import ColorField
from utilities.querysets import RestrictedQuerySet
from utilities.utils import to_meters
@@ -152,8 +153,6 @@ class Cable(PrimaryModel):
# Validate length and length_unit
if self.length is not None and not self.length_unit:
raise ValidationError("Must specify a unit when setting a cable length")
elif self.length is None:
self.length_unit = ''
if self.pk is None and (not self.a_terminations or not self.b_terminations):
raise ValidationError("Must define A and B terminations when creating a new cable.")
@@ -187,6 +186,10 @@ class Cable(PrimaryModel):
else:
self._abs_length = None
# Clear length_unit if no length is defined
if self.length is None:
self.length_unit = ''
super().save(*args, **kwargs)
# Update the private pk used in __str__ in case this is a new object (i.e. just got its pk)
@@ -220,7 +223,7 @@ class Cable(PrimaryModel):
return LinkStatusChoices.colors.get(self.status)
class CableTermination(models.Model):
class CableTermination(ChangeLoggedModel):
"""
A mapping between side A or B of a Cable and a terminating object (e.g. an Interface or CircuitTermination).
"""
@@ -357,6 +360,11 @@ class CableTermination(models.Model):
elif getattr(self.termination, 'site', None):
self._site = self.termination.site
def to_objectchange(self, action):
objectchange = super().to_objectchange(action)
objectchange.related_object = self.termination
return objectchange
class CablePath(models.Model):
"""

View File

@@ -80,11 +80,25 @@ class ComponentTemplateModel(ChangeLoggedModel):
"""
raise NotImplementedError()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Cache the original DeviceType ID for reference under clean()
self._original_device_type = self.device_type_id
def to_objectchange(self, action):
objectchange = super().to_objectchange(action)
objectchange.related_object = self.device_type
return objectchange
def clean(self):
super().clean()
if self.pk is not None and self._original_device_type != self.device_type_id:
raise ValidationError({
"device_type": "Component templates cannot be moved to a different device type."
})
class ModularComponentTemplateModel(ComponentTemplateModel):
"""

View File

@@ -78,6 +78,12 @@ class ComponentModel(NetBoxModel):
),
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Cache the original Device ID for reference under clean()
self._original_device = self.device_id
def __str__(self):
if self.label:
return f"{self.name} ({self.label})"
@@ -88,6 +94,15 @@ class ComponentModel(NetBoxModel):
objectchange.related_object = self.device
return objectchange
def clean(self):
super().clean()
# Check list of Modules that allow device field to be changed
if (type(self) not in [InventoryItem]) and (self.pk is not None) and (self._original_device != self.device_id):
raise ValidationError({
"device": "Components cannot be moved to a different device."
})
@property
def parent_object(self):
return self.device
@@ -797,8 +812,6 @@ class Interface(ModularComponentModel, BaseInterface, CabledObjectModel, PathEnd
raise ValidationError({
'rf_channel_frequency': "Cannot specify custom frequency with channel selected.",
})
elif self.rf_channel:
self.rf_channel_frequency = get_channel_attr(self.rf_channel, 'frequency')
# Validate channel width against interface type and selected channel (if any)
if self.rf_channel_width:
@@ -806,8 +819,6 @@ class Interface(ModularComponentModel, BaseInterface, CabledObjectModel, PathEnd
raise ValidationError({'rf_channel_width': "Channel width may be set only on wireless interfaces."})
if self.rf_channel and self.rf_channel_width != get_channel_attr(self.rf_channel, 'width'):
raise ValidationError({'rf_channel_width': "Cannot specify custom width with channel selected."})
elif self.rf_channel:
self.rf_channel_width = get_channel_attr(self.rf_channel, 'width')
# VLAN validation
@@ -818,6 +829,16 @@ class Interface(ModularComponentModel, BaseInterface, CabledObjectModel, PathEnd
f"interface's parent device, or it must be global."
})
def save(self, *args, **kwargs):
# Set absolute channel attributes from selected options
if self.rf_channel and not self.rf_channel_frequency:
self.rf_channel_frequency = get_channel_attr(self.rf_channel, 'frequency')
if self.rf_channel and not self.rf_channel_width:
self.rf_channel_width = get_channel_attr(self.rf_channel, 'width')
super().save(*args, **kwargs)
@property
def _occupied(self):
return super()._occupied or bool(self.wireless_link_id)

View File

@@ -128,6 +128,10 @@ class DeviceType(PrimaryModel, WeightMixin):
blank=True
)
images = GenericRelation(
to='extras.ImageAttachment'
)
clone_fields = (
'manufacturer', 'default_platform', 'u_height', 'is_full_depth', 'subdevice_role', 'airflow', 'weight', 'weight_unit'
)
@@ -707,8 +711,6 @@ class Device(PrimaryModel, ConfigContextModel):
raise ValidationError({
'rack': f"Rack {self.rack} does not belong to location {self.location}.",
})
elif self.rack:
self.location = self.rack.location
if self.rack is None:
if self.face:
@@ -824,8 +826,10 @@ class Device(PrimaryModel, ConfigContextModel):
bulk_create: If True, bulk_create() will be called to create all components in a single query
(default). Otherwise, save() will be called on each instance individually.
"""
components = [obj.instantiate(device=self) for obj in queryset]
if components and bulk_create:
if bulk_create:
components = [obj.instantiate(device=self) for obj in queryset]
if not components:
return
model = components[0]._meta.model
model.objects.bulk_create(components)
# Manually send the post_save signal for each of the newly created components
@@ -838,8 +842,9 @@ class Device(PrimaryModel, ConfigContextModel):
using='default',
update_fields=None
)
elif components:
for component in components:
else:
for obj in queryset:
component = obj.instantiate(device=self)
component.save()
def save(self, *args, **kwargs):
@@ -853,6 +858,10 @@ class Device(PrimaryModel, ConfigContextModel):
if is_new and not self.platform:
self.platform = self.device_type.default_platform
# Inherit location from Rack if not set
if self.rack and self.rack.location:
self.location = self.rack.location
super().save(*args, **kwargs)
# If this is a new Device, instantiate all the related components per the DeviceType definition

View File

@@ -222,8 +222,6 @@ class Rack(PrimaryModel, WeightMixin):
# Validate outer dimensions and unit
if (self.outer_width is not None or self.outer_depth is not None) and not self.outer_unit:
raise ValidationError("Must specify a unit when setting an outer width/depth")
elif self.outer_width is None and self.outer_depth is None:
self.outer_unit = ''
# Validate max_weight and weight_unit
if self.max_weight and not self.weight_unit:
@@ -259,6 +257,10 @@ class Rack(PrimaryModel, WeightMixin):
else:
self._abs_max_weight = None
# Clear unit if outer width & depth are not set
if self.outer_width is None and self.outer_depth is None:
self.outer_unit = ''
super().save(*args, **kwargs)
@property

View File

@@ -172,6 +172,7 @@ class PlatformIndex(SearchIndex):
fields = (
('name', 100),
('slug', 110),
('napalm_driver', 300),
('description', 500),
)

View File

@@ -37,15 +37,28 @@ def get_device_name(device):
def get_device_description(device):
return '{} ({}) — {} {} ({}U) {} {}'.format(
device.name,
device.device_role,
device.device_type.manufacturer.name,
device.device_type.model,
floatformat(device.device_type.u_height),
device.asset_tag or '',
device.serial or ''
)
"""
Return a description for a device to be rendered in the rack elevation in the following format
Name: <name>
Role: <device_role>
Device Type: <manufacturer> <model> (<u_height>)
Asset tag: <asset_tag> (if defined)
Serial: <serial> (if defined)
Description: <description> (if defined)
"""
description = f'Name: {device.name}'
description += f'\nRole: {device.device_role}'
u_height = f'{floatformat(device.device_type.u_height)}U'
description += f'\nDevice Type: {device.device_type.manufacturer.name} {device.device_type.model} ({u_height})'
if device.asset_tag:
description += f'\nAsset tag: {device.asset_tag}'
if device.serial:
description += f'\nSerial: {device.serial}'
if device.description:
description += f'\nDescription: {device.description}'
return description
class RackElevationSVG:

View File

@@ -39,6 +39,10 @@ __all__ = (
'VirtualDeviceContextTable'
)
MODULEBAY_STATUS = """
{% badge record.installed_module.get_status_display bg_color=record.installed_module.get_status_color %}
"""
def get_cabletermination_row_class(record):
if record.mark_connected:
@@ -133,11 +137,11 @@ class PlatformTable(NetBoxTable):
class Meta(NetBoxTable.Meta):
model = models.Platform
fields = (
'pk', 'id', 'name', 'manufacturer', 'device_count', 'vm_count', 'slug', 'config_template', 'description',
'tags', 'actions', 'created', 'last_updated',
'pk', 'id', 'name', 'manufacturer', 'device_count', 'vm_count', 'slug', 'config_template', 'napalm_driver',
'napalm_args', 'description', 'tags', 'actions', 'created', 'last_updated',
)
default_columns = (
'pk', 'name', 'manufacturer', 'device_count', 'vm_count', 'description',
'pk', 'name', 'manufacturer', 'device_count', 'vm_count', 'napalm_driver', 'description',
)
@@ -781,14 +785,17 @@ class ModuleBayTable(DeviceComponentTable):
tags = columns.TagColumn(
url_name='dcim:modulebay_list'
)
module_status = columns.TemplateColumn(
template_code=MODULEBAY_STATUS
)
class Meta(DeviceComponentTable.Meta):
model = models.ModuleBay
fields = (
'pk', 'id', 'name', 'device', 'label', 'position', 'installed_module', 'module_serial', 'module_asset_tag',
'description', 'tags',
'pk', 'id', 'name', 'device', 'label', 'position', 'installed_module', 'module_status', 'module_serial',
'module_asset_tag', 'description', 'tags',
)
default_columns = ('pk', 'name', 'device', 'label', 'installed_module', 'description')
default_columns = ('pk', 'name', 'device', 'label', 'installed_module', 'module_status', 'description')
class DeviceModuleBayTable(ModuleBayTable):
@@ -799,10 +806,10 @@ class DeviceModuleBayTable(ModuleBayTable):
class Meta(DeviceComponentTable.Meta):
model = models.ModuleBay
fields = (
'pk', 'id', 'name', 'label', 'position', 'installed_module', 'module_serial', 'module_asset_tag',
'pk', 'id', 'name', 'label', 'position', 'installed_module', 'module_status', 'module_serial', 'module_asset_tag',
'description', 'tags', 'actions',
)
default_columns = ('pk', 'name', 'label', 'installed_module', 'description')
default_columns = ('pk', 'name', 'label', 'installed_module', 'module_status', 'description')
class InventoryItemTable(DeviceComponentTable):

View File

@@ -12,12 +12,12 @@ LINKTERMINATION = """
CABLE_LENGTH = """
{% load helpers %}
{% if record.length %}{{ record.length|simplify_decimal }} {{ record.length_unit }}{% endif %}
{% if record.length %}{{ record.length|floatformat:"-2" }} {{ record.length_unit }}{% endif %}
"""
WEIGHT = """
{% load helpers %}
{% if value %}{{ value|simplify_decimal }} {{ record.weight_unit }}{% endif %}
{% if value %}{{ value|floatformat:"-2" }} {{ record.weight_unit }}{% endif %}
"""
DEVICE_LINK = """

View File

@@ -1498,9 +1498,9 @@ class PlatformTestCase(TestCase, ChangeLoggedFilterSetTests):
Manufacturer.objects.bulk_create(manufacturers)
platforms = (
Platform(name='Platform 1', slug='platform-1', manufacturer=manufacturers[0], description='A'),
Platform(name='Platform 2', slug='platform-2', manufacturer=manufacturers[1], description='B'),
Platform(name='Platform 3', slug='platform-3', manufacturer=manufacturers[2], description='C'),
Platform(name='Platform 1', slug='platform-1', manufacturer=manufacturers[0], napalm_driver='driver-1', description='A'),
Platform(name='Platform 2', slug='platform-2', manufacturer=manufacturers[1], napalm_driver='driver-2', description='B'),
Platform(name='Platform 3', slug='platform-3', manufacturer=manufacturers[2], napalm_driver='driver-3', description='C'),
)
Platform.objects.bulk_create(platforms)
@@ -1516,6 +1516,10 @@ class PlatformTestCase(TestCase, ChangeLoggedFilterSetTests):
params = {'description': ['A', 'B']}
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
def test_napalm_driver(self):
params = {'napalm_driver': ['driver-1', 'driver-2']}
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
def test_manufacturer(self):
manufacturers = Manufacturer.objects.all()[:2]
params = {'manufacturer_id': [manufacturers[0].pk, manufacturers[1].pk]}

View File

@@ -1591,6 +1591,8 @@ class PlatformTestCase(ViewTestCases.OrganizationalObjectViewTestCase):
'name': 'Platform X',
'slug': 'platform-x',
'manufacturer': manufacturer.pk,
'napalm_driver': 'junos',
'napalm_args': None,
'description': 'A new platform',
'tags': [t.pk for t in tags],
}
@@ -1610,6 +1612,7 @@ class PlatformTestCase(ViewTestCases.OrganizationalObjectViewTestCase):
)
cls.bulk_edit_data = {
'napalm_driver': 'ios',
'description': 'New description',
}

View File

@@ -6,6 +6,7 @@ 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
@@ -370,7 +371,7 @@ class SiteView(generic.ObjectView):
(VLANGroup.objects.restrict(request.user, 'view').filter(
scope_type=ContentType.objects.get_for_model(Site),
scope_id=instance.pk
), 'site_id'),
), 'site'),
(VLAN.objects.restrict(request.user, 'view').filter(site=instance), 'site_id'),
# Circuits
(Circuit.objects.restrict(request.user, 'view').filter(terminations__site=instance).distinct(), 'site_id'),
@@ -578,6 +579,7 @@ class RackRoleBulkDeleteView(generic.BulkDeleteView):
queryset = RackRole.objects.annotate(
rack_count=count_related(Rack, 'role')
)
filterset = filtersets.RackRoleFilterSet
table = tables.RackRoleTable
@@ -685,6 +687,7 @@ class RackView(generic.ObjectView):
'next_rack': next_rack,
'prev_rack': prev_rack,
'svg_extra': svg_extra,
'peer_racks': peer_racks,
}
@@ -867,6 +870,7 @@ class ManufacturerBulkDeleteView(generic.BulkDeleteView):
inventoryitem_count=count_related(InventoryItem, 'manufacturer'),
platform_count=count_related(Platform, 'manufacturer')
)
filterset = filtersets.ManufacturerFilterSet
table = tables.ManufacturerTable
@@ -1728,6 +1732,7 @@ class DeviceRoleBulkDeleteView(generic.BulkDeleteView):
device_count=count_related(Device, 'device_role'),
vm_count=count_related(VirtualMachine, 'role')
)
filterset = filtersets.DeviceRoleFilterSet
table = tables.DeviceRoleTable
@@ -1785,6 +1790,7 @@ class PlatformBulkEditView(generic.BulkEditView):
class PlatformBulkDeleteView(generic.BulkDeleteView):
queryset = Platform.objects.all()
filterset = filtersets.PlatformFilterSet
table = tables.PlatformTable
@@ -2008,12 +2014,28 @@ class DeviceRenderConfigView(generic.ObjectView):
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'):
response = HttpResponse(context['rendered_config'], 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 = {
'device': instance,
}
context_data.update(**instance.get_config_context())
context_data = instance.get_config_context()
context_data.update({'device': instance})
# Render the config template
rendered_config = None
@@ -2855,6 +2877,7 @@ class InventoryItemBulkRenameView(generic.BulkRenameView):
class InventoryItemBulkDeleteView(generic.BulkDeleteView):
queryset = InventoryItem.objects.all()
filterset = filtersets.InventoryItemFilterSet
table = tables.InventoryItemTable
template_name = 'dcim/inventoryitem_bulk_delete.html'
@@ -2911,6 +2934,7 @@ class InventoryItemRoleBulkDeleteView(generic.BulkDeleteView):
queryset = InventoryItemRole.objects.annotate(
inventoryitem_count=count_related(InventoryItem, 'role'),
)
filterset = filtersets.InventoryItemRoleFilterSet
table = tables.InventoryItemRoleTable

View File

@@ -1,3 +1,4 @@
from jinja2.exceptions import TemplateError
from rest_framework.response import Response
from .nested_serializers import NestedConfigTemplateSerializer
@@ -32,7 +33,12 @@ class ConfigContextQuerySetMixin:
class ConfigTemplateRenderMixin:
def render_configtemplate(self, request, configtemplate, context):
output = configtemplate.render(context=context)
try:
output = configtemplate.render(context=context)
except TemplateError as e:
return Response({
'detail': f"An error occurred while rendering the template (line {e.lineno}): {e}"
}, status=500)
# If the client has requested "text/plain", return the raw content.
if request.accepted_renderer.format == 'txt':

View File

@@ -104,6 +104,12 @@ class CustomFieldSerializer(ValidatedModelSerializer):
'last_updated',
]
def validate_type(self, value):
if self.instance and self.instance.type != value:
raise serializers.ValidationError('Changing the type of custom fields is not supported.')
return value
@extend_schema_field(OpenApiTypes.STR)
def get_data_type(self, obj):
types = CustomFieldTypeChoices
@@ -437,6 +443,16 @@ class ReportInputSerializer(serializers.Serializer):
schedule_at = serializers.DateTimeField(required=False, allow_null=True)
interval = serializers.IntegerField(required=False, allow_null=True)
def validate_schedule_at(self, value):
if value and not self.context['report'].scheduling_enabled:
raise serializers.ValidationError("Scheduling is not enabled for this report.")
return value
def validate_interval(self, value):
if value and not self.context['report'].scheduling_enabled:
raise serializers.ValidationError("Scheduling is not enabled for this report.")
return value
#
# Scripts
@@ -472,6 +488,16 @@ class ScriptInputSerializer(serializers.Serializer):
schedule_at = serializers.DateTimeField(required=False, allow_null=True)
interval = serializers.IntegerField(required=False, allow_null=True)
def validate_schedule_at(self, value):
if value and not self.context['script'].scheduling_enabled:
raise serializers.ValidationError("Scheduling is not enabled for this script.")
return value
def validate_interval(self, value):
if value and not self.context['script'].scheduling_enabled:
raise serializers.ValidationError("Scheduling is not enabled for this script.")
return value
class ScriptLogMessageSerializer(serializers.Serializer):
status = serializers.SerializerMethodField(read_only=True)

View File

@@ -187,11 +187,10 @@ class ReportViewSet(ViewSet):
"""
Compile all reports and their related results (if any). Result data is deferred in the list view.
"""
report_content_type = ContentType.objects.get(app_label='extras', model='report')
results = {
r.name: r
for r in Job.objects.filter(
object_type=report_content_type,
job.name: job
for job in Job.objects.filter(
object_type=ContentType.objects.get(app_label='extras', model='reportmodule'),
status__in=JobStatusChoices.TERMINAL_STATE_CHOICES
).order_by('name', '-created').distinct('name').defer('data')
}
@@ -202,7 +201,7 @@ class ReportViewSet(ViewSet):
# Attach Job objects to each report (if any)
for report in report_list:
report.result = results.get(report.full_name, None)
report.result = results.get(report.name, None)
serializer = serializers.ReportSerializer(report_list, many=True, context={
'request': request,
@@ -244,8 +243,12 @@ class ReportViewSet(ViewSet):
raise RQWorkerNotRunningException()
# Retrieve and run the Report. This will create a new Job.
module, report = self._get_report(pk)
input_serializer = serializers.ReportInputSerializer(data=request.data)
module, report_cls = self._get_report(pk)
report = report_cls()
input_serializer = serializers.ReportInputSerializer(
data=request.data,
context={'report': report}
)
if input_serializer.is_valid():
report.result = Job.enqueue(
@@ -286,12 +289,10 @@ class ScriptViewSet(ViewSet):
return module, script
def list(self, request):
script_content_type = ContentType.objects.get(app_label='extras', model='script')
results = {
r.name: r
for r in Job.objects.filter(
object_type=script_content_type,
job.name: job
for job in Job.objects.filter(
object_type=ContentType.objects.get(app_label='extras', model='scriptmodule'),
status__in=JobStatusChoices.TERMINAL_STATE_CHOICES
).order_by('name', '-created').distinct('name').defer('data')
}
@@ -302,7 +303,7 @@ class ScriptViewSet(ViewSet):
# Attach Job objects to each script (if any)
for script in script_list:
script.result = results.get(script.full_name, None)
script.result = results.get(script.name, None)
serializer = serializers.ScriptSerializer(script_list, many=True, context={'request': request})
@@ -329,7 +330,10 @@ class ScriptViewSet(ViewSet):
raise PermissionDenied("This user does not have permission to run scripts.")
module, script = self._get_script(pk)
input_serializer = serializers.ScriptInputSerializer(data=request.data)
input_serializer = serializers.ScriptInputSerializer(
data=request.data,
context={'script': script}
)
# Check that at least one RQ worker is running
if not Worker.count(get_connection('default')):

View File

@@ -116,7 +116,7 @@ class JournalEntryKindChoices(ChoiceSet):
#
# Log Levels for Reports and Scripts
# Reports and Scripts
#
class LogLevelChoices(ChoiceSet):
@@ -136,6 +136,17 @@ class LogLevelChoices(ChoiceSet):
)
class DurationChoices(ChoiceSet):
CHOICES = (
(60, 'Hourly'),
(720, '12 hours'),
(1440, 'Daily'),
(10080, 'Weekly'),
(43200, '30 days'),
)
#
# Job results
#

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