Compare commits

..

101 Commits

Author SHA1 Message Date
Jeremy Stretch
b15ecf7649 Merge pull request #8123 from netbox-community/develop
Release v3.1.2
2021-12-20 16:04:41 -05:00
jeremystretch
df4f80e773 Release v3.1.2 2021-12-20 15:48:28 -05:00
jeremystretch
b8b485af4d Changelog & PEP8 cleanup for #7999 2021-12-20 14:17:52 -05:00
Jeremy Stretch
892d6b55ec Merge pull request #8000 from joni1993/more-channels
feat: add 6GHz & 60Ghz channels
2021-12-20 14:16:12 -05:00
Jeremy Stretch
4a3bc8d365 Merge pull request #8111 from bonktree/opaque-icon
templates: add an opaque icon for mobile home screens
2021-12-20 13:58:25 -05:00
jeremystretch
e12da72615 Fixes #8101: Preserve return URL when using "create and add another" button 2021-12-20 13:41:22 -05:00
jeremystretch
f95e510060 Fixes #8102: Raise validation error when attempting to assign an IP address to multiple objects 2021-12-20 13:09:28 -05:00
Daniel Sheppard
82932ae7a5 Fixes #8102 - Add validation around assigned objects 2021-12-20 11:07:44 -06:00
jeremystretch
14fc37a8b8 Closes #7661: Remove forced styling of custom banners 2021-12-19 15:33:48 -05:00
Arseny Maslennikov
7b23856cc8 templates: add an opaque icon for mobile home screens
The netbox_touch-icon-180.png icon was produced by rendering
netbox_icon.svg into a 160x160 square, centered in a 180x180 PNG filled
by the background colour of #212529.

In other words, it is a screenshot of the following HTML element:
```html
  <div style="width: 180px;height: 180px;background-color: #212529;">
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 320" style="padding: 10px;">
    <g fill="#9cc8f8" stroke="#9cc8f8">
      <circle cx="37" cy="284" r="23"></circle>
      <circle cx="101" cy="37" r="23"></circle>
      <circle cx="101" cy="220" r="23"></circle>
      <circle cx="284" cy="220" r="23"></circle>
      <rect x="93" y="37" width="16" height="180"></rect>
      <rect x="101" y="212" width="180" height="16"></rect>
      <rect x="93" y="212" width="16" height="90" transform="rotate(45 101 220)"></rect>
    </g>
    <g fill="#1685fc" stroke="#1685fc">
      <circle cx="284" cy="37" r="23"></circle>
      <circle cx="37" cy="101" r="23"></circle>
      <circle cx="220" cy="101" r="23"></circle>
      <circle cx="220" cy="284" r="23"></circle>
      <rect x="37" y="93" width="180" height="16"></rect>
      <rect x="212" y="101" width="16" height="180"></rect>
      <rect x="212" y="93" width="16" height="90" transform="rotate(225 220 101)"></rect>
    </g>
  </svg>
  </div>
```
2021-12-19 01:32:15 +03:00
jeremystretch
85f9690377 Closes #8083: Removed "related devices" panel from device view 2021-12-18 14:30:28 -05:00
jeremystretch
4723500c5f Fixes #8092: Rack elevations should not include device asset tags 2021-12-18 14:26:32 -05:00
jeremystretch
2db82a73a5 #8096: Include only first assigned IP in FHRPGroup string representation 2021-12-18 14:19:57 -05:00
jeremystretch
b00eeb86ea Fixes #8096: Fix DataError during change logging of objects with very long string representations 2021-12-18 14:16:37 -05:00
jeremystretch
628e186846 Closes #8108: Improve breadcrumb links for device/VM components 2021-12-18 14:02:01 -05:00
jeremystretch
cf4a55bc2f Closes #8107: Correct template name 2021-12-18 13:52:39 -05:00
Christian Jonak
cab07c7c4b fix: non 20Mhz-wide channel centers 2021-12-16 19:28:39 +01:00
jeremystretch
7735a539e9 Fixes #8088: Improve legibility of text in labels with light-colored backgrounds 2021-12-16 12:44:18 -05:00
Christian Jonak
68eb6fc3c1 fix: use center freq instead of beginning of freq range for 6Ghz 2021-12-16 18:14:56 +01:00
jeremystretch
fd785fc9a5 Move speed select dropdown menu to widget template 2021-12-16 08:41:43 -05:00
jeremystretch
8d06908353 Bulk component add view should use tabs 2021-12-15 16:57:30 -05:00
jeremystretch
806706ca1d Refresh development documentation 2021-12-15 16:31:06 -05:00
jeremystretch
044e203eab Standardize button colors 2021-12-15 12:16:50 -05:00
jeremystretch
fcc7207b67 Restore actions column under VM interfaces table 2021-12-15 12:11:20 -05:00
jeremystretch
8dbd3f332b Closes #8081: Allow creating services directly from navigation menu 2021-12-15 11:55:27 -05:00
jeremystretch
f43ec7c05d Add "add IP range" button to prefix IP ranges view 2021-12-15 11:03:38 -05:00
jeremystretch
ff9dde54e3 Ensure consistent placement of table paginator 2021-12-15 10:34:20 -05:00
jeremystretch
3699f16848 Show per-page selector only when results are present 2021-12-15 09:46:59 -05:00
jeremystretch
fee2ac2ebd Changelog for #8057 2021-12-15 09:36:52 -05:00
Jeremy Stretch
57d3bfcfc9 Merge pull request #8073 from netbox-community/8057-htmx-tables
Closes #8057: Dynamic object tables using HTMX
2021-12-15 09:16:41 -05:00
jeremystretch
b92e34556f Fixes #8077: Fix exception when attaching image to location, circuit, or power panel 2021-12-15 08:45:17 -05:00
jeremystretch
b6ff55309e Fixes #8078: Add missing wireless models to lsmodels() in nbshell 2021-12-15 08:38:19 -05:00
jeremystretch
305d88ebda Fixes #8079: Fix validation of LLDP neighbors when connected device has an asset tag 2021-12-15 08:36:03 -05:00
jeremystretch
cdc73d4f56 Closes #8080: Link to NAT IPs for device/VM primary IPs 2021-12-15 08:35:01 -05:00
jeremystretch
0e50c964d5 Remove obsolete pagination TS/CSS 2021-12-14 21:00:48 -05:00
jeremystretch
863fb9aa47 Sync HTMX and non-HTMX paginator styles 2021-12-14 20:53:24 -05:00
jeremystretch
298fb00a3e Remove obsolete "quick find" TS 2021-12-14 20:04:49 -05:00
jeremystretch
d1e8c06d36 Fixes #8074: Ordering VMs by name should reference naturalized value 2021-12-14 17:03:03 -05:00
jeremystretch
8ed79d5973 Remove obsolete templates 2021-12-14 16:44:03 -05:00
jeremystretch
85b10b59e4 Introduce child prefixes view for aggregates 2021-12-14 16:38:25 -05:00
jeremystretch
9a53c22833 Serve HTMX JS locally 2021-12-14 15:55:40 -05:00
jeremystretch
c981b5cba0 Add prep_table_data() method to ObjectChildrenView 2021-12-14 15:42:28 -05:00
jeremystretch
4ffa823ab8 Enable HTMX for all ObjectChildrenViews 2021-12-14 15:31:42 -05:00
Jeremy Stretch
001c7e4b18 Merge pull request #8070 from netbox-community/8069-generic-children-view
Closes #8069: Generic children view
2021-12-14 14:30:41 -05:00
jeremystretch
402136dc8f Merge branch '8069-generic-children-view' into 8057-htmx-tables 2021-12-14 14:21:08 -05:00
jeremystretch
59ee30f056 Update cluster VM/device views to use ObjectChildrenView 2021-12-14 14:08:44 -05:00
jeremystretch
c795068a78 Update VLAN member interface views to use ObjectChildrenView 2021-12-14 14:03:44 -05:00
jeremystretch
5ce080779b Update IPRange IP addresses view to use ObjectChildrenView 2021-12-14 13:55:09 -05:00
jeremystretch
8d3b296eed Update device/VM component views to use ObjectChildrenView 2021-12-14 13:47:40 -05:00
jeremystretch
cfdb985d00 Update prefix children views to use ObjectChildrenView 2021-12-14 13:33:53 -05:00
jeremystretch
af6f0db284 Introduce ObjectChildrenView 2021-12-14 13:33:36 -05:00
jeremystretch
491eac184e Enable HTMX for connections lists 2021-12-14 11:53:16 -05:00
jeremystretch
414d33eb26 Refactor HTMX table template 2021-12-14 11:41:39 -05:00
jeremystretch
6dd6094088 Push HTMX URL to browser location 2021-12-14 08:25:17 -05:00
jeremystretch
5c34a75032 Enable HTMX for quick table search 2021-12-13 20:15:03 -05:00
jeremystretch
91f33d3289 #8057: Enable dynamic tables for object list views 2021-12-13 16:51:59 -05:00
jeremystretch
c50dc1eb35 Standardize usage of table template 2021-12-13 15:36:51 -05:00
jeremystretch
dc1331e736 Fixes #7674: Fix inadvertent application of device type context to virtual machines 2021-12-13 13:42:59 -05:00
jeremystretch
afc866eee4 #7665: Refactored add_requested_prefixes(); removed button icons 2021-12-13 12:15:43 -05:00
jeremystretch
b6d93b7c5b Changelog for #7665 2021-12-13 12:10:03 -05:00
Jeremy Stretch
5d6158dd64 Merge pull request #7826 from WillIrvine/develop
Add filter for optionally including assigned prefixes
2021-12-13 12:04:38 -05:00
jeremystretch
e9549ab0bd PRVB 2021-12-13 09:16:55 -05:00
Jeremy Stretch
779249ff81 Merge pull request #8053 from netbox-community/develop
Release v3.1.1
2021-12-13 09:08:33 -05:00
jeremystretch
66d206a710 Release v3.1.1 2021-12-13 08:51:55 -05:00
jeremystretch
bfc1cab6df Fixes #8051: Contact group parent assignment should not be required under REST API 2021-12-13 08:22:48 -05:00
jeremystretch
5b0c79629e Closes #8047: Display sorting indicator in table column headers 2021-12-10 21:03:24 -05:00
jeremystretch
7922d3909a Fixes #8042: Fix filtering cables list by site slug or rack name 2021-12-10 16:41:03 -05:00
jeremystretch
ee6e2e0af1 Fixes #7690: Fix custom field integer support for MultiValueNumberFilter 2021-12-10 16:34:38 -05:00
jeremystretch
326a6be91c #7519: Update REST API tests 2021-12-10 15:45:22 -05:00
jeremystretch
58095e1916 Fixes #8038: Placeholder filter should display zero integer values 2021-12-10 15:38:51 -05:00
jeremystretch
3dae077b4d Fixes #8035: Redirect back to parent prefix after creating IP address(es) where applicable 2021-12-10 15:34:12 -05:00
jeremystretch
7c14c0812b Fixes #7519: Return a 409 status for unfulfillable available prefix/IP requests 2021-12-10 15:11:45 -05:00
Jeremy Stretch
3a05eda63a Merge pull request #8039 from netbox-community/5869-available-prefixes
Fixes #5869: Fix permissions evaluation under available prefix/IP REST API endpoints
2021-12-10 14:22:29 -05:00
jeremystretch
d850b3ac7e Fix available prefix creation test 2021-12-10 13:58:11 -05:00
jeremystretch
08de6c32c9 Changelog for #5869 2021-12-10 13:26:56 -05:00
jeremystretch
91fe158c26 Restore endpoint schema documentation 2021-12-10 13:23:49 -05:00
jeremystretch
661b3c4bfb Fix queryset restrictions 2021-12-10 12:52:48 -05:00
jeremystretch
35eabc0353 Move available IPs endpoints to separate views 2021-12-10 12:37:55 -05:00
jeremystretch
ef5bbdb1e2 Move available prefixes endpoint to its own view 2021-12-10 11:40:57 -05:00
jeremystretch
88fae2171d Closes #7691: Remove field_order from filterset forms 2021-12-10 08:57:19 -05:00
jeremystretch
de698154cd Fixes #8030: Validate custom field names 2021-12-09 15:19:19 -05:00
jeremystretch
1df05715c2 Fixes #8033: Fix display of zero values for custom integer fields in tables 2021-12-09 14:56:12 -05:00
jeremystretch
e5524da40e Fixes #8009: Validate IP addresses for uniqueness when creating an FHRP group 2021-12-09 13:46:19 -05:00
jeremystretch
50d393e0f9 Clean up user preferences view 2021-12-08 16:36:06 -05:00
jeremystretch
cd08836f3e Refresh user profile view; add recent activity 2021-12-08 16:32:31 -05:00
jeremystretch
45ac1cfd54 Fixes #8019: Exclude metrics endpoint when LOGIN_REQUIRED is true 2021-12-08 15:47:41 -05:00
jeremystretch
dda11ec69e Fixes #8003: Fix cable tracing across bridged interfaces with no cable 2021-12-08 11:35:50 -05:00
jeremystretch
7be6206d9d Fixes #8010: Allow filtering devices by multiple serial numbers 2021-12-08 11:08:19 -05:00
jeremystretch
4d896573b1 Fixes #8005: Fix contact email display 2021-12-08 11:04:03 -05:00
jeremystretch
988383648c Fixes #8001: Correct verbose name for wireless LAN group model 2021-12-08 10:45:27 -05:00
Daniel Sheppard
d59847537d Fix #7990 - Fix title display on contact view 2021-12-07 10:58:44 -06:00
jeremystretch
36859d89c8 Fixes #7996: Show WWN field in interface creation form 2021-12-07 10:59:08 -05:00
Christian Jonak-Möchel
cc50e22928 feat: add 6GHz & 60Ghz channels 2021-12-07 15:14:17 +01:00
William Irvine
13414dcd25 pep8 compliance... 2021-12-07 10:13:54 +13:00
jeremystretch
ba8b593351 PRVB 2021-12-06 16:13:48 -05:00
William Irvine
aebfccfd4b Merge branch 'develop' into develop 2021-12-07 10:06:35 +13:00
Will Irvine
ca07a88674 fix spelling... 2021-12-02 10:47:19 +13:00
Will Irvine
dcfd332cbf Moved filtering logic to utils, adjusted show buttons 2021-12-01 19:24:44 +13:00
Will Irvine
80048bfa2b Make the same changes for aggregate views as these use the same adjusted functions 2021-11-13 16:42:38 +13:00
Will Irvine
641a9bc6c5 pep8 compliance 2021-11-13 15:26:07 +13:00
Will Irvine
0edf9b17f6 Closes #7665 add new boolen for filtering assigned prefixes, adjust current filter for avaliabile prefixes to only return avaliable 2021-11-13 13:27:49 +13:00
162 changed files with 2369 additions and 1732 deletions

View File

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

View File

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

View File

@@ -1,6 +1,6 @@
# The Python web framework on which NetBox is built
# https://github.com/django/django
Django
Django<4.0
# Django middleware which permits cross-domain API requests
# https://github.com/OttoYiu/django-cors-headers

View File

@@ -6,9 +6,9 @@ Models within each app are stored in either `models.py` or within a submodule un
Each model should define, at a minimum:
* A `Meta` class specifying a deterministic ordering (if ordered by fields other than the primary ID)
* A `__str__()` method returning a user-friendly string representation of the instance
* A `get_absolute_url()` method returning an instance's direct URL (using `reverse()`)
* A `Meta` class specifying a deterministic ordering (if ordered by fields other than the primary ID)
## 2. Define field choices
@@ -16,9 +16,9 @@ If the model has one or more fields with static choices, define those choices in
## 3. Generate database migrations
Once your model definition is complete, generate database migrations by running `manage.py -n $NAME --no-header`. Always specify a short unique name when generating migrations.
Once your model definition is complete, generate database migrations by running `manage.py makemigrations -n $NAME --no-header`. Always specify a short unique name when generating migrations.
!!! info
!!! info "Configuration Required"
Set `DEVELOPER = True` in your NetBox configuration to enable the creation of new migrations.
## 4. Add all standard views
@@ -41,9 +41,7 @@ Add the relevant URL path for each view created in the previous step to `urls.py
Each model should have a corresponding FilterSet class defined. This is used to filter UI and API queries. Subclass the appropriate class from `netbox.filtersets` that matches the model's parent class.
Every model FilterSet should define a `q` filter to support general search queries.
## 7. Create the table
## 7. Create the table class
Create a table class for the model in `tables.py` by subclassing `utilities.tables.BaseTable`. Under the table's `Meta` class, be sure to list both the fields and default columns.
@@ -53,7 +51,7 @@ Create the HTML template for the object view. (The other views each typically em
## 9. Add the model to the navigation menu
For NetBox releases prior to v3.0, add the relevant link(s) to the navigation menu template. For later releases, add the relevant items in `netbox/netbox/navigation_menu.py`.
Add the relevant navigation menu items in `netbox/netbox/navigation_menu.py`.
## 10. REST API components
@@ -64,7 +62,7 @@ Create the following for each model:
* API view in `api/views.py`
* Endpoint route in `api/urls.py`
## 11. GraphQL API components (v3.0+)
## 11. GraphQL API components
Create a Graphene object type for the model in `graphql/types.py` by subclassing the appropriate class from `netbox.graphql.types`.

View File

@@ -4,16 +4,16 @@ Below is a list of tasks to consider when adding a new field to a core model.
## 1. Generate and run database migrations
Django migrations are used to express changes to the database schema. In most cases, Django can generate these automatically, however very complex changes may require manual intervention. Always remember to specify a short but descriptive name when generating a new migration.
[Django migrations](https://docs.djangoproject.com/en/stable/topics/migrations/) are used to express changes to the database schema. In most cases, Django can generate these automatically, however very complex changes may require manual intervention. Always remember to specify a short but descriptive name when generating a new migration.
```
./manage.py makemigrations <app> -n <name>
./manage.py migrate
```
Where possible, try to merge related changes into a single migration. For example, if three new fields are being added to different models within an app, these can be expressed in the same migration. You can merge a new migration with an existing one by combining their `operations` lists.
Where possible, try to merge related changes into a single migration. For example, if three new fields are being added to different models within an app, these can be expressed in a single migration. You can merge a newly generated migration with an existing one by combining their `operations` lists.
!!! note
!!! warning "Do not alter existing migrations"
Migrations can only be merged within a release. Once a new release has been published, its migrations cannot be altered (other than for the purpose of correcting a bug).
## 2. Add validation logic to `clean()`
@@ -24,7 +24,6 @@ If the new field introduces additional validation requirements (beyond what's in
class Foo(models.Model):
def clean(self):
super().clean()
# Custom validation goes here
@@ -40,9 +39,9 @@ If you're adding a relational field (e.g. `ForeignKey`) and intend to include th
Extend the model's API serializer in `<app>.api.serializers` to include the new field. In most cases, it will not be necessary to also extend the nested serializer, which produces a minimal representation of the model.
## 5. Add field to forms
## 5. Add fields to forms
Extend any forms to include the new field as appropriate. Common forms include:
Extend any forms to include the new field(s) as appropriate. These are found under the `forms/` directory within each app. Common forms include:
* **Credit/edit** - Manipulating a single object
* **Bulk edit** - Performing a change on many objects at once
@@ -51,11 +50,11 @@ Extend any forms to include the new field as appropriate. Common forms include:
## 6. Extend object filter set
If the new field should be filterable, add it to the `FilterSet` for the model. If the field should be searchable, remember to reference it in the FilterSet's `search()` method.
If the new field should be filterable, add it to the `FilterSet` for the model. If the field should be searchable, remember to query it in the FilterSet's `search()` method.
## 7. Add column to object table
If the new field will be included in the object list view, add a column to the model's table. For simple fields, adding the field name to `Meta.fields` will be sufficient. More complex fields may require declaring a custom column.
If the new field will be included in the object list view, add a column to the model's table. For simple fields, adding the field name to `Meta.fields` will be sufficient. More complex fields may require declaring a custom column. Also add the field name to `default_columns` if the column should be present in the table by default.
## 8. Update the UI templates

View File

@@ -35,6 +35,8 @@ The NetBox project utilizes three persistent git branches to track work:
Typically, you'll base pull requests off of the `develop` branch, or off of `feature` if you're working on a new major release. **Never** merge pull requests into the `master` branch, which receives merged only from the `develop` branch.
For example, assume that the current NetBox release is v3.1.1. Work applied to the `develop` branch will appear in v3.1.2, and work done under the `feature` branch will be included in the next minor release (v3.2.0).
### Enable Pre-Commit Hooks
NetBox ships with a [git pre-commit hook](https://githooks.com/) script that automatically checks for style compliance and missing database migrations prior to committing changes. This helps avoid erroneous commits that result in CI test failures. You are encouraged to enable it by creating a link to `scripts/git-hooks/pre-commit`:
@@ -46,7 +48,7 @@ $ ln -s ../../scripts/git-hooks/pre-commit
### Create a Python Virtual Environment
A [virtual environment](https://docs.python.org/3/tutorial/venv.html) is like a container for a set of Python packages. They allow you to build environments suited to specific projects without interfering with system packages or other projects. When installed per the documentation, NetBox uses a virtual environment in production.
A [virtual environment](https://docs.python.org/3/tutorial/venv.html) (or "venv" for short) is like a container for a set of Python packages. These allow you to build environments suited to specific projects without interfering with system packages or other projects. When installed per the documentation, NetBox uses a virtual environment in production.
Create a virtual environment using the `venv` Python module:
@@ -57,8 +59,8 @@ $ python3 -m venv ~/.venv/netbox
This will create a directory named `.venv/netbox/` in your home directory, which houses a virtual copy of the Python executable and its related libraries and tooling. When running NetBox for development, it will be run using the Python binary at `~/.venv/netbox/bin/python`.
!!! info
Keeping virtual environments in `~/.venv/` is a common convention but entirely optional: Virtual environments can be created wherever you please.
!!! info "Where to Create Your Virtual Environments"
Keeping virtual environments in `~/.venv/` is a common convention but entirely optional: Virtual environments can be created almost wherever you please.
Once created, activate the virtual environment:
@@ -94,7 +96,7 @@ Within the `netbox/netbox/` directory, copy `configuration.example.py` to `confi
### Start the Development Server
Django provides a lightweight, auto-updating HTTP/WSGI server for development use. NetBox extends this slightly to automatically import models and other utilities. Run the NetBox development server with the `nbshell` management command:
Django provides a lightweight, auto-updating HTTP/WSGI server for development use. It is started with the `runserver` management command:
```no-highlight
$ python netbox/manage.py runserver
@@ -109,9 +111,12 @@ Quit the server with CONTROL-C.
This ensures that your development environment is now complete and operational. Any changes you make to the code base will be automatically adapted by the development server.
!!! info "IDE Integration"
Some IDEs, such as PyCharm, will integrate with Django's development server and allow you to run it directly within the IDE. This is strongly encouraged as it makes for a much more convenient development environment.
## Running Tests
Throughout the course of development, it's a good idea to occasionally run NetBox's test suite to catch any potential errors. Tests are run using the `test` management command:
Prior to committing any substantial changes to the code base, be sure to run NetBox's test suite to catch any potential errors. Tests are run using the `test` management command. Remember to ensure the Python virtual environment is active before running this command.
```no-highlight
$ python netbox/manage.py test
@@ -123,9 +128,15 @@ In cases where you haven't made any changes to the database (which is most of th
$ python netbox/manage.py test --keepdb
```
You can also limit the command to running only a specific subset of tests. For example, to run only IPAM and DCIM view tests:
```no-highlight
$ python netbox/manage.py test dcim.tests.test_views ipam.tests.test_views
```
## Submitting Pull Requests
Once you're happy with your work and have verified that all tests pass, commit your changes and push it upstream to your fork. Always provide descriptive (but not excessively verbose) commit messages. When working on a specific issue, be sure to reference it.
Once you're happy with your work and have verified that all tests pass, commit your changes and push it upstream to your fork. Always provide descriptive (but not excessively verbose) commit messages. When working on a specific issue, be sure to prefix your commit message with the word "Fixes" or "Closes" and the issue number (with a hash mark). This tells GitHub to automatically close the referenced issue once the commit has been merged.
```no-highlight
$ git commit -m "Closes #1234: Add IPv5 support"
@@ -136,5 +147,5 @@ Once your fork has the new commit, submit a [pull request](https://github.com/ne
Once submitted, a maintainer will review your pull request and either merge it or request changes. If changes are needed, you can make them via new commits to your fork: The pull request will update automatically.
!!! note
Remember, pull requests are entertained only for **accepted** issues. If an issue you want to work on hasn't been approved by a maintainer yet, it's best to avoid risking your time and effort on a change that might not be accepted.
!!! note "Remember to Open an Issue First"
Remember, pull requests are permitted only for **accepted** issues. If an issue you want to work on hasn't been approved by a maintainer yet, it's best to avoid risking your time and effort on a change that might not be accepted. (The one exception to this is trivial changes to the documentation or other non-critical resources.)

View File

@@ -1,25 +1,25 @@
# NetBox Development
NetBox is maintained as a [GitHub project](https://github.com/netbox-community/netbox) under the Apache 2 license. Users are encouraged to submit GitHub issues for feature requests and bug reports, however we are very selective about pull requests. Please see the `CONTRIBUTING` guide for more direction on contributing to NetBox.
NetBox is maintained as a [GitHub project](https://github.com/netbox-community/netbox) under the Apache 2 license. Users are encouraged to submit GitHub issues for feature requests and bug reports, however we are very selective about pull requests. Each pull request must be preceded by an **approved** issue. Please see the `CONTRIBUTING` guide for more direction on contributing to NetBox.
## Communication
There are several official forums for communication among the developers and community members:
* [GitHub issues](https://github.com/netbox-community/netbox/issues) - All feature requests, bug reports, and other substantial changes to the code base **must** be documented in an issue.
* [GitHub issues](https://github.com/netbox-community/netbox/issues) - All feature requests, bug reports, and other substantial changes to the code base **must** be documented in a GitHub issue.
* [GitHub Discussions](https://github.com/netbox-community/netbox/discussions) - The preferred forum for general discussion and support issues. Ideal for shaping a feature request prior to submitting an issue.
* [#netbox on NetDev Community Slack](https://netdev.chat/) - Good for quick chats. Avoid any discussion that might need to be referenced later on, as the chat history is not retained long.
* [Google Group](https://groups.google.com/g/netbox-discuss) - Legacy mailing list; slowly being phased out in favor of GitHub discussions.
## Governance
NetBox follows the [benevolent dictator](http://oss-watch.ac.uk/resources/benevolentdictatorgovernancemodel) model of governance, with [Jeremy Stretch](https://github.com/jeremystretch) ultimately responsible for all changes to the code base. While community contributions are welcomed and encouraged, the lead maintainer's primary role is to ensure the project's long-term maintainability and continued focus on its primary functions (in other words, avoid scope creep).
NetBox follows the [benevolent dictator](http://oss-watch.ac.uk/resources/benevolentdictatorgovernancemodel) model of governance, with [Jeremy Stretch](https://github.com/jeremystretch) ultimately responsible for all changes to the code base. While community contributions are welcomed and encouraged, the lead maintainer's primary role is to ensure the project's long-term maintainability and continued focus on its primary functions.
## Project Structure
All development of the current NetBox release occurs in the `develop` branch; releases are packaged from the `master` branch. The `master` branch should _always_ represent the current stable release in its entirety, such that installing NetBox by either downloading a packaged release or cloning the `master` branch provides the same code base.
All development of the current NetBox release occurs in the `develop` branch; releases are packaged from the `master` branch. The `master` branch should _always_ represent the current stable release in its entirety, such that installing NetBox by either downloading a packaged release or cloning the `master` branch provides the same code base. Only pull requests representing new releases should be merged into `master`.
NetBox components are arranged into functional subsections called _apps_ (a carryover from Django vernacular). Each app holds the models, views, and templates relevant to a particular function:
NetBox components are arranged into Django apps. Each app holds the models, views, and other resources relevant to a particular function:
* `circuits`: Communications circuits and providers (not to be confused with power circuits)
* `dcim`: Datacenter infrastructure management (sites, racks, and devices)
@@ -29,3 +29,6 @@ NetBox components are arranged into functional subsections called _apps_ (a carr
* `users`: Authentication and user preferences
* `utilities`: Resources which are not user-facing (extendable classes, etc.)
* `virtualization`: Virtual machines and clusters
* `wireless`: Wireless links and LANs
All core functionality is stored within the `netbox/` subdirectory. HTML templates are stored in a common `templates/` directory, with model- and view-specific templates arranged by app. Documentation is kept in the `docs/` root directory.

View File

@@ -17,12 +17,12 @@ The Django [content types](https://docs.djangoproject.com/en/stable/ref/contrib/
* Nesting - These models can be nested recursively to create a hierarchy
| Type | Change Logging | Webhooks | Custom Fields | Export Templates | Tags | Journaling | Nesting |
| ------------------ | ---------------- | ---------------- | ---------------- | ---------------- | ---------------- | ---------------- | ---------------- |
| ------------------ | ---------------- | ---------------- |------------------| ---------------- | ---------------- | ---------------- | ---------------- |
| Primary | :material-check: | :material-check: | :material-check: | :material-check: | :material-check: | :material-check: | |
| Organizational | :material-check: | :material-check: | :material-check: | :material-check: | :material-check: | | |
| Nested Group | :material-check: | :material-check: | :material-check: | :material-check: | :material-check: | | :material-check: |
| Component | :material-check: | :material-check: | :material-check: | :material-check: | :material-check: | | |
| Component Template | :material-check: | :material-check: | :material-check: | | | | |
| Component Template | :material-check: | :material-check: | | | | | |
## Models Index
@@ -44,6 +44,7 @@ The Django [content types](https://docs.djangoproject.com/en/stable/ref/contrib/
* [ipam.ASN](../models/ipam/asn.md)
* [ipam.FHRPGroup](../models/ipam/fhrpgroup.md)
* [ipam.IPAddress](../models/ipam/ipaddress.md)
* [ipam.IPRange](../models/ipam/iprange.md)
* [ipam.Prefix](../models/ipam/prefix.md)
* [ipam.RouteTarget](../models/ipam/routetarget.md)
* [ipam.Service](../models/ipam/service.md)

View File

@@ -1,6 +1,6 @@
# Style Guide
NetBox generally follows the [Django style guide](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/coding-style/), which is itself based on [PEP 8](https://www.python.org/dev/peps/pep-0008/). [Pycodestyle](https://github.com/pycqa/pycodestyle) is used to validate code formatting, ignoring certain violations. See `scripts/cibuild.sh`.
NetBox generally follows the [Django style guide](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/coding-style/), which is itself based on [PEP 8](https://www.python.org/dev/peps/pep-0008/). [Pycodestyle](https://github.com/pycqa/pycodestyle) is used to validate code formatting, ignoring certain violations. See `scripts/cibuild.sh` for details.
## PEP 8 Exceptions
@@ -30,7 +30,7 @@ pycodestyle --ignore=W504,E501 netbox/
## Introducing New Dependencies
The introduction of a new dependency is best avoided unless it is absolutely necessary. For small features, it's generally preferable to replicate functionality within the NetBox code base rather than to introduce reliance on an external project. This reduces both the burden of tracking new releases and our exposure to outside bugs and attacks.
The introduction of a new dependency is best avoided unless it is absolutely necessary. For small features, it's generally preferable to replicate functionality within the NetBox code base rather than to introduce reliance on an external project. This reduces both the burden of tracking new releases and our exposure to outside bugs and supply chain attacks.
If there's a strong case for introducing a new dependency, it must meet the following criteria:
@@ -43,7 +43,7 @@ When adding a new dependency, a short description of the package and the URL of
## General Guidance
* When in doubt, remain consistent: It is better to be consistently incorrect than inconsistently correct. If you notice in the course of unrelated work a pattern that should be corrected, continue to follow the pattern for now and open a bug so that the entire code base can be evaluated at a later point.
* When in doubt, remain consistent: It is better to be consistently incorrect than inconsistently correct. If you notice in the course of unrelated work a pattern that should be corrected, continue to follow the pattern for now and submit a separate bug report so that the entire code base can be evaluated at a later point.
* Prioritize readability over concision. Python is a very flexible language that typically offers several options for expressing a given piece of logic, but some may be more friendly to the reader than others. (List comprehensions are particularly vulnerable to over-optimization.) Always remain considerate of the future reader who may need to interpret your code without the benefit of the context within which you are writing it.

View File

@@ -20,7 +20,7 @@ Custom fields may be created by navigating to Customization > Custom Fields. Net
* Selection: A selection of one of several pre-defined custom choices
* Multiple selection: A selection field which supports the assignment of multiple values
Each custom field must have a name; this should be a simple database-friendly string, e.g. `tps_report`. You may also assign a corresponding human-friendly label (e.g. "TPS report"); the label will be displayed on web forms. A weight is also required: Higher-weight fields will be ordered lower within a form. (The default weight is 100.) If a description is provided, it will appear beneath the field in a form.
Each custom field must have a name. This should be a simple database-friendly string (e.g. `tps_report`) and may contain only alphanumeric characters and underscores. You may also assign a corresponding human-friendly label (e.g. "TPS report"); the label will be displayed on web forms. A weight is also required: Higher-weight fields will be ordered lower within a form. (The default weight is 100.) If a description is provided, it will appear beneath the field in a form.
Marking a field as required will force the user to provide a value for the field when creating a new object or when saving an existing object. A default value for the field may also be provided. Use "true" or "false" for boolean fields, or the exact value of a choice for selection fields.

View File

@@ -1,5 +1,61 @@
# NetBox v3.1
## v3.1.2 (2021-12-20)
### Enhancements
* [#7661](https://github.com/netbox-community/netbox/issues/7661) - Remove forced styling of custom banners
* [#7665](https://github.com/netbox-community/netbox/issues/7665) - Add toggle to show only available child prefixes
* [#7999](https://github.com/netbox-community/netbox/issues/7999) - Add 6 GHz and 60 GHz wireless channels
* [#8057](https://github.com/netbox-community/netbox/issues/8057) - Dynamic object tables using HTMX
* [#8080](https://github.com/netbox-community/netbox/issues/8080) - Link to NAT IPs for device/VM primary IPs
* [#8081](https://github.com/netbox-community/netbox/issues/8081) - Allow creating services directly from navigation menu
* [#8083](https://github.com/netbox-community/netbox/issues/8083) - Removed "related devices" panel from device view
* [#8108](https://github.com/netbox-community/netbox/issues/8108) - Improve breadcrumb links for device/VM components
### Bug Fixes
* [#7674](https://github.com/netbox-community/netbox/issues/7674) - Fix inadvertent application of device type context to virtual machines
* [#8074](https://github.com/netbox-community/netbox/issues/8074) - Ordering VMs by name should reference naturalized value
* [#8077](https://github.com/netbox-community/netbox/issues/8077) - Fix exception when attaching image to location, circuit, or power panel
* [#8078](https://github.com/netbox-community/netbox/issues/8078) - Add missing wireless models to `lsmodels()` in `nbshell`
* [#8079](https://github.com/netbox-community/netbox/issues/8079) - Fix validation of LLDP neighbors when connected device has an asset tag
* [#8088](https://github.com/netbox-community/netbox/issues/8088) - Improve legibility of text in labels with light-colored backgrounds
* [#8092](https://github.com/netbox-community/netbox/issues/8092) - Rack elevations should not include device asset tags
* [#8096](https://github.com/netbox-community/netbox/issues/8096) - Fix DataError during change logging of objects with very long string representations
* [#8101](https://github.com/netbox-community/netbox/issues/8101) - Preserve return URL when using "create and add another" button
* [#8102](https://github.com/netbox-community/netbox/issues/8102) - Raise validation error when attempting to assign an IP address to multiple objects
---
## v3.1.1 (2021-12-13)
### Enhancements
* [#8047](https://github.com/netbox-community/netbox/issues/8047) - Display sorting indicator in table column headers
### Bug Fixes
* [#5869](https://github.com/netbox-community/netbox/issues/5869) - Fix permissions evaluation under available prefix/IP REST API endpoints
* [#7519](https://github.com/netbox-community/netbox/issues/7519) - Return a 409 status for unfulfillable available prefix/IP requests
* [#7690](https://github.com/netbox-community/netbox/issues/7690) - Fix custom field integer support for MultiValueNumberFilter
* [#7990](https://github.com/netbox-community/netbox/issues/7990) - Fix `title` display on contact detail view
* [#7996](https://github.com/netbox-community/netbox/issues/7996) - Show WWN field in interface creation form
* [#8001](https://github.com/netbox-community/netbox/issues/8001) - Correct verbose name for wireless LAN group model
* [#8003](https://github.com/netbox-community/netbox/issues/8003) - Fix cable tracing across bridged interfaces with no cable
* [#8005](https://github.com/netbox-community/netbox/issues/8005) - Fix contact email display
* [#8009](https://github.com/netbox-community/netbox/issues/8009) - Validate IP addresses for uniqueness when creating an FHRP group
* [#8010](https://github.com/netbox-community/netbox/issues/8010) - Allow filtering devices by multiple serial numbers
* [#8019](https://github.com/netbox-community/netbox/issues/8019) - Exclude metrics endpoint when `LOGIN_REQUIRED` is true
* [#8030](https://github.com/netbox-community/netbox/issues/8030) - Validate custom field names
* [#8033](https://github.com/netbox-community/netbox/issues/8033) - Fix display of zero values for custom integer fields in tables
* [#8035](https://github.com/netbox-community/netbox/issues/8035) - Redirect back to parent prefix after creating IP address(es) where applicable
* [#8038](https://github.com/netbox-community/netbox/issues/8038) - Placeholder filter should display zero integer values
* [#8042](https://github.com/netbox-community/netbox/issues/8042) - Fix filtering cables list by site slug or rack name
* [#8051](https://github.com/netbox-community/netbox/issues/8051) - Contact group parent assignment should not be required under REST API
---
## v3.1.0 (2021-12-06)
!!! warning "PostgreSQL 10 Required"

View File

@@ -718,7 +718,7 @@ class DeviceFilterSet(PrimaryModelFilterSet, TenancyFilterSet, LocalConfigContex
field_name='interfaces__mac_address',
label='MAC address',
)
serial = django_filters.CharFilter(
serial = MultiValueCharFilter(
lookup_expr='iexact'
)
has_primary_ip = django_filters.BooleanFilter(
@@ -1258,7 +1258,7 @@ class CableFilterSet(TenancyFilterSet, PrimaryModelFilterSet):
method='filter_device',
field_name='device__rack_id'
)
rack = MultiValueNumberFilter(
rack = MultiValueCharFilter(
method='filter_device',
field_name='device__rack__name'
)
@@ -1266,7 +1266,7 @@ class CableFilterSet(TenancyFilterSet, PrimaryModelFilterSet):
method='filter_device',
field_name='device__site_id'
)
site = MultiValueNumberFilter(
site = MultiValueCharFilter(
method='filter_device',
field_name='device__site__slug'
)

View File

@@ -48,9 +48,6 @@ __all__ = (
class DeviceComponentFilterForm(CustomFieldModelFilterForm):
field_order = [
'q', 'name', 'label', 'region_id', 'site_group_id', 'site_id',
]
name = forms.CharField(
required=False
)
@@ -131,7 +128,6 @@ class SiteGroupFilterForm(CustomFieldModelFilterForm):
class SiteFilterForm(TenancyFilterForm, CustomFieldModelFilterForm):
model = Site
field_order = ['q', 'status', 'region_id', 'tenant_group_id', 'tenant_id', 'asn_id']
field_groups = [
['q', 'tag'],
['status', 'region_id', 'group_id'],
@@ -213,7 +209,6 @@ class RackRoleFilterForm(CustomFieldModelFilterForm):
class RackFilterForm(TenancyFilterForm, CustomFieldModelFilterForm):
model = Rack
field_order = ['q', 'region_id', 'site_id', 'location_id', 'status', 'role_id', 'tenant_group_id', 'tenant_id']
field_groups = [
['q', 'tag'],
['region_id', 'site_id', 'location_id'],
@@ -278,10 +273,6 @@ class RackFilterForm(TenancyFilterForm, CustomFieldModelFilterForm):
class RackElevationFilterForm(RackFilterForm):
field_order = [
'q', 'region_id', 'site_id', 'location_id', 'id', 'status', 'role_id', 'tenant_group_id',
'tenant_id',
]
id = DynamicModelMultipleChoiceField(
queryset=Rack.objects.all(),
label=_('Rack'),
@@ -296,7 +287,6 @@ class RackElevationFilterForm(RackFilterForm):
class RackReservationFilterForm(TenancyFilterForm, CustomFieldModelFilterForm):
model = RackReservation
field_order = ['q', 'region_id', 'site_id', 'location_id', 'user_id', 'tenant_group_id', 'tenant_id']
field_groups = [
['q', 'tag'],
['user_id'],
@@ -428,10 +418,6 @@ class PlatformFilterForm(CustomFieldModelFilterForm):
class DeviceFilterForm(LocalConfigContextFilterForm, TenancyFilterForm, CustomFieldModelFilterForm):
model = Device
field_order = [
'q', 'region_id', 'site_group_id', 'site_id', 'location_id', 'rack_id', 'status', 'role_id', 'tenant_group_id',
'tenant_id', 'manufacturer_id', 'device_type_id', 'asset_tag', 'mac_address', 'has_primary_ip',
]
field_groups = [
['q', 'tag'],
['region_id', 'site_group_id', 'site_id', 'location_id', 'rack_id'],
@@ -595,7 +581,6 @@ class DeviceFilterForm(LocalConfigContextFilterForm, TenancyFilterForm, CustomFi
class VirtualChassisFilterForm(TenancyFilterForm, CustomFieldModelFilterForm):
model = VirtualChassis
field_order = ['q', 'region_id', 'site_group_id', 'site_id', 'tenant_group_id', 'tenant_id']
field_groups = [
['q', 'tag'],
['region_id', 'site_group_id', 'site_id'],

View File

@@ -465,12 +465,17 @@ class InterfaceCreateForm(ComponentCreateForm, InterfaceCommonForm):
query_params={
'device_id': '$device',
'type': 'lag',
}
},
label='LAG'
)
mac_address = forms.CharField(
required=False,
label='MAC Address'
)
wwn = forms.CharField(
required=False,
label='WWN'
)
mgmt_only = forms.BooleanField(
required=False,
label='Management only',
@@ -503,15 +508,17 @@ class InterfaceCreateForm(ComponentCreateForm, InterfaceCommonForm):
)
untagged_vlan = DynamicModelChoiceField(
queryset=VLAN.objects.all(),
required=False
required=False,
label='Untagged VLAN'
)
tagged_vlans = DynamicModelMultipleChoiceField(
queryset=VLAN.objects.all(),
required=False
required=False,
label='Tagged VLANs'
)
field_order = (
'device', 'name_pattern', 'label_pattern', 'type', 'enabled', 'parent', 'bridge', 'lag', 'mtu', 'mac_address',
'description', 'mgmt_only', 'mark_connected', 'rf_role', 'rf_channel', 'rf_channel_frequency',
'wwn', 'description', 'mgmt_only', 'mark_connected', 'rf_role', 'rf_channel', 'rf_channel_frequency',
'rf_channel_width', 'mode', 'untagged_vlan', 'tagged_vlans', 'tags'
)

View File

@@ -193,7 +193,7 @@ class PathEndpoint(models.Model):
while origin is not None:
if origin._path is None:
return path
break
path.extend([origin, *origin._path.get_path()])
while (len(path) + 1) % 3:

View File

@@ -18,6 +18,10 @@ __all__ = (
)
def get_device_name(device):
return device.name or str(device.device_type)
class RackElevationSVG:
"""
Use this class to render a rack elevation as an SVG image.
@@ -85,7 +89,7 @@ class RackElevationSVG:
return drawing
def _draw_device_front(self, drawing, device, start, end, text):
name = str(device)
name = get_device_name(device)
if device.devicebay_count:
name += ' ({}/{})'.format(device.get_children().count(), device.devicebay_count)
@@ -120,7 +124,7 @@ class RackElevationSVG:
rect = drawing.rect(start, end, class_="slot blocked")
rect.set_desc(self._get_device_description(device))
drawing.add(rect)
drawing.add(drawing.text(str(device), insert=text))
drawing.add(drawing.text(get_device_name(device), insert=text))
# Embed rear device type image if one exists
if self.include_images and device.device_type.rear_image:
@@ -132,9 +136,9 @@ class RackElevationSVG:
)
image.fit(scale='slice')
drawing.add(image)
drawing.add(drawing.text(str(device), insert=text, stroke='black',
drawing.add(drawing.text(get_device_name(device), insert=text, stroke='black',
stroke_width='0.2em', stroke_linejoin='round', class_='device-image-label'))
drawing.add(drawing.text(str(device), insert=text, fill='white', class_='device-image-label'))
drawing.add(drawing.text(get_device_name(device), insert=text, fill='white', class_='device-image-label'))
@staticmethod
def _draw_empty(drawing, rack, start, end, text, id_, face_id, class_, reservation):

View File

@@ -1420,10 +1420,10 @@ class DeviceTestCase(TestCase, ChangeLoggedFilterSetTests):
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
def test_serial(self):
params = {'serial': 'ABC'}
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
params = {'serial': 'abc'}
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
params = {'serial': ['ABC', 'DEF']}
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
params = {'serial': ['abc', 'def']}
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
def test_has_primary_ip(self):
params = {'has_primary_ip': 'true'}

View File

@@ -1,7 +1,6 @@
from django.urls import path
from extras.views import ObjectChangeLogView, ObjectJournalView
from ipam.views import ServiceEditView
from utilities.views import SlugRedirectView
from . import views
from .models import *
@@ -233,7 +232,6 @@ urlpatterns = [
path('devices/<int:pk>/status/', views.DeviceStatusView.as_view(), name='device_status'),
path('devices/<int:pk>/lldp-neighbors/', views.DeviceLLDPNeighborsView.as_view(), name='device_lldp_neighbors'),
path('devices/<int:pk>/config/', views.DeviceConfigView.as_view(), name='device_config'),
path('devices/<int:device>/services/assign/', ServiceEditView.as_view(), name='device_service_assign'),
# Console ports
path('console-ports/', views.ConsolePortListView.as_view(), name='consoleport_list'),

View File

@@ -36,26 +36,15 @@ from .models import (
)
class DeviceComponentsView(generic.ObjectView):
class DeviceComponentsView(generic.ObjectChildrenView):
queryset = Device.objects.all()
model = None
table = None
def get_components(self, request, instance):
return self.model.objects.restrict(request.user, 'view').filter(device=instance)
def get_children(self, request, parent):
return self.child_model.objects.restrict(request.user, 'view').filter(device=parent)
def get_extra_context(self, request, instance):
components = self.get_components(request, instance)
table = self.table(data=components, user=request.user)
change_perm = f'{self.model._meta.app_label}.change_{self.model._meta.model_name}'
delete_perm = f'{self.model._meta.app_label}.delete_{self.model._meta.model_name}'
if request.user.has_perm(change_perm) or request.user.has_perm(delete_perm):
table.columns.show('pk')
paginate_table(table, request)
return {
'table': table,
'active_tab': f"{self.model._meta.verbose_name_plural.replace(' ', '-')}",
'active_tab': f"{self.child_model._meta.verbose_name_plural.replace(' ', '-')}",
}
@@ -63,8 +52,8 @@ class DeviceTypeComponentsView(DeviceComponentsView):
queryset = DeviceType.objects.all()
template_name = 'dcim/devicetype/component_templates.html'
def get_components(self, request, instance):
return self.model.objects.restrict(request.user, 'view').filter(device_type=instance)
def get_children(self, request, parent):
return self.child_model.objects.restrict(request.user, 'view').filter(device_type=parent)
class BulkDisconnectView(GetReturnURLMixin, ObjectPermissionRequiredMixin, View):
@@ -806,43 +795,51 @@ class DeviceTypeView(generic.ObjectView):
class DeviceTypeConsolePortsView(DeviceTypeComponentsView):
model = ConsolePortTemplate
child_model = ConsolePortTemplate
table = tables.ConsolePortTemplateTable
filterset = filtersets.ConsolePortTemplateFilterSet
class DeviceTypeConsoleServerPortsView(DeviceTypeComponentsView):
model = ConsoleServerPortTemplate
child_model = ConsoleServerPortTemplate
table = tables.ConsoleServerPortTemplateTable
filterset = filtersets.ConsoleServerPortTemplateFilterSet
class DeviceTypePowerPortsView(DeviceTypeComponentsView):
model = PowerPortTemplate
child_model = PowerPortTemplate
table = tables.PowerPortTemplateTable
filterset = filtersets.PowerPortTemplateFilterSet
class DeviceTypePowerOutletsView(DeviceTypeComponentsView):
model = PowerOutletTemplate
child_model = PowerOutletTemplate
table = tables.PowerOutletTemplateTable
filterset = filtersets.PowerOutletTemplateFilterSet
class DeviceTypeInterfacesView(DeviceTypeComponentsView):
model = InterfaceTemplate
child_model = InterfaceTemplate
table = tables.InterfaceTemplateTable
filterset = filtersets.InterfaceTemplateFilterSet
class DeviceTypeFrontPortsView(DeviceTypeComponentsView):
model = FrontPortTemplate
child_model = FrontPortTemplate
table = tables.FrontPortTemplateTable
filterset = filtersets.FrontPortTemplateFilterSet
class DeviceTypeRearPortsView(DeviceTypeComponentsView):
model = RearPortTemplate
child_model = RearPortTemplate
table = tables.RearPortTemplateTable
filterset = filtersets.RearPortTemplateFilterSet
class DeviceTypeDeviceBaysView(DeviceTypeComponentsView):
model = DeviceBayTemplate
child_model = DeviceBayTemplate
table = tables.DeviceBayTemplateTable
filterset = filtersets.DeviceBayTemplateFilterSet
class DeviceTypeEditView(generic.ObjectEditView):
@@ -1319,80 +1316,79 @@ class DeviceView(generic.ObjectView):
# Services
services = Service.objects.restrict(request.user, 'view').filter(device=instance)
# Find up to ten devices in the same site with the same functional role for quick reference.
related_devices = Device.objects.restrict(request.user, 'view').filter(
site=instance.site, device_role=instance.device_role
).exclude(
pk=instance.pk
).prefetch_related(
'rack', 'device_type__manufacturer'
)[:10]
return {
'services': services,
'vc_members': vc_members,
'related_devices': related_devices,
'active_tab': 'device',
}
class DeviceConsolePortsView(DeviceComponentsView):
model = ConsolePort
child_model = ConsolePort
table = tables.DeviceConsolePortTable
filterset = filtersets.ConsolePortFilterSet
template_name = 'dcim/device/consoleports.html'
class DeviceConsoleServerPortsView(DeviceComponentsView):
model = ConsoleServerPort
child_model = ConsoleServerPort
table = tables.DeviceConsoleServerPortTable
filterset = filtersets.ConsoleServerPortFilterSet
template_name = 'dcim/device/consoleserverports.html'
class DevicePowerPortsView(DeviceComponentsView):
model = PowerPort
child_model = PowerPort
table = tables.DevicePowerPortTable
filterset = filtersets.PowerPortFilterSet
template_name = 'dcim/device/powerports.html'
class DevicePowerOutletsView(DeviceComponentsView):
model = PowerOutlet
child_model = PowerOutlet
table = tables.DevicePowerOutletTable
filterset = filtersets.PowerOutletFilterSet
template_name = 'dcim/device/poweroutlets.html'
class DeviceInterfacesView(DeviceComponentsView):
model = Interface
child_model = Interface
table = tables.DeviceInterfaceTable
filterset = filtersets.InterfaceFilterSet
template_name = 'dcim/device/interfaces.html'
def get_components(self, request, instance):
return instance.vc_interfaces().restrict(request.user, 'view').prefetch_related(
def get_children(self, request, parent):
return parent.vc_interfaces().restrict(request.user, 'view').prefetch_related(
Prefetch('ip_addresses', queryset=IPAddress.objects.restrict(request.user)),
Prefetch('member_interfaces', queryset=Interface.objects.restrict(request.user))
)
class DeviceFrontPortsView(DeviceComponentsView):
model = FrontPort
child_model = FrontPort
table = tables.DeviceFrontPortTable
filterset = filtersets.FrontPortFilterSet
template_name = 'dcim/device/frontports.html'
class DeviceRearPortsView(DeviceComponentsView):
model = RearPort
child_model = RearPort
table = tables.DeviceRearPortTable
filterset = filtersets.RearPortFilterSet
template_name = 'dcim/device/rearports.html'
class DeviceDeviceBaysView(DeviceComponentsView):
model = DeviceBay
child_model = DeviceBay
table = tables.DeviceDeviceBayTable
filterset = filtersets.DeviceBayFilterSet
template_name = 'dcim/device/devicebays.html'
class DeviceInventoryView(DeviceComponentsView):
model = InventoryItem
child_model = InventoryItem
table = tables.DeviceInventoryItemTable
filterset = filtersets.InventoryItemFilterSet
template_name = 'dcim/device/inventory.html'

View File

@@ -170,17 +170,7 @@ class ImageAttachmentSerializer(ValidatedModelSerializer):
@swagger_serializer_method(serializer_or_field=serializers.DictField)
def get_parent(self, obj):
# Static mapping of models to their nested serializers
if isinstance(obj.parent, Device):
serializer = NestedDeviceSerializer
elif isinstance(obj.parent, Rack):
serializer = NestedRackSerializer
elif isinstance(obj.parent, Site):
serializer = NestedSiteSerializer
else:
raise Exception("Unexpected type of parent object for ImageAttachment")
serializer = get_serializer_for_model(obj.parent, prefix='Nested')
return serializer(obj.parent, context={'request': self.context['request']}).data

View File

@@ -9,7 +9,7 @@ from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.core.management.base import BaseCommand
APPS = ['circuits', 'dcim', 'extras', 'ipam', 'tenancy', 'users', 'virtualization']
APPS = ('circuits', 'dcim', 'extras', 'ipam', 'tenancy', 'users', 'virtualization', 'wireless')
BANNER_TEXT = """### NetBox interactive shell ({node})
### Python {python} | Django {django} | NetBox {netbox}

View File

@@ -0,0 +1,18 @@
import django.core.validators
from django.db import migrations, models
import re
class Migration(migrations.Migration):
dependencies = [
('extras', '0065_imageattachment_change_logging'),
]
operations = [
migrations.AlterField(
model_name='customfield',
name='name',
field=models.CharField(max_length=50, unique=True, validators=[django.core.validators.RegexValidator(flags=re.RegexFlag['IGNORECASE'], message='Only alphanumeric characters and underscores are allowed.', regex='^[a-z0-9_]+$')]),
),
]

View File

@@ -22,6 +22,12 @@ from utilities.querysets import RestrictedQuerySet
from utilities.validators import validate_regex
__all__ = (
'CustomField',
'CustomFieldManager',
)
class CustomFieldManager(models.Manager.from_queryset(RestrictedQuerySet)):
use_in_migrations = True
@@ -49,7 +55,14 @@ class CustomField(ChangeLoggedModel):
name = models.CharField(
max_length=50,
unique=True,
help_text='Internal field name'
help_text='Internal field name',
validators=(
RegexValidator(
regex=r'^[a-z0-9_]+$',
message="Only alphanumeric characters and underscores are allowed.",
flags=re.IGNORECASE
),
)
)
label = models.CharField(
max_length=50,

View File

@@ -22,7 +22,7 @@ class ConfigContextQuerySet(RestrictedQuerySet):
# Device type assignment is relevant only for Devices
device_type = getattr(obj, 'device_type', None)
# Cluster assignment is relevant only for VirtualMachines
# Get assigned Cluster and ClusterGroup, if any
cluster = getattr(obj, 'cluster', None)
cluster_group = getattr(cluster, 'group', None)
@@ -67,11 +67,8 @@ class ConfigContextModelQuerySet(RestrictedQuerySet):
Includes a method which appends an annotation of aggregated config context JSON data objects. This is
implemented as a subquery which performs all the joins necessary to filter relevant config context objects.
This offers a substantial performance gain over ConfigContextQuerySet.get_for_object() when dealing with
multiple objects.
This allows the annotation to be entirely optional.
multiple objects. This allows the annotation to be entirely optional.
"""
def annotate_config_context_data(self):
"""
Attach the subquery annotation to the base queryset
@@ -123,6 +120,7 @@ class ConfigContextModelQuerySet(RestrictedQuerySet):
elif self.model._meta.model_name == 'virtualmachine':
base_query.add((Q(roles=OuterRef('role')) | Q(roles=None)), Q.AND)
base_query.add((Q(sites=OuterRef('cluster__site')) | Q(sites=None)), Q.AND)
base_query.add(Q(device_types=None), Q.AND)
region_field = 'cluster__site__region'
sitegroup_field = 'cluster__site__group'

View File

@@ -1,185 +0,0 @@
from django.core.exceptions import ObjectDoesNotExist, PermissionDenied
from django.db import transaction
from django.shortcuts import get_object_or_404
from django_pglocks import advisory_lock
from drf_yasg.utils import swagger_auto_schema
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response
from ipam.models import *
from netbox.config import get_config
from utilities.constants import ADVISORY_LOCK_KEYS
from . import serializers
class AvailablePrefixesMixin:
@swagger_auto_schema(method='get', responses={200: serializers.AvailablePrefixSerializer(many=True)})
@swagger_auto_schema(method='post', responses={201: serializers.PrefixSerializer(many=False)})
@action(detail=True, url_path='available-prefixes', methods=['get', 'post'])
@advisory_lock(ADVISORY_LOCK_KEYS['available-prefixes'])
def available_prefixes(self, request, pk=None):
"""
A convenience method for returning available child prefixes within a parent.
The advisory lock decorator uses a PostgreSQL advisory lock to prevent this API from being
invoked in parallel, which results in a race condition where multiple insertions can occur.
"""
prefix = get_object_or_404(self.queryset, pk=pk)
available_prefixes = prefix.get_available_prefixes()
if request.method == 'POST':
# Validate Requested Prefixes' length
serializer = serializers.PrefixLengthSerializer(
data=request.data if isinstance(request.data, list) else [request.data],
many=True,
context={
'request': request,
'prefix': prefix,
}
)
if not serializer.is_valid():
return Response(
serializer.errors,
status=status.HTTP_400_BAD_REQUEST
)
requested_prefixes = serializer.validated_data
# Allocate prefixes to the requested objects based on availability within the parent
for i, requested_prefix in enumerate(requested_prefixes):
# Find the first available prefix equal to or larger than the requested size
for available_prefix in available_prefixes.iter_cidrs():
if requested_prefix['prefix_length'] >= available_prefix.prefixlen:
allocated_prefix = '{}/{}'.format(available_prefix.network, requested_prefix['prefix_length'])
requested_prefix['prefix'] = allocated_prefix
requested_prefix['vrf'] = prefix.vrf.pk if prefix.vrf else None
break
else:
return Response(
{
"detail": "Insufficient space is available to accommodate the requested prefix size(s)"
},
status=status.HTTP_204_NO_CONTENT
)
# Remove the allocated prefix from the list of available prefixes
available_prefixes.remove(allocated_prefix)
# Initialize the serializer with a list or a single object depending on what was requested
context = {'request': request}
if isinstance(request.data, list):
serializer = serializers.PrefixSerializer(data=requested_prefixes, many=True, context=context)
else:
serializer = serializers.PrefixSerializer(data=requested_prefixes[0], context=context)
# Create the new Prefix(es)
if serializer.is_valid():
try:
with transaction.atomic():
created = serializer.save()
self._validate_objects(created)
except ObjectDoesNotExist:
raise PermissionDenied()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
else:
serializer = serializers.AvailablePrefixSerializer(available_prefixes.iter_cidrs(), many=True, context={
'request': request,
'vrf': prefix.vrf,
})
return Response(serializer.data)
class AvailableIPsMixin:
parent_model = Prefix
@swagger_auto_schema(method='get', responses={200: serializers.AvailableIPSerializer(many=True)})
@swagger_auto_schema(method='post', responses={201: serializers.AvailableIPSerializer(many=True)},
request_body=serializers.AvailableIPSerializer(many=True))
@action(detail=True, url_path='available-ips', methods=['get', 'post'], queryset=IPAddress.objects.all())
@advisory_lock(ADVISORY_LOCK_KEYS['available-ips'])
def available_ips(self, request, pk=None):
"""
A convenience method for returning available IP addresses within a Prefix or IPRange. By default, the number of
IPs returned will be equivalent to PAGINATE_COUNT. An arbitrary limit (up to MAX_PAGE_SIZE, if set) may be
passed, however results will not be paginated.
The advisory lock decorator uses a PostgreSQL advisory lock to prevent this API from being
invoked in parallel, which results in a race condition where multiple insertions can occur.
"""
parent = get_object_or_404(self.parent_model.objects.restrict(request.user), pk=pk)
# Create the next available IP
if request.method == 'POST':
# Normalize to a list of objects
requested_ips = request.data if isinstance(request.data, list) else [request.data]
# Determine if the requested number of IPs is available
available_ips = parent.get_available_ips()
if available_ips.size < len(requested_ips):
return Response(
{
"detail": f"An insufficient number of IP addresses are available within {parent} "
f"({len(requested_ips)} requested, {len(available_ips)} available)"
},
status=status.HTTP_204_NO_CONTENT
)
# Assign addresses from the list of available IPs and copy VRF assignment from the parent
available_ips = iter(available_ips)
for requested_ip in requested_ips:
requested_ip['address'] = f'{next(available_ips)}/{parent.mask_length}'
requested_ip['vrf'] = parent.vrf.pk if parent.vrf else None
# Initialize the serializer with a list or a single object depending on what was requested
context = {'request': request}
if isinstance(request.data, list):
serializer = serializers.IPAddressSerializer(data=requested_ips, many=True, context=context)
else:
serializer = serializers.IPAddressSerializer(data=requested_ips[0], context=context)
# Create the new IP address(es)
if serializer.is_valid():
try:
with transaction.atomic():
created = serializer.save()
self._validate_objects(created)
except ObjectDoesNotExist:
raise PermissionDenied()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# Determine the maximum number of IPs to return
else:
config = get_config()
PAGINATE_COUNT = config.PAGINATE_COUNT
MAX_PAGE_SIZE = config.MAX_PAGE_SIZE
try:
limit = int(request.query_params.get('limit', PAGINATE_COUNT))
except ValueError:
limit = PAGINATE_COUNT
if MAX_PAGE_SIZE:
limit = min(limit, MAX_PAGE_SIZE)
# Calculate available IPs within the parent
ip_list = []
for index, ip in enumerate(parent.get_available_ips(), start=1):
ip_list.append(ip)
if index == limit:
break
serializer = serializers.AvailableIPSerializer(ip_list, many=True, context={
'request': request,
'parent': parent,
'vrf': parent.vrf,
})
return Response(serializer.data)

View File

@@ -1,4 +1,7 @@
from django.urls import path
from netbox.api import OrderedDefaultRouter
from ipam.models import IPRange, Prefix
from . import views
@@ -42,4 +45,23 @@ router.register('vlans', views.VLANViewSet)
router.register('services', views.ServiceViewSet)
app_name = 'ipam-api'
urlpatterns = router.urls
urlpatterns = [
path(
'ip-ranges/<int:pk>/available-ips/',
views.IPRangeAvailableIPAddressesView.as_view(),
name='iprange-available-ips'
),
path(
'prefixes/<int:pk>/available-prefixes/',
views.AvailablePrefixesView.as_view(),
name='prefix-available-prefixes'
),
path(
'prefixes/<int:pk>/available-ips/',
views.PrefixAvailableIPAddressesView.as_view(),
name='prefix-available-ips'
),
]
urlpatterns += router.urls

View File

@@ -1,12 +1,23 @@
from django.core.exceptions import ObjectDoesNotExist, PermissionDenied
from django.db import transaction
from django_pglocks import advisory_lock
from django.shortcuts import get_object_or_404
from drf_yasg.utils import swagger_auto_schema
from rest_framework import status
from rest_framework.response import Response
from rest_framework.routers import APIRootView
from rest_framework.views import APIView
from dcim.models import Site
from extras.api.views import CustomFieldModelViewSet
from ipam import filtersets
from ipam.models import *
from netbox.api.views import ModelViewSet
from netbox.api.views import ModelViewSet, ObjectValidationMixin
from netbox.config import get_config
from utilities.constants import ADVISORY_LOCK_KEYS
from utilities.utils import count_related
from . import mixins, serializers
from . import serializers
class IPAMRootView(APIRootView):
@@ -18,7 +29,7 @@ class IPAMRootView(APIRootView):
#
# ASNs
# Viewsets
#
class ASNViewSet(CustomFieldModelViewSet):
@@ -27,10 +38,6 @@ class ASNViewSet(CustomFieldModelViewSet):
filterset_class = filtersets.ASNFilterSet
#
# VRFs
#
class VRFViewSet(CustomFieldModelViewSet):
queryset = VRF.objects.prefetch_related('tenant').prefetch_related(
'import_targets', 'export_targets', 'tags'
@@ -42,20 +49,12 @@ class VRFViewSet(CustomFieldModelViewSet):
filterset_class = filtersets.VRFFilterSet
#
# Route targets
#
class RouteTargetViewSet(CustomFieldModelViewSet):
queryset = RouteTarget.objects.prefetch_related('tenant').prefetch_related('tags')
serializer_class = serializers.RouteTargetSerializer
filterset_class = filtersets.RouteTargetFilterSet
#
# RIRs
#
class RIRViewSet(CustomFieldModelViewSet):
queryset = RIR.objects.annotate(
aggregate_count=count_related(Aggregate, 'rir')
@@ -64,20 +63,12 @@ class RIRViewSet(CustomFieldModelViewSet):
filterset_class = filtersets.RIRFilterSet
#
# Aggregates
#
class AggregateViewSet(CustomFieldModelViewSet):
queryset = Aggregate.objects.prefetch_related('rir').prefetch_related('tags')
serializer_class = serializers.AggregateSerializer
filterset_class = filtersets.AggregateFilterSet
#
# Roles
#
class RoleViewSet(CustomFieldModelViewSet):
queryset = Role.objects.annotate(
prefix_count=count_related(Prefix, 'role'),
@@ -87,11 +78,7 @@ class RoleViewSet(CustomFieldModelViewSet):
filterset_class = filtersets.RoleFilterSet
#
# Prefixes
#
class PrefixViewSet(mixins.AvailableIPsMixin, mixins.AvailablePrefixesMixin, CustomFieldModelViewSet):
class PrefixViewSet(CustomFieldModelViewSet):
queryset = Prefix.objects.prefetch_related(
'site', 'vrf__tenant', 'tenant', 'vlan', 'role', 'tags'
)
@@ -106,11 +93,7 @@ class PrefixViewSet(mixins.AvailableIPsMixin, mixins.AvailablePrefixesMixin, Cus
return super().get_serializer_class()
#
# IP ranges
#
class IPRangeViewSet(mixins.AvailableIPsMixin, CustomFieldModelViewSet):
class IPRangeViewSet(CustomFieldModelViewSet):
queryset = IPRange.objects.prefetch_related('vrf', 'role', 'tenant', 'tags')
serializer_class = serializers.IPRangeSerializer
filterset_class = filtersets.IPRangeFilterSet
@@ -118,10 +101,6 @@ class IPRangeViewSet(mixins.AvailableIPsMixin, CustomFieldModelViewSet):
parent_model = IPRange # AvailableIPsMixin
#
# IP addresses
#
class IPAddressViewSet(CustomFieldModelViewSet):
queryset = IPAddress.objects.prefetch_related(
'vrf__tenant', 'tenant', 'nat_inside', 'nat_outside', 'tags', 'assigned_object'
@@ -130,10 +109,6 @@ class IPAddressViewSet(CustomFieldModelViewSet):
filterset_class = filtersets.IPAddressFilterSet
#
# FHRP groups
#
class FHRPGroupViewSet(CustomFieldModelViewSet):
queryset = FHRPGroup.objects.prefetch_related('ip_addresses', 'tags')
serializer_class = serializers.FHRPGroupSerializer
@@ -147,10 +122,6 @@ class FHRPGroupAssignmentViewSet(CustomFieldModelViewSet):
filterset_class = filtersets.FHRPGroupAssignmentFilterSet
#
# VLAN groups
#
class VLANGroupViewSet(CustomFieldModelViewSet):
queryset = VLANGroup.objects.annotate(
vlan_count=count_related(VLAN, 'group')
@@ -159,10 +130,6 @@ class VLANGroupViewSet(CustomFieldModelViewSet):
filterset_class = filtersets.VLANGroupFilterSet
#
# VLANs
#
class VLANViewSet(CustomFieldModelViewSet):
queryset = VLAN.objects.prefetch_related(
'site', 'group', 'tenant', 'role', 'tags'
@@ -173,13 +140,190 @@ class VLANViewSet(CustomFieldModelViewSet):
filterset_class = filtersets.VLANFilterSet
#
# Services
#
class ServiceViewSet(ModelViewSet):
queryset = Service.objects.prefetch_related(
'device', 'virtual_machine', 'tags', 'ipaddresses'
)
serializer_class = serializers.ServiceSerializer
filterset_class = filtersets.ServiceFilterSet
#
# Views
#
class AvailablePrefixesView(ObjectValidationMixin, APIView):
queryset = Prefix.objects.all()
@swagger_auto_schema(responses={200: serializers.AvailablePrefixSerializer(many=True)})
def get(self, request, pk):
prefix = get_object_or_404(Prefix.objects.restrict(request.user), pk=pk)
available_prefixes = prefix.get_available_prefixes()
serializer = serializers.AvailablePrefixSerializer(available_prefixes.iter_cidrs(), many=True, context={
'request': request,
'vrf': prefix.vrf,
})
return Response(serializer.data)
@swagger_auto_schema(
request_body=serializers.PrefixLengthSerializer,
responses={201: serializers.PrefixSerializer(many=True)}
)
@advisory_lock(ADVISORY_LOCK_KEYS['available-prefixes'])
def post(self, request, pk):
self.queryset = self.queryset.restrict(request.user, 'add')
prefix = get_object_or_404(Prefix.objects.restrict(request.user), pk=pk)
available_prefixes = prefix.get_available_prefixes()
# Validate Requested Prefixes' length
serializer = serializers.PrefixLengthSerializer(
data=request.data if isinstance(request.data, list) else [request.data],
many=True,
context={
'request': request,
'prefix': prefix,
}
)
if not serializer.is_valid():
return Response(
serializer.errors,
status=status.HTTP_400_BAD_REQUEST
)
requested_prefixes = serializer.validated_data
# Allocate prefixes to the requested objects based on availability within the parent
for i, requested_prefix in enumerate(requested_prefixes):
# Find the first available prefix equal to or larger than the requested size
for available_prefix in available_prefixes.iter_cidrs():
if requested_prefix['prefix_length'] >= available_prefix.prefixlen:
allocated_prefix = '{}/{}'.format(available_prefix.network, requested_prefix['prefix_length'])
requested_prefix['prefix'] = allocated_prefix
requested_prefix['vrf'] = prefix.vrf.pk if prefix.vrf else None
break
else:
return Response(
{
"detail": "Insufficient space is available to accommodate the requested prefix size(s)"
},
status=status.HTTP_409_CONFLICT
)
# Remove the allocated prefix from the list of available prefixes
available_prefixes.remove(allocated_prefix)
# Initialize the serializer with a list or a single object depending on what was requested
context = {'request': request}
if isinstance(request.data, list):
serializer = serializers.PrefixSerializer(data=requested_prefixes, many=True, context=context)
else:
serializer = serializers.PrefixSerializer(data=requested_prefixes[0], context=context)
# Create the new Prefix(es)
if serializer.is_valid():
try:
with transaction.atomic():
created = serializer.save()
self._validate_objects(created)
except ObjectDoesNotExist:
raise PermissionDenied()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class AvailableIPAddressesView(ObjectValidationMixin, APIView):
queryset = IPAddress.objects.all()
def get_parent(self, request, pk):
raise NotImplemented()
@swagger_auto_schema(responses={200: serializers.AvailableIPSerializer(many=True)})
def get(self, request, pk):
parent = self.get_parent(request, pk)
config = get_config()
PAGINATE_COUNT = config.PAGINATE_COUNT
MAX_PAGE_SIZE = config.MAX_PAGE_SIZE
try:
limit = int(request.query_params.get('limit', PAGINATE_COUNT))
except ValueError:
limit = PAGINATE_COUNT
if MAX_PAGE_SIZE:
limit = min(limit, MAX_PAGE_SIZE)
# Calculate available IPs within the parent
ip_list = []
for index, ip in enumerate(parent.get_available_ips(), start=1):
ip_list.append(ip)
if index == limit:
break
serializer = serializers.AvailableIPSerializer(ip_list, many=True, context={
'request': request,
'parent': parent,
'vrf': parent.vrf,
})
return Response(serializer.data)
@swagger_auto_schema(
request_body=serializers.AvailableIPSerializer,
responses={201: serializers.IPAddressSerializer(many=True)}
)
@advisory_lock(ADVISORY_LOCK_KEYS['available-ips'])
def post(self, request, pk):
self.queryset = self.queryset.restrict(request.user, 'add')
parent = self.get_parent(request, pk)
# Normalize to a list of objects
requested_ips = request.data if isinstance(request.data, list) else [request.data]
# Determine if the requested number of IPs is available
available_ips = parent.get_available_ips()
if available_ips.size < len(requested_ips):
return Response(
{
"detail": f"An insufficient number of IP addresses are available within {parent} "
f"({len(requested_ips)} requested, {len(available_ips)} available)"
},
status=status.HTTP_409_CONFLICT
)
# Assign addresses from the list of available IPs and copy VRF assignment from the parent
available_ips = iter(available_ips)
for requested_ip in requested_ips:
requested_ip['address'] = f'{next(available_ips)}/{parent.mask_length}'
requested_ip['vrf'] = parent.vrf.pk if parent.vrf else None
# Initialize the serializer with a list or a single object depending on what was requested
context = {'request': request}
if isinstance(request.data, list):
serializer = serializers.IPAddressSerializer(data=requested_ips, many=True, context=context)
else:
serializer = serializers.IPAddressSerializer(data=requested_ips[0], context=context)
# Create the new IP address(es)
if serializer.is_valid():
try:
with transaction.atomic():
created = serializer.save()
self._validate_objects(created)
except ObjectDoesNotExist:
raise PermissionDenied()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class PrefixAvailableIPAddressesView(AvailableIPAddressesView):
def get_parent(self, request, pk):
return get_object_or_404(Prefix.objects.restrict(request.user), pk=pk)
class IPRangeAvailableIPAddressesView(AvailableIPAddressesView):
def get_parent(self, request, pk):
return get_object_or_404(IPRange.objects.restrict(request.user), pk=pk)

View File

@@ -277,10 +277,6 @@ class IPRangeFilterForm(TenancyFilterForm, CustomFieldModelFilterForm):
class IPAddressFilterForm(TenancyFilterForm, CustomFieldModelFilterForm):
model = IPAddress
field_order = [
'q', 'parent', 'family', 'mask_length', 'vrf_id', 'present_in_vrf_id', 'status', 'role',
'assigned_to_interface', 'tenant_group_id', 'tenant_id',
]
field_groups = [
['q', 'tag'],
['parent', 'family', 'status', 'role', 'mask_length', 'assigned_to_interface'],

View File

@@ -462,12 +462,15 @@ class IPAddressForm(TenancyForm, CustomFieldModelForm):
super().clean()
# Handle object assignment
if self.cleaned_data['interface']:
self.instance.assigned_object = self.cleaned_data['interface']
elif self.cleaned_data['vminterface']:
self.instance.assigned_object = self.cleaned_data['vminterface']
elif self.cleaned_data['fhrpgroup']:
self.instance.assigned_object = self.cleaned_data['fhrpgroup']
selected_objects = [
field for field in ('interface', 'vminterface', 'fhrpgroup') if self.cleaned_data[field]
]
if len(selected_objects) > 1:
raise forms.ValidationError({
selected_objects[1]: "An IP address can only be assigned to a single object."
})
elif selected_objects:
self.instance.assigned_object = self.cleaned_data[selected_objects[0]]
# Primary IP assignment is only available if an interface has been assigned.
interface = self.cleaned_data.get('interface') or self.cleaned_data.get('vminterface')
@@ -575,9 +578,9 @@ class FHRPGroupForm(CustomFieldModelForm):
vrf=self.cleaned_data['ip_vrf'],
address=self.cleaned_data['ip_address'],
status=self.cleaned_data['ip_status'],
role=FHRP_PROTOCOL_ROLE_MAPPINGS[self.cleaned_data['protocol']],
assigned_object=instance
)
ipaddress.role = FHRP_PROTOCOL_ROLE_MAPPINGS[self.cleaned_data['protocol']]
ipaddress.save()
# Check that the new IPAddress conforms with any assigned object-level permissions
@@ -587,13 +590,20 @@ class FHRPGroupForm(CustomFieldModelForm):
return instance
def clean(self):
ip_vrf = self.cleaned_data.get('ip_vrf')
ip_address = self.cleaned_data.get('ip_address')
ip_status = self.cleaned_data.get('ip_status')
if ip_address and not ip_status:
raise forms.ValidationError({
'ip_status': "Status must be set when creating a new IP address."
if ip_address:
ip_form = IPAddressForm({
'address': ip_address,
'vrf': ip_vrf,
'status': ip_status,
})
if not ip_form.is_valid():
self.errors.update({
f'ip_{field}': error for field, error in ip_form.errors.items()
})
class FHRPGroupAssignmentForm(BootstrapMixin, forms.ModelForm):
@@ -802,6 +812,14 @@ class VLANForm(TenancyForm, CustomFieldModelForm):
class ServiceForm(CustomFieldModelForm):
device = DynamicModelChoiceField(
queryset=Device.objects.all(),
required=False
)
virtual_machine = DynamicModelChoiceField(
queryset=VirtualMachine.objects.all(),
required=False
)
ports = NumericArrayField(
base_field=forms.IntegerField(
min_value=SERVICE_PORT_MIN,
@@ -809,6 +827,15 @@ class ServiceForm(CustomFieldModelForm):
),
help_text="Comma-separated list of one or more port numbers. A range may be specified using a hyphen."
)
ipaddresses = DynamicModelMultipleChoiceField(
queryset=IPAddress.objects.all(),
required=False,
label='IP Addresses',
query_params={
'device_id': '$device',
'virtual_machine_id': '$virtual_machine',
}
)
tags = DynamicModelMultipleChoiceField(
queryset=Tag.objects.all(),
required=False
@@ -817,7 +844,7 @@ class ServiceForm(CustomFieldModelForm):
class Meta:
model = Service
fields = [
'name', 'protocol', 'ports', 'ipaddresses', 'description', 'tags',
'device', 'virtual_machine', 'name', 'protocol', 'ports', 'ipaddresses', 'description', 'tags',
]
help_texts = {
'ipaddresses': "IP address assignment is optional. If no IPs are selected, the service is assumed to be "
@@ -827,18 +854,3 @@ class ServiceForm(CustomFieldModelForm):
'protocol': StaticSelect(),
'ipaddresses': StaticSelectMultiple(),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Limit IP address choices to those assigned to interfaces of the parent device/VM
if self.instance.device:
self.fields['ipaddresses'].queryset = IPAddress.objects.filter(
interface__in=self.instance.device.vc_interfaces().values_list('id', flat=True)
)
elif self.instance.virtual_machine:
self.fields['ipaddresses'].queryset = IPAddress.objects.filter(
vminterface__in=self.instance.virtual_machine.interfaces.values_list('id', flat=True)
)
else:
self.fields['ipaddresses'].choices = []

View File

@@ -58,13 +58,11 @@ class FHRPGroup(PrimaryModel):
def __str__(self):
name = f'{self.get_protocol_display()}: {self.group_id}'
# Append the list of assigned IP addresses to serve as an additional identifier
# Append the first assigned IP addresses (if any) to serve as an additional identifier
if self.pk:
ip_addresses = [
str(ip.address) for ip in self.ip_addresses.all()
]
if ip_addresses:
return f"{name} ({', '.join(ip_addresses)})"
ip_address = self.ip_addresses.first()
if ip_address:
return f"{name} ({ip_address})"
return name

View File

@@ -195,6 +195,12 @@ class Aggregate(PrimaryModel):
return self.prefix.version
return None
def get_child_prefixes(self):
"""
Return all Prefixes within this Aggregate
"""
return Prefix.objects.filter(prefix__net_contained=str(self.prefix))
def get_utilization(self):
"""
Determine the prefix utilization of the aggregate and return it as a percentage.

View File

@@ -289,7 +289,7 @@ class PrefixTest(APIViewTestCases.APIViewTestCase):
vrf = VRF.objects.create(name='VRF 1')
prefix = Prefix.objects.create(prefix=IPNetwork('192.0.2.0/28'), vrf=vrf, is_pool=True)
url = reverse('ipam-api:prefix-available-prefixes', kwargs={'pk': prefix.pk})
self.add_permissions('ipam.add_prefix')
self.add_permissions('ipam.view_prefix', 'ipam.add_prefix')
# Create four available prefixes with individual requests
prefixes_to_be_created = [
@@ -311,7 +311,7 @@ class PrefixTest(APIViewTestCases.APIViewTestCase):
# Try to create one more prefix
response = self.client.post(url, {'prefix_length': 30}, format='json', **self.header)
self.assertHttpStatus(response, status.HTTP_204_NO_CONTENT)
self.assertHttpStatus(response, status.HTTP_409_CONFLICT)
self.assertIn('detail', response.data)
# Try to create invalid prefix type
@@ -337,7 +337,7 @@ class PrefixTest(APIViewTestCases.APIViewTestCase):
{'prefix_length': 30, 'description': 'Prefix 5'},
]
response = self.client.post(url, data, format='json', **self.header)
self.assertHttpStatus(response, status.HTTP_204_NO_CONTENT)
self.assertHttpStatus(response, status.HTTP_409_CONFLICT)
self.assertIn('detail', response.data)
# Verify that no prefixes were created (the entire /28 is still available)
@@ -391,7 +391,7 @@ class PrefixTest(APIViewTestCases.APIViewTestCase):
# Try to create one more IP
response = self.client.post(url, {}, **self.header)
self.assertHttpStatus(response, status.HTTP_204_NO_CONTENT)
self.assertHttpStatus(response, status.HTTP_409_CONFLICT)
self.assertIn('detail', response.data)
def test_create_multiple_available_ips(self):
@@ -406,7 +406,7 @@ class PrefixTest(APIViewTestCases.APIViewTestCase):
# Try to create nine IPs (only eight are available)
data = [{'description': f'Test IP {i}'} for i in range(1, 10)] # 9 IPs
response = self.client.post(url, data, format='json', **self.header)
self.assertHttpStatus(response, status.HTTP_204_NO_CONTENT)
self.assertHttpStatus(response, status.HTTP_409_CONFLICT)
self.assertIn('detail', response.data)
# Create all eight available IPs in a single request
@@ -488,7 +488,7 @@ class IPRangeTest(APIViewTestCases.APIViewTestCase):
# Try to create one more IP
response = self.client.post(url, {}, **self.header)
self.assertHttpStatus(response, status.HTTP_204_NO_CONTENT)
self.assertHttpStatus(response, status.HTTP_409_CONFLICT)
self.assertIn('detail', response.data)
def test_create_multiple_available_ips(self):
@@ -505,7 +505,7 @@ class IPRangeTest(APIViewTestCases.APIViewTestCase):
# Try to create nine IPs (only eight are available)
data = [{'description': f'Test IP #{i}'} for i in range(1, 10)] # 9 IPs
response = self.client.post(url, data, format='json', **self.header)
self.assertHttpStatus(response, status.HTTP_204_NO_CONTENT)
self.assertHttpStatus(response, status.HTTP_409_CONFLICT)
self.assertIn('detail', response.data)
# Create all eight available IPs in a single request

View File

@@ -562,18 +562,7 @@ class VLANTestCase(ViewTestCases.PrimaryObjectViewTestCase):
}
# TODO: Update base class to PrimaryObjectViewTestCase
# Blocked by absence of standard creation view
class ServiceTestCase(
ViewTestCases.GetObjectViewTestCase,
ViewTestCases.GetObjectChangelogViewTestCase,
ViewTestCases.EditObjectViewTestCase,
ViewTestCases.DeleteObjectViewTestCase,
ViewTestCases.ListObjectsViewTestCase,
ViewTestCases.BulkImportObjectsViewTestCase,
ViewTestCases.BulkEditObjectsViewTestCase,
ViewTestCases.BulkDeleteObjectsViewTestCase
):
class ServiceTestCase(ViewTestCases.PrimaryObjectViewTestCase):
model = Service
@classmethod

View File

@@ -61,6 +61,7 @@ urlpatterns = [
path('aggregates/edit/', views.AggregateBulkEditView.as_view(), name='aggregate_bulk_edit'),
path('aggregates/delete/', views.AggregateBulkDeleteView.as_view(), name='aggregate_bulk_delete'),
path('aggregates/<int:pk>/', views.AggregateView.as_view(), name='aggregate'),
path('aggregates/<int:pk>/prefixes/', views.AggregatePrefixesView.as_view(), name='aggregate_prefixes'),
path('aggregates/<int:pk>/edit/', views.AggregateEditView.as_view(), name='aggregate_edit'),
path('aggregates/<int:pk>/delete/', views.AggregateDeleteView.as_view(), name='aggregate_delete'),
path('aggregates/<int:pk>/changelog/', ObjectChangeLogView.as_view(), name='aggregate_changelog', kwargs={'model': Aggregate}),
@@ -163,6 +164,7 @@ urlpatterns = [
# Services
path('services/', views.ServiceListView.as_view(), name='service_list'),
path('services/add/', views.ServiceEditView.as_view(), name='service_add'),
path('services/import/', views.ServiceBulkImportView.as_view(), name='service_import'),
path('services/edit/', views.ServiceBulkEditView.as_view(), name='service_bulk_edit'),
path('services/delete/', views.ServiceBulkDeleteView.as_view(), name='service_bulk_delete'),

View File

@@ -4,20 +4,34 @@ from .constants import *
from .models import Prefix, VLAN
def add_available_prefixes(parent, prefix_list):
def add_requested_prefixes(parent, prefix_list, show_available=True, show_assigned=True):
"""
Create fake Prefix objects for all unallocated space within a prefix.
Return a list of requested prefixes using show_available, show_assigned filters. If available prefixes are
requested, create fake Prefix objects for all unallocated space within a prefix.
:param parent: Parent Prefix instance
:param prefix_list: Child prefixes list
:param show_available: Include available prefixes.
:param show_assigned: Show assigned prefixes.
"""
child_prefixes = []
# Find all unallocated space
available_prefixes = netaddr.IPSet(parent) ^ netaddr.IPSet([p.prefix for p in prefix_list])
available_prefixes = [Prefix(prefix=p, status=None) for p in available_prefixes.iter_cidrs()]
# Add available prefixes to the table if requested
if prefix_list and show_available:
# Concatenate and sort complete list of children
prefix_list = list(prefix_list) + available_prefixes
prefix_list.sort(key=lambda p: p.prefix)
# Find all unallocated space, add fake Prefix objects to child_prefixes.
available_prefixes = netaddr.IPSet(parent) ^ netaddr.IPSet([p.prefix for p in prefix_list])
available_prefixes = [Prefix(prefix=p, status=None) for p in available_prefixes.iter_cidrs()]
child_prefixes = child_prefixes + available_prefixes
return prefix_list
# Add assigned prefixes to the table if requested
if prefix_list and show_assigned:
child_prefixes = child_prefixes + list(prefix_list)
# Sort child prefixes after additions
child_prefixes.sort(key=lambda p: p.prefix)
return child_prefixes
def add_available_ipaddresses(prefix, ipaddress_list, is_pool=False):

View File

@@ -1,21 +1,22 @@
from django.contrib.contenttypes.models import ContentType
from django.db.models import Prefetch
from django.db.models.expressions import RawSQL
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from dcim.filtersets import InterfaceFilterSet
from dcim.models import Device, Interface, Site
from dcim.tables import SiteTable
from netbox.views import generic
from utilities.tables import paginate_table
from utilities.utils import count_related
from virtualization.filtersets import VMInterfaceFilterSet
from virtualization.models import VirtualMachine, VMInterface
from . import filtersets, forms, tables
from .constants import *
from .models import *
from .models import ASN
from .utils import add_available_ipaddresses, add_available_prefixes, add_available_vlans
from .utils import add_requested_prefixes, add_available_vlans
#
@@ -274,37 +275,32 @@ class AggregateListView(generic.ObjectListView):
class AggregateView(generic.ObjectView):
queryset = Aggregate.objects.all()
class AggregatePrefixesView(generic.ObjectChildrenView):
queryset = Aggregate.objects.all()
child_model = Prefix
table = tables.PrefixTable
filterset = filtersets.PrefixFilterSet
template_name = 'ipam/aggregate/prefixes.html'
def get_children(self, request, parent):
return Prefix.objects.restrict(request.user, 'view').filter(
prefix__net_contained_or_equal=str(parent.prefix)
).prefetch_related('site', 'role', 'tenant', 'vlan')
def prep_table_data(self, request, queryset, parent):
# Determine whether to show assigned prefixes, available prefixes, or both
show_available = bool(request.GET.get('show_available', 'true') == 'true')
show_assigned = bool(request.GET.get('show_assigned', 'true') == 'true')
return add_requested_prefixes(parent.prefix, queryset, show_available, show_assigned)
def get_extra_context(self, request, instance):
# Find all child prefixes contained by this aggregate
child_prefixes = Prefix.objects.restrict(request.user, 'view').filter(
prefix__net_contained_or_equal=str(instance.prefix)
).prefetch_related(
'site', 'role'
).order_by(
'prefix'
)
# Add available prefixes to the table if requested
if request.GET.get('show_available', 'true') == 'true':
child_prefixes = add_available_prefixes(instance.prefix, child_prefixes)
prefix_table = tables.PrefixTable(child_prefixes, exclude=('utilization',))
if request.user.has_perm('ipam.change_prefix') or request.user.has_perm('ipam.delete_prefix'):
prefix_table.columns.show('pk')
paginate_table(prefix_table, request)
# Compile permissions list for rendering the object table
permissions = {
'add': request.user.has_perm('ipam.add_prefix'),
'change': request.user.has_perm('ipam.change_prefix'),
'delete': request.user.has_perm('ipam.delete_prefix'),
}
return {
'prefix_table': prefix_table,
'permissions': permissions,
'bulk_querystring': f'within={instance.prefix}',
'show_available': request.GET.get('show_available', 'true') == 'true',
'active_tab': 'prefixes',
'show_available': bool(request.GET.get('show_available', 'true') == 'true'),
'show_assigned': bool(request.GET.get('show_assigned', 'true') == 'true'),
}
@@ -451,104 +447,66 @@ class PrefixView(generic.ObjectView):
}
class PrefixPrefixesView(generic.ObjectView):
class PrefixPrefixesView(generic.ObjectChildrenView):
queryset = Prefix.objects.all()
child_model = Prefix
table = tables.PrefixTable
filterset = filtersets.PrefixFilterSet
template_name = 'ipam/prefix/prefixes.html'
def get_children(self, request, parent):
return parent.get_child_prefixes().restrict(request.user, 'view')
def prep_table_data(self, request, queryset, parent):
# Determine whether to show assigned prefixes, available prefixes, or both
show_available = bool(request.GET.get('show_available', 'true') == 'true')
show_assigned = bool(request.GET.get('show_assigned', 'true') == 'true')
return add_requested_prefixes(parent.prefix, queryset, show_available, show_assigned)
def get_extra_context(self, request, instance):
# Child prefixes table
child_prefixes = instance.get_child_prefixes().restrict(request.user, 'view').prefetch_related(
'site', 'vlan', 'role',
)
# Add available prefixes to the table if requested
if child_prefixes and request.GET.get('show_available', 'true') == 'true':
child_prefixes = add_available_prefixes(instance.prefix, child_prefixes)
table = tables.PrefixTable(child_prefixes, user=request.user, exclude=('utilization',))
if request.user.has_perm('ipam.change_prefix') or request.user.has_perm('ipam.delete_prefix'):
table.columns.show('pk')
paginate_table(table, request)
bulk_querystring = 'vrf_id={}&within={}'.format(instance.vrf.pk if instance.vrf else '0', instance.prefix)
# Compile permissions list for rendering the object table
permissions = {
'change': request.user.has_perm('ipam.change_prefix'),
'delete': request.user.has_perm('ipam.delete_prefix'),
}
return {
'table': table,
'permissions': permissions,
'bulk_querystring': bulk_querystring,
'bulk_querystring': f"vrf_id={instance.vrf.pk if instance.vrf else '0'}&within={instance.prefix}",
'active_tab': 'prefixes',
'first_available_prefix': instance.get_first_available_prefix(),
'show_available': request.GET.get('show_available', 'true') == 'true',
'show_available': bool(request.GET.get('show_available', 'true') == 'true'),
'show_assigned': bool(request.GET.get('show_assigned', 'true') == 'true'),
}
class PrefixIPRangesView(generic.ObjectView):
class PrefixIPRangesView(generic.ObjectChildrenView):
queryset = Prefix.objects.all()
child_model = IPRange
table = tables.IPRangeTable
filterset = filtersets.IPRangeFilterSet
template_name = 'ipam/prefix/ip_ranges.html'
def get_children(self, request, parent):
return parent.get_child_ranges().restrict(request.user, 'view')
def get_extra_context(self, request, instance):
# Find all IPRanges belonging to this Prefix
ip_ranges = instance.get_child_ranges().restrict(request.user, 'view').prefetch_related('vrf')
table = tables.IPRangeTable(ip_ranges, user=request.user)
if request.user.has_perm('ipam.change_iprange') or request.user.has_perm('ipam.delete_iprange'):
table.columns.show('pk')
paginate_table(table, request)
bulk_querystring = 'vrf_id={}&parent={}'.format(instance.vrf.pk if instance.vrf else '0', instance.prefix)
# Compile permissions list for rendering the object table
permissions = {
'change': request.user.has_perm('ipam.change_iprange'),
'delete': request.user.has_perm('ipam.delete_iprange'),
}
return {
'table': table,
'permissions': permissions,
'bulk_querystring': bulk_querystring,
'bulk_querystring': f"vrf_id={instance.vrf.pk if instance.vrf else '0'}&parent={instance.prefix}",
'active_tab': 'ip-ranges',
'first_available_ip': instance.get_first_available_ip(),
}
class PrefixIPAddressesView(generic.ObjectView):
class PrefixIPAddressesView(generic.ObjectChildrenView):
queryset = Prefix.objects.all()
child_model = IPAddress
table = tables.IPAddressTable
filterset = filtersets.IPAddressFilterSet
template_name = 'ipam/prefix/ip_addresses.html'
def get_children(self, request, parent):
return parent.get_child_ips().restrict(request.user, 'view')
def get_extra_context(self, request, instance):
# Find all IPAddresses belonging to this Prefix
ipaddresses = instance.get_child_ips().restrict(request.user, 'view').prefetch_related('vrf')
# Add available IP addresses to the table if requested
if request.GET.get('show_available', 'true') == 'true':
ipaddresses = add_available_ipaddresses(instance.prefix, ipaddresses, instance.is_pool)
table = tables.IPAddressTable(ipaddresses, user=request.user)
if request.user.has_perm('ipam.change_ipaddress') or request.user.has_perm('ipam.delete_ipaddress'):
table.columns.show('pk')
paginate_table(table, request)
bulk_querystring = 'vrf_id={}&parent={}'.format(instance.vrf.pk if instance.vrf else '0', instance.prefix)
# Compile permissions list for rendering the object table
permissions = {
'change': request.user.has_perm('ipam.change_ipaddress'),
'delete': request.user.has_perm('ipam.delete_ipaddress'),
}
return {
'table': table,
'permissions': permissions,
'bulk_querystring': bulk_querystring,
'bulk_querystring': f"vrf_id={instance.vrf.pk if instance.vrf else '0'}&parent={instance.prefix}",
'active_tab': 'ip-addresses',
'first_available_ip': instance.get_first_available_ip(),
'show_available': request.GET.get('show_available', 'true') == 'true',
}
@@ -596,35 +554,19 @@ class IPRangeView(generic.ObjectView):
queryset = IPRange.objects.all()
class IPRangeIPAddressesView(generic.ObjectView):
class IPRangeIPAddressesView(generic.ObjectChildrenView):
queryset = IPRange.objects.all()
child_model = IPAddress
table = tables.IPAddressTable
filterset = filtersets.IPAddressFilterSet
template_name = 'ipam/iprange/ip_addresses.html'
def get_children(self, request, parent):
return parent.get_child_ips().restrict(request.user, 'view')
def get_extra_context(self, request, instance):
# Find all IPAddresses within this range
ipaddresses = instance.get_child_ips().restrict(request.user, 'view').prefetch_related('vrf')
# Add available IP addresses to the table if requested
# if request.GET.get('show_available', 'true') == 'true':
# ipaddresses = add_available_ipaddresses(instance.prefix, ipaddresses, instance.is_pool)
ip_table = tables.IPAddressTable(ipaddresses)
if request.user.has_perm('ipam.change_ipaddress') or request.user.has_perm('ipam.delete_ipaddress'):
ip_table.columns.show('pk')
paginate_table(ip_table, request)
# Compile permissions list for rendering the object table
permissions = {
'add': request.user.has_perm('ipam.add_ipaddress'),
'change': request.user.has_perm('ipam.change_ipaddress'),
'delete': request.user.has_perm('ipam.delete_ipaddress'),
}
return {
'ip_table': ip_table,
'permissions': permissions,
'active_tab': 'ip-addresses',
'show_available': request.GET.get('show_available', 'true') == 'true',
}
@@ -1012,32 +954,34 @@ class VLANView(generic.ObjectView):
}
class VLANInterfacesView(generic.ObjectView):
class VLANInterfacesView(generic.ObjectChildrenView):
queryset = VLAN.objects.all()
child_model = Interface
table = tables.VLANDevicesTable
filterset = InterfaceFilterSet
template_name = 'ipam/vlan/interfaces.html'
def get_extra_context(self, request, instance):
interfaces = instance.get_interfaces().prefetch_related('device')
members_table = tables.VLANDevicesTable(interfaces)
paginate_table(members_table, request)
def get_children(self, request, parent):
return parent.get_interfaces().restrict(request.user, 'view')
def get_extra_context(self, request, instance):
return {
'members_table': members_table,
'active_tab': 'interfaces',
}
class VLANVMInterfacesView(generic.ObjectView):
class VLANVMInterfacesView(generic.ObjectChildrenView):
queryset = VLAN.objects.all()
child_model = VMInterface
table = tables.VLANVirtualMachinesTable
filterset = VMInterfaceFilterSet
template_name = 'ipam/vlan/vminterfaces.html'
def get_extra_context(self, request, instance):
interfaces = instance.get_vminterfaces().prefetch_related('virtual_machine')
members_table = tables.VLANVirtualMachinesTable(interfaces)
paginate_table(members_table, request)
def get_children(self, request, parent):
return parent.get_vminterfaces().restrict(request.user, 'view')
def get_extra_context(self, request, instance):
return {
'members_table': members_table,
'active_tab': 'vminterfaces',
}
@@ -1092,19 +1036,6 @@ class ServiceEditView(generic.ObjectEditView):
model_form = forms.ServiceForm
template_name = 'ipam/service_edit.html'
def alter_obj(self, obj, request, url_args, url_kwargs):
if 'device' in url_kwargs:
obj.device = get_object_or_404(
Device.objects.restrict(request.user),
pk=url_kwargs['device']
)
elif 'virtualmachine' in url_kwargs:
obj.virtual_machine = get_object_or_404(
VirtualMachine.objects.restrict(request.user),
pk=url_kwargs['virtualmachine']
)
return obj
class ServiceBulkImportView(generic.BulkImportView):
queryset = Service.objects.all()

View File

@@ -123,11 +123,28 @@ class BulkDestroyModelMixin:
self.perform_destroy(obj)
class ObjectValidationMixin:
def _validate_objects(self, instance):
"""
Check that the provided instance or list of instances are matched by the current queryset. This confirms that
any newly created or modified objects abide by the attributes granted by any applicable ObjectPermissions.
"""
if type(instance) is list:
# Check that all instances are still included in the view's queryset
conforming_count = self.queryset.filter(pk__in=[obj.pk for obj in instance]).count()
if conforming_count != len(instance):
raise ObjectDoesNotExist
else:
# Check that the instance is matched by the view's queryset
self.queryset.get(pk=instance.pk)
#
# Viewsets
#
class ModelViewSet(BulkUpdateModelMixin, BulkDestroyModelMixin, ModelViewSet_):
class ModelViewSet(BulkUpdateModelMixin, BulkDestroyModelMixin, ObjectValidationMixin, ModelViewSet_):
"""
Extend DRF's ModelViewSet to support bulk update and delete functions.
"""
@@ -211,20 +228,6 @@ class ModelViewSet(BulkUpdateModelMixin, BulkDestroyModelMixin, ModelViewSet_):
**kwargs
)
def _validate_objects(self, instance):
"""
Check that the provided instance or list of instances are matched by the current queryset. This confirms that
any newly created or modified objects abide by the attributes granted by any applicable ObjectPermissions.
"""
if type(instance) is list:
# Check that all instances are still included in the view's queryset
conforming_count = self.queryset.filter(pk__in=[obj.pk for obj in instance]).count()
if conforming_count != len(instance):
raise ObjectDoesNotExist
else:
# Check that the instance is matched by the view's queryset
self.queryset.get(pk=instance.pk)
def list(self, request, *args, **kwargs):
"""
Overrides ListModelMixin to allow processing ExportTemplates.

View File

@@ -62,7 +62,7 @@ class ChangeLoggingMixin(models.Model):
objectchange = ObjectChange(
changed_object=self,
related_object=related_object,
object_repr=str(self),
object_repr=str(self)[:200],
action=action
)
if hasattr(self, '_prechange_snapshot'):

View File

@@ -260,7 +260,7 @@ IPAM_MENU = Menu(
label='Other',
items=(
get_model_item('ipam', 'fhrpgroup', 'FHRP Groups'),
get_model_item('ipam', 'service', 'Services', actions=['import']),
get_model_item('ipam', 'service', 'Services'),
),
),
),

View File

@@ -19,7 +19,7 @@ from netbox.config import PARAMS
# Environment setup
#
VERSION = '3.1.0'
VERSION = '3.1.2'
# Hostname
HOSTNAME = platform.node()
@@ -424,7 +424,7 @@ EXEMPT_PATHS = (
f'/{BASE_PATH}graphql/',
f'/{BASE_PATH}login/',
f'/{BASE_PATH}oauth/',
f'/{BASE_PATH}metrics/',
f'/{BASE_PATH}metrics',
)

View File

@@ -23,6 +23,7 @@ from utilities.exceptions import AbortTransaction, PermissionsViolation
from utilities.forms import (
BootstrapMixin, BulkRenameForm, ConfirmationForm, CSVDataField, CSVFileField, ImportForm, restrict_form_fields,
)
from utilities.htmx import is_htmx
from utilities.permissions import get_permission_for_model
from utilities.tables import paginate_table
from utilities.utils import normalize_querydict, prepare_cloned_fields
@@ -72,6 +73,75 @@ class ObjectView(ObjectPermissionRequiredMixin, View):
})
class ObjectChildrenView(ObjectView):
"""
Display a table of child objects associated with the parent object.
queryset: The base queryset for retrieving the *parent* object
table: Table class used to render child objects list
template_name: Name of the template to use
"""
queryset = None
child_model = None
table = None
filterset = None
template_name = None
def get_children(self, request, parent):
"""
Return a QuerySet of child objects.
request: The current request
parent: The parent object
"""
raise NotImplementedError(f'{self.__class__.__name__} must implement get_children()')
def prep_table_data(self, request, queryset, parent):
"""
Provides a hook for subclassed views to modify data before initializing the table.
:param request: The current request
:param queryset: The filtered queryset of child objects
:param parent: The parent object
"""
return queryset
def get(self, request, *args, **kwargs):
"""
GET handler for rendering child objects.
"""
instance = get_object_or_404(self.queryset, **kwargs)
child_objects = self.get_children(request, instance)
if self.filterset:
child_objects = self.filterset(request.GET, child_objects).qs
permissions = {}
for action in ('change', 'delete'):
perm_name = get_permission_for_model(self.child_model, action)
permissions[action] = request.user.has_perm(perm_name)
table = self.table(self.prep_table_data(request, child_objects, instance), user=request.user)
# Determine whether to display bulk action checkboxes
if 'pk' in table.base_columns and (permissions['change'] or permissions['delete']):
table.columns.show('pk')
paginate_table(table, request)
# If this is an HTMX request, return only the rendered table HTML
if is_htmx(request):
return render(request, 'htmx/table.html', {
'object': instance,
'table': table,
})
return render(request, self.get_template_name(), {
'object': instance,
'table': table,
'permissions': permissions,
**self.get_extra_context(request, instance),
})
class ObjectListView(ObjectPermissionRequiredMixin, View):
"""
List a series of objects.
@@ -185,6 +255,12 @@ class ObjectListView(ObjectPermissionRequiredMixin, View):
table = self.get_table(request, permissions)
paginate_table(table, request)
# If this is an HTMX request, return only the rendered table HTML
if is_htmx(request):
return render(request, 'htmx/table.html', {
'table': table,
})
context = {
'content_type': content_type,
'table': table,
@@ -295,8 +371,11 @@ class ObjectEditView(GetReturnURLMixin, ObjectPermissionRequiredMixin, View):
redirect_url = request.path
# If the object has clone_fields, pre-populate a new instance of the form
if hasattr(obj, 'clone_fields'):
redirect_url += f"?{prepare_cloned_fields(obj)}"
params = prepare_cloned_fields(obj)
if 'return_url' in request.GET:
params['return_url'] = request.GET.get('return_url')
if params:
redirect_url += f"?{params.urlencode()}"
return redirect(redirect_url)
@@ -1229,7 +1308,7 @@ class BulkComponentCreateView(GetReturnURLMixin, ObjectPermissionRequiredMixin,
if not selected_objects:
messages.warning(request, "No {} were selected.".format(self.parent_model._meta.verbose_name_plural))
return redirect(self.get_return_url(request))
table = self.table(selected_objects)
table = self.table(selected_objects, orderable=False)
if '_create' in request.POST:
form = self.form(request.POST)

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

@@ -30,6 +30,7 @@
"cookie": "^0.4.1",
"dayjs": "^1.10.4",
"flatpickr": "4.6.3",
"htmx.org": "^1.6.1",
"just-debounce-it": "^1.4.0",
"masonry-layout": "^4.2.2",
"query-string": "^6.14.1",

View File

@@ -1,7 +1,6 @@
import { initConnectionToggle } from './connectionToggle';
import { initDepthToggle } from './depthToggle';
import { initMoveButtons } from './moveOptions';
import { initPerPage } from './pagination';
import { initPreferenceUpdate } from './preferences';
import { initReslug } from './reslug';
import { initSelectAll } from './selectAll';
@@ -13,7 +12,6 @@ export function initButtons(): void {
initReslug,
initSelectAll,
initPreferenceUpdate,
initPerPage,
initMoveButtons,
]) {
func();

View File

@@ -1,14 +0,0 @@
import { getElements } from '../util';
function handlePerPageSelect(event: Event): void {
const select = event.currentTarget as HTMLSelectElement;
if (select.form !== null) {
select.form.submit();
}
}
export function initPerPage(): void {
for (const element of getElements<HTMLSelectElement>('select.per-page')) {
element.addEventListener('change', handlePerPageSelect);
}
}

View File

@@ -1,4 +1,5 @@
import '@popperjs/core';
import 'bootstrap';
import 'htmx.org';
import 'simplebar';
import './netbox';

View File

@@ -1,5 +1,4 @@
import debounce from 'just-debounce-it';
import { getElements, getRowValues, findFirstAdjacent, isTruthy } from './util';
import { getElements, findFirstAdjacent, isTruthy } from './util';
/**
* Change the display value and hidden input values of the search filter based on dropdown
@@ -41,109 +40,8 @@ function initSearchBar(): void {
}
}
/**
* Initialize Interface Table Filter Elements.
*/
function initInterfaceFilter(): void {
for (const input of getElements<HTMLInputElement>('input.interface-filter')) {
const table = findFirstAdjacent<HTMLTableElement>(input, 'table');
const rows = Array.from(
table?.querySelectorAll<HTMLTableRowElement>('tbody > tr') ?? [],
).filter(r => r !== null);
/**
* Filter on-page table by input text.
*/
function handleInput(event: Event): void {
const target = event.target as HTMLInputElement;
// Create a regex pattern from the input search text to match against.
const filter = new RegExp(target.value.toLowerCase().trim());
// Each row represents an interface and its attributes.
for (const row of rows) {
// Find the row's checkbox and deselect it, so that it is not accidentally included in form
// submissions.
const checkBox = row.querySelector<HTMLInputElement>('input[type="checkbox"][name="pk"]');
if (checkBox !== null) {
checkBox.checked = false;
}
// The data-name attribute's value contains the interface name.
const name = row.getAttribute('data-name');
if (typeof name === 'string') {
if (filter.test(name.toLowerCase().trim())) {
// If this row matches the search pattern, but is already hidden, unhide it.
if (row.classList.contains('d-none')) {
row.classList.remove('d-none');
}
} else {
// If this row doesn't match the search pattern, hide it.
row.classList.add('d-none');
}
}
}
}
input.addEventListener('keyup', debounce(handleInput, 300));
}
}
function initTableFilter(): void {
for (const input of getElements<HTMLInputElement>('input.object-filter')) {
// Find the first adjacent table element.
const table = findFirstAdjacent<HTMLTableElement>(input, 'table');
// Build a valid array of <tr/> elements that are children of the adjacent table.
const rows = Array.from(
table?.querySelectorAll<HTMLTableRowElement>('tbody > tr') ?? [],
).filter(r => r !== null);
/**
* Filter table rows by matched input text.
* @param event
*/
function handleInput(event: Event): void {
const target = event.target as HTMLInputElement;
// Create a regex pattern from the input search text to match against.
const filter = new RegExp(target.value.toLowerCase().trim());
// List of which rows which match the query
const matchedRows: Array<HTMLTableRowElement> = [];
for (const row of rows) {
// Find the row's checkbox and deselect it, so that it is not accidentally included in form
// submissions.
const checkBox = row.querySelector<HTMLInputElement>('input[type="checkbox"][name="pk"]');
if (checkBox !== null) {
checkBox.checked = false;
}
// Iterate through each row's cell values
for (const value of getRowValues(row)) {
if (filter.test(value.toLowerCase())) {
// If this row matches the search pattern, add it to the list.
matchedRows.push(row);
break;
}
}
}
// Iterate the rows again to set visibility.
// This results in a single reflow instead of one for each row.
for (const row of rows) {
if (matchedRows.indexOf(row) >= 0) {
row.classList.remove('d-none');
} else {
row.classList.add('d-none');
}
}
}
input.addEventListener('keyup', debounce(handleInput, 300));
}
}
export function initSearch(): void {
for (const func of [initSearchBar, initTableFilter, initInterfaceFilter]) {
for (const func of [initSearchBar]) {
func();
}
}

View File

@@ -235,6 +235,16 @@ table {
}
}
th.asc a::after {
content: "\f0140";
font-family: 'Material Design Icons';
}
th.desc a::after {
content: "\f0143";
font-family: 'Material Design Icons';
}
&.table > :not(caption) > * > * {
padding-right: $table-cell-padding-x-sm !important;
padding-left: $table-cell-padding-x-sm !important;
@@ -727,10 +737,6 @@ nav.breadcrumb-container {
}
}
div.paginator > form > div.input-group {
width: fit-content;
}
label.required {
font-weight: $font-weight-bold;
@@ -890,14 +896,6 @@ div.card-overlay {
}
}
// Right-align the paginator element.
.paginator {
display: flex;
flex-direction: column;
align-items: flex-end;
padding: $spacer 0;
}
// Tabbed content
.nav-tabs {
.nav-link {

View File

@@ -1688,6 +1688,11 @@ hosted-git-info@^2.1.4, hosted-git-info@^2.8.9:
resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.8.9.tgz#dffc0bf9a21c02209090f2aa69429e1414daf3f9"
integrity sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==
htmx.org@^1.6.1:
version "1.6.1"
resolved "https://registry.yarnpkg.com/htmx.org/-/htmx.org-1.6.1.tgz#6f0d59a93fa61cbaa15316c134a2f179045a5778"
integrity sha512-i+1k5ee2eFWaZbomjckyrDjUpa3FMDZWufatUSBmmsjXVksn89nsXvr1KLGIdAajiz+ZSL7TE4U/QaZVd2U2sA==
ignore@^4.0.6:
version "4.0.6"
resolved "https://registry.yarnpkg.com/ignore/-/ignore-4.0.6.tgz#750e3db5862087b4737ebac8207ffd1ef27b25fc"

View File

@@ -124,6 +124,7 @@
onerror="window.location='{% url 'media_failure' %}?filename=netbox-print.css'"
/>
<link rel="icon" type="image/png" href="{% static 'netbox.ico' %}" />
<link rel="apple-touch-icon" type="image/png" href="{% static 'netbox_touch-icon-180.png' %}" />
{# Javascript #}
<script

View File

@@ -59,7 +59,7 @@
</nav>
{% if config.BANNER_TOP %}
<div class="alert alert-info text-center mx-3" role="alert">
<div class="text-center mx-3">
{{ config.BANNER_TOP|safe }}
</div>
{% endif %}
@@ -99,7 +99,7 @@
</div>
{% if config.BANNER_BOTTOM %}
<div class="alert alert-info text-center mx-3" role="alert">
<div class="text-center mx-3">
{{ config.BANNER_BOTTOM|safe }}
</div>
{% endif %}

View File

@@ -1,6 +1,15 @@
{% extends 'generic/object.html' %}
{% load helpers %}
{% load plugins %}
{% load render_table from django_tables2 %}
{% block extra_controls %}
{% if perms.circuits.add_circuit %}
<a href="{% url 'circuits:circuit_add' %}?type={{ object.pk }}" class="btn btn-sm btn-primary">
<span class="mdi mdi-plus-thick" aria-hidden="true"></span> Add Circuit
</a>
{% endif %}
{% endblock extra_controls %}
{% block content %}
<div class="row mb-3">
@@ -39,22 +48,13 @@
<div class="row mb-3">
<div class="col col-md-12">
<div class="card">
<h5 class="card-header">
Circuits
</h5>
<div class="card-body">
{% include 'inc/table.html' with table=circuits_table %}
<h5 class="card-header">Circuits</h5>
<div class="card-body table-responsive">
{% render_table circuits_table 'inc/table.html' %}
{% include 'inc/paginator.html' with paginator=circuits_table.paginator page=circuits_table.page %}
</div>
{% if perms.circuits.add_circuit %}
<div class="card-footer text-end noprint">
<a href="{% url 'circuits:circuit_add' %}?type={{ object.pk }}" class="btn btn-sm btn-primary">
<span class="mdi mdi-plus-thick" aria-hidden="true"></span> Add Circuit
</a>
</div>
{% endif %}
</div>
{% include 'inc/paginator.html' with paginator=circuits_table.paginator page=circuits_table.page %}
{% plugin_full_width_page object %}
</div>
{% plugin_full_width_page object %}
</div>
</div>
{% endblock %}

View File

@@ -2,9 +2,18 @@
{% load static %}
{% load helpers %}
{% load plugins %}
{% load render_table from django_tables2 %}
{% block extra_controls %}
{% if perms.circuits.add_circuit %}
<a href="{% url 'circuits:circuit_add' %}?provider={{ object.pk }}" class="btn btn-sm btn-primary">
<i class="mdi mdi-plus-thick" aria-hidden="true"></i> Add circuit
</a>
{% endif %}
{% endblock extra_controls %}
{% block content %}
<div class="row">
<div class="row mb-3">
<div class="col col-md-6">
<div class="card">
<h5 class="card-header">
@@ -56,28 +65,17 @@
{% include 'inc/panels/contacts.html' %}
{% plugin_right_page object %}
</div>
<div class="col col-md-12">
<div class="card">
<h5 class="card-header">
Circuits
</h5>
<div class="card-body">
{% include 'inc/table.html' with table=circuits_table %}
</div>
{% if perms.circuits.add_circuit %}
<div class="card-footer text-end noprint">
<a href="{% url 'circuits:circuit_add' %}?provider={{ object.pk }}" class="btn btn-sm btn-primary">
<i class="mdi mdi-plus-thick" aria-hidden="true"></i> Add circuit
</a>
</div>
{% endif %}
</div>
{% include 'inc/paginator.html' with paginator=circuits_table.paginator page=circuits_table.page %}
</div>
</div>
<div class="row">
<div class="col col-md-12">
{% plugin_full_width_page object %}
<div class="row mb-3">
<div class="col col-md-12">
<div class="card">
<h5 class="card-header">Circuits</h5>
<div class="card-body table-responsive">
{% render_table circuits_table 'inc/table.html' %}
{% include 'inc/paginator.html' with paginator=circuits_table.paginator page=circuits_table.page %}
</div>
</div>
{% plugin_full_width_page object %}
</div>
</div>
{% endblock %}

View File

@@ -2,6 +2,7 @@
{% load static %}
{% load helpers %}
{% load plugins %}
{% load render_table from django_tables2 %}
{% block breadcrumbs %}
{{ block.super }}
@@ -9,7 +10,7 @@
{% endblock %}
{% block content %}
<div class="row">
<div class="row mb-3">
<div class="col col-md-6">
<div class="card">
<h5 class="card-header">
@@ -43,22 +44,16 @@
{% plugin_right_page object %}
</div>
</div>
<div class="row">
<div class="col col-md-12">
<div class="card">
<h5 class="card-header">
Circuits
</h5>
<div class="card-body">
{% include 'inc/table.html' with table=circuits_table %}
</div>
</div>
<div class="row mb-3">
<div class="col col-md-12">
<div class="card">
<h5 class="card-header">Circuits</h5>
<div class="card-body table-responsive">
{% render_table circuits_table 'inc/table.html' %}
{% include 'inc/paginator.html' with paginator=circuits_table.paginator page=circuits_table.page %}
</div>
</div>
</div>
<div class="row">
<div class="col col-md-12">
{% plugin_full_width_page object %}
</div>
{% plugin_full_width_page object %}
</div>
</div>
{% endblock %}

View File

@@ -8,19 +8,14 @@
{% block content-wrapper %}
<div class="tab-content">
{# Conncetions list #}
{# Connections list #}
<div class="tab-pane show active" id="object-list" role="tabpanel" aria-labelledby="object-list-tab">
{% include 'inc/table_controls.html' %}
{% include 'inc/table_controls_htmx.html' %}
<div class="card">
<div class="card-body">
<div class="table-responsive">
{% render_table table 'inc/table.html' %}
</div>
<div class="card-body" id="object_list">
{% include 'htmx/table.html' %}
</div>
</div>
{% include 'inc/paginator.html' with paginator=table.paginator page=table.page %}
</div>
{# Filter form #}

View File

@@ -1,7 +1,14 @@
{% extends 'dcim/device_component.html' %}
{% extends 'generic/object.html' %}
{% load helpers %}
{% load plugins %}
{% block breadcrumbs %}
{{ block.super }}
<li class="breadcrumb-item">
<a href="{% url 'dcim:device_consoleports' pk=object.device.pk %}">{{ object.device }}</a>
</li>
{% endblock %}
{% block content %}
<div class="row">
<div class="col col-md-6">

View File

@@ -1,7 +1,14 @@
{% extends 'dcim/device_component.html' %}
{% extends 'generic/object.html' %}
{% load helpers %}
{% load plugins %}
{% block breadcrumbs %}
{{ block.super }}
<li class="breadcrumb-item">
<a href="{% url 'dcim:device_consoleserverports' pk=object.device.pk %}">{{ object.device }}</a>
</li>
{% endblock %}
{% block content %}
<div class="row">
<div class="col col-md-6">

View File

@@ -148,6 +148,12 @@
</div>
</div>
{% endif %}
{% include 'inc/panels/custom_fields.html' %}
{% include 'inc/panels/tags.html' %}
{% include 'inc/panels/comments.html' %}
{% plugin_left_page object %}
</div>
<div class="col col-md-6">
<div class="card">
<h5 class="card-header">
Management
@@ -179,31 +185,31 @@
<tr>
<th scope="row">Primary IPv4</th>
<td>
{% if object.primary_ip4 %}
<a href="{% url 'ipam:ipaddress' pk=object.primary_ip4.pk %}">{{ object.primary_ip4.address.ip }}</a>
{% if object.primary_ip4.nat_inside %}
<span>(NAT for {{ object.primary_ip4.nat_inside.address.ip }})</span>
{% elif object.primary_ip4.nat_outside %}
<span>(NAT: {{ object.primary_ip4.nat_outside.address.ip }})</span>
{% endif %}
{% else %}
<span class="text-muted">&mdash;</span>
{% if object.primary_ip4 %}
<a href="{% url 'ipam:ipaddress' pk=object.primary_ip4.pk %}">{{ object.primary_ip4.address.ip }}</a>
{% if object.primary_ip4.nat_inside %}
(NAT for <a href="{{ object.primary_ip4.nat_inside.get_absolute_url }})">{{ object.primary_ip4.nat_inside.address.ip }}</a>)
{% elif object.primary_ip4.nat_outside %}
(NAT: <a href="{{ object.primary_ip4.nat_outside.get_absolute_url }}">{{ object.primary_ip4.nat_outside.address.ip }}</a>)
{% endif %}
{% else %}
<span class="text-muted">&mdash;</span>
{% endif %}
</td>
</tr>
<tr>
<th scope="row">Primary IPv6</th>
<td>
{% if object.primary_ip6 %}
<a href="{% url 'ipam:ipaddress' pk=object.primary_ip6.pk %}">{{ object.primary_ip6.address.ip }}</a>
{% if object.primary_ip6.nat_inside %}
<span>(NAT for {{ object.primary_ip6.nat_inside.address.ip }})</span>
{% elif object.primary_ip6.nat_outside %}
<span>(NAT: {{ object.primary_ip6.nat_outside.address.ip }})</span>
{% endif %}
{% else %}
<span class="text-muted">&mdash;</span>
{% if object.primary_ip6 %}
<a href="{% url 'ipam:ipaddress' pk=object.primary_ip6.pk %}">{{ object.primary_ip6.address.ip }}</a>
{% if object.primary_ip6.nat_inside %}
(NAT for <a href="{{ object.primary_ip6.nat_inside.get_absolute_url }}">{{ object.primary_ip6.nat_inside.address.ip }}</a>)
{% elif object.primary_ip6.nat_outside %}
(NAT: <a href="{{ object.primary_ip6.nat_outside.get_absolute_url }}">{{ object.primary_ip6.nat_outside.address.ip }}</a>)
{% endif %}
{% else %}
<span class="text-muted">&mdash;</span>
{% endif %}
</td>
</tr>
{% if object.cluster %}
@@ -220,12 +226,6 @@
</table>
</div>
</div>
{% include 'inc/panels/custom_fields.html' %}
{% include 'inc/panels/tags.html' %}
{% include 'inc/panels/comments.html' %}
{% plugin_left_page object %}
</div>
<div class="col col-md-6">
{% if object.powerports.exists and object.poweroutlets.exists %}
<div class="card">
<h5 class="card-header">
@@ -290,7 +290,7 @@
</div>
{% if perms.ipam.add_service %}
<div class="card-footer text-end noprint">
<a href="{% url 'dcim:device_service_assign' device=object.pk %}" class="btn btn-sm btn-primary">
<a href="{% url 'ipam:service_add' %}?device={{ object.pk }}" class="btn btn-sm btn-primary">
<span class="mdi mdi-plus-thick" aria-hidden="true"></span> Assign Service
</a>
</div>
@@ -298,39 +298,6 @@
</div>
{% include 'inc/panels/contacts.html' %}
{% include 'inc/panels/image_attachments.html' %}
<div class="card noprint">
<h5 class="card-header">
Related Devices
</h5>
<div class="card-body">
{% if related_devices %}
<table class="table table-hover">
<tr>
<th>Device</th>
<th>Rack</th>
<th>Type</th>
</tr>
{% for rd in related_devices %}
<tr>
<td>
<a href="{% url 'dcim:device' pk=rd.pk %}">{{ rd }}</a>
</td>
<td>
{% if rd.rack %}
<a href="{% url 'dcim:rack' pk=rd.rack.pk %}">{{ rd.rack }}</a>
{% else %}
<span class="text-muted">&mdash;</span>
{% endif %}
</td>
<td>{{ rd.device_type }}</td>
</tr>
{% endfor %}
</table>
{% else %}
<div class="text-muted">None</div>
{% endif %}
</div>
</div>
{% plugin_right_page object %}
</div>
</div>

View File

@@ -6,8 +6,14 @@
{% block content %}
<form method="post">
{% csrf_token %}
{% include 'inc/table_controls.html' with table_modal="DeviceConsolePortTable_config" %}
{% render_table table 'inc/table.html' %}
{% include 'inc/table_controls_htmx.html' with table_modal="DeviceConsolePortTable_config" %}
<div class="card">
<div class="card-body" id="object_list">
{% include 'htmx/table.html' %}
</div>
</div>
<div class="noprint bulk-buttons">
<div class="bulk-button-group">
{% if perms.dcim.change_consoleport %}
@@ -36,6 +42,5 @@
{% endif %}
</div>
</form>
{% include 'inc/paginator.html' with paginator=table.paginator page=table.page %}
{% table_config_form table %}
{% endblock %}

View File

@@ -6,8 +6,14 @@
{% block content %}
<form method="post">
{% csrf_token %}
{% include 'inc/table_controls.html' with table_modal="DeviceConsoleServerPortTable_config" %}
{% render_table table 'inc/table.html' %}
{% include 'inc/table_controls_htmx.html' with table_modal="DeviceConsoleServerPortTable_config" %}
<div class="card">
<div class="card-body" id="object_list">
{% include 'htmx/table.html' %}
</div>
</div>
<div class="noprint bulk-buttons">
<div class="bulk-button-group">
{% if perms.dcim.change_consoleserverport %}
@@ -36,6 +42,5 @@
{% endif %}
</div>
</form>
{% include 'inc/paginator.html' with paginator=table.paginator page=table.page %}
{% table_config_form table %}
{% endblock %}

View File

@@ -6,8 +6,14 @@
{% block content %}
<form method="post">
{% csrf_token %}
{% include 'inc/table_controls.html' with table_modal="DeviceDeviceBayTable_config" %}
{% render_table table 'inc/table.html' %}
{% include 'inc/table_controls_htmx.html' with table_modal="DeviceDeviceBayTable_config" %}
<div class="card">
<div class="card-body" id="object_list">
{% include 'htmx/table.html' %}
</div>
</div>
<div class="noprint bulk-buttons">
<div class="bulk-button-group">
{% if perms.dcim.change_devicebay %}
@@ -33,6 +39,5 @@
{% endif %}
</div>
</form>
{% include 'inc/paginator.html' with paginator=table.paginator page=table.page %}
{% table_config_form table %}
{% endblock %}

View File

@@ -6,8 +6,14 @@
{% block content %}
<form method="post">
{% csrf_token %}
{% include 'inc/table_controls.html' with table_modal="DeviceFrontPortTable_config" %}
{% render_table table 'inc/table.html' %}
{% include 'inc/table_controls_htmx.html' with table_modal="DeviceFrontPortTable_config" %}
<div class="card">
<div class="card-body" id="object_list">
{% include 'htmx/table.html' %}
</div>
</div>
<div class="noprint bulk-buttons">
<div class="bulk-button-group">
{% if perms.dcim.change_frontport %}
@@ -36,6 +42,5 @@
{% endif %}
</div>
</form>
{% include 'inc/paginator.html' with paginator=table.paginator page=table.page %}
{% table_config_form table %}
{% endblock %}

View File

@@ -9,7 +9,15 @@
<div class="row mb-3 justify-content-between">
<div class="col col-12 col-lg-4 my-3 my-lg-0 d-flex noprint table-controls">
<div class="input-group input-group-sm">
<input type="text" class="form-control interface-filter" placeholder="Filter" title="Filter text (regular expressions supported)" />
<input
type="text"
name="q"
class="form-control"
placeholder="Quick search"
hx-get="{{ request.full_path }}"
hx-target="#object_list"
hx-trigger="keyup changed delay:500ms"
/>
</div>
</div>
<div class="col col-md-3 mb-0 d-flex noprint table-controls">
@@ -34,7 +42,13 @@
</div>
</div>
</div>
{% render_table table 'inc/table.html' %}
<div class="card">
<div class="card-body" id="object_list">
{% include 'htmx/table.html' %}
</div>
</div>
<div class="noprint bulk-buttons">
<div class="bulk-button-group">
{% if perms.dcim.change_interface %}
@@ -63,6 +77,5 @@
{% endif %}
</div>
</form>
{% include 'inc/paginator.html' with paginator=table.paginator page=table.page %}
{% table_config_form table %}
{% endblock %}

View File

@@ -6,8 +6,14 @@
{% block content %}
<form method="post">
{% csrf_token %}
{% include 'inc/table_controls.html' with table_modal="DeviceInventoryItemTable_config" %}
{% render_table table 'inc/table.html' %}
{% include 'inc/table_controls_htmx.html' with table_modal="DeviceInventoryItemTable_config" %}
<div class="card">
<div class="card-body" id="object_list">
{% include 'htmx/table.html' %}
</div>
</div>
<div class="noprint bulk-buttons">
<div class="bulk-button-group">
{% if perms.dcim.change_inventoryitem %}
@@ -33,6 +39,5 @@
{% endif %}
</div>
</form>
{% include 'inc/paginator.html' with paginator=table.paginator page=table.page %}
{% table_config_form table %}
{% endblock %}

View File

@@ -31,12 +31,12 @@
<tbody>
{% for iface in interfaces %}
<tr id="{{ iface.name }}">
<td class="font-monospace">{{ iface }}</td>
<td>{{ iface }}</td>
{% if iface.connected_endpoint.device %}
<td class="configured_device" data="{{ iface.connected_endpoint.device }}" data-chassis="{{ iface.connected_endpoint.device.virtual_chassis.name }}">
<td class="configured_device" data="{{ iface.connected_endpoint.device.name }}" data-chassis="{{ iface.connected_endpoint.device.virtual_chassis.name }}">
<a href="{% url 'dcim:device' pk=iface.connected_endpoint.device.pk %}">{{ iface.connected_endpoint.device }}</a>
</td>
<td class="configured_interface" data="{{ iface.connected_endpoint }}">
<td class="configured_interface" data="{{ iface.connected_endpoint.name }}">
<span title="{{ iface.connected_endpoint.get_type_display }}">{{ iface.connected_endpoint }}</span>
</td>
{% elif iface.connected_endpoint.circuit %}

View File

@@ -6,8 +6,14 @@
{% block content %}
<form method="post">
{% csrf_token %}
{% include 'inc/table_controls.html' with table_modal="DevicePowerOutletTable_config" %}
{% render_table table 'inc/table.html' %}
{% include 'inc/table_controls_htmx.html' with table_modal="DevicePowerOutletTable_config" %}
<div class="card">
<div class="card-body" id="object_list">
{% include 'htmx/table.html' %}
</div>
</div>
<div class="noprint bulk-buttons">
<div class="bulk-button-group">
{% if perms.dcim.change_powerport %}
@@ -36,6 +42,5 @@
{% endif %}
</div>
</form>
{% include 'inc/paginator.html' with paginator=table.paginator page=table.page %}
{% table_config_form table %}
{% endblock %}

View File

@@ -6,8 +6,14 @@
{% block content %}
<form method="post">
{% csrf_token %}
{% include 'inc/table_controls.html' with table_modal="DevicePowerPortTable_config" %}
{% render_table table 'inc/table.html' %}
{% include 'inc/table_controls_htmx.html' with table_modal="DevicePowerPortTable_config" %}
<div class="card">
<div class="card-body" id="object_list">
{% include 'htmx/table.html' %}
</div>
</div>
<div class="noprint bulk-buttons">
<div class="bulk-button-group">
{% if perms.dcim.change_powerport %}
@@ -36,6 +42,5 @@
{% endif %}
</div>
</form>
{% include 'inc/paginator.html' with paginator=table.paginator page=table.page %}
{% table_config_form table %}
{% endblock %}

View File

@@ -6,8 +6,14 @@
{% block content %}
<form method="post">
{% csrf_token %}
{% include 'inc/table_controls.html' with table_modal="DeviceRearPortTable_config" %}
{% render_table table 'inc/table.html' %}
{% include 'inc/table_controls_htmx.html' with table_modal="DeviceRearPortTable_config" %}
<div class="card">
<div class="card-body" id="object_list">
{% include 'htmx/table.html' %}
</div>
</div>
<div class="noprint bulk-buttons">
<div class="bulk-button-group">
{% if perms.dcim.change_rearport %}
@@ -36,6 +42,5 @@
{% endif %}
</div>
</form>
{% include 'inc/paginator.html' with paginator=table.paginator page=table.page %}
{% table_config_form table %}
{% endblock %}

View File

@@ -1,9 +0,0 @@
{% extends 'generic/object.html' %}
{% load helpers %}
{% load perms %}
{% load plugins %}
{% block breadcrumbs %}
{{ block.super }}
<li class="breadcrumb-item"><a href="{% url object|viewname:'list' %}?device_id={{ object.device.pk }}">{{ object.device }}</a></li>
{% endblock %}

View File

@@ -1,7 +1,14 @@
{% extends 'dcim/device_component.html' %}
{% extends 'generic/object.html' %}
{% load helpers %}
{% load plugins %}
{% block breadcrumbs %}
{{ block.super }}
<li class="breadcrumb-item">
<a href="{% url 'dcim:device_devicebays' pk=object.device.pk %}">{{ object.device }}</a>
</li>
{% endblock %}
{% block content %}
<div class="row">
<div class="col col-md-6">

View File

@@ -1,11 +1,20 @@
{% extends 'generic/object.html' %}
{% load helpers %}
{% load plugins %}
{% load render_table from django_tables2 %}
{% block breadcrumbs %}
<li class="breadcrumb-item"><a href="{% url 'dcim:devicerole_list' %}">Device Roles</a></li>
{% endblock %}
{% block extra_controls %}
{% if perms.dcim.add_device %}
<a href="{% url 'dcim:device_add' %}?device_role={{ object.pk }}" class="btn btn-sm btn-primary">
<span class="mdi mdi-plus-thick" aria-hidden="true"></span> Add Device
</a>
{% endif %}
{% endblock extra_controls %}
{% block content %}
<div class="row mb-3">
<div class="col col-md-6">
@@ -69,21 +78,12 @@
<div class="row mb-3">
<div class="col col-md-12">
<div class="card">
<h5 class="card-header">
Devices
</h5>
<div class="card-body">
{% include 'inc/table.html' with table=devices_table %}
<h5 class="card-header">Devices</h5>
<div class="card-body table-responsive">
{% render_table devices_table 'inc/table.html' %}
{% include 'inc/paginator.html' with paginator=devices_table.paginator page=devices_table.page %}
</div>
{% if perms.dcim.add_device %}
<div class="card-footer text-end noprint">
<a href="{% url 'dcim:device_add' %}?device_role={{ object.pk }}" class="btn btn-sm btn-primary">
<span class="mdi mdi-plus-thick" aria-hidden="true"></span> Add Device
</a>
</div>
{% endif %}
</div>
{% include 'inc/paginator.html' with paginator=devices_table.paginator page=devices_table.page %}
{% plugin_full_width_page object %}
</div>
</div>

View File

@@ -7,11 +7,9 @@
<form method="post">
{% csrf_token %}
<div class="card">
<h5 class="card-header">
{{ title }}
</h5>
<div class="card-body table-responsive">
{% render_table table 'inc/table.html' %}
<h5 class="card-header">{{ title }}</h5>
<div class="card-body" id="object_list">
{% include 'htmx/table.html' %}
</div>
<div class="card-footer noprint">
{% if table.rows %}
@@ -37,12 +35,10 @@
</form>
{% else %}
<div class="card">
<h5 class="card-header">
{{ title }}
</h5>
<div class="card-body table-responsive">
{% render_table table 'inc/table.html' %}
</div>
<h5 class="card-header">{{ title }}</h5>
<div class="card-body" id="object_list">
{% include 'htmx/table.html' %}
</div>
</div>
{% endif %}
{% endblock content %}

View File

@@ -1,7 +1,14 @@
{% extends 'dcim/device_component.html' %}
{% extends 'generic/object.html' %}
{% load helpers %}
{% load plugins %}
{% block breadcrumbs %}
{{ block.super }}
<li class="breadcrumb-item">
<a href="{% url 'dcim:device_frontports' pk=object.device.pk %}">{{ object.device }}</a>
</li>
{% endblock %}
{% block content %}
<div class="row">
<div class="col col-md-6">

View File

@@ -1,8 +1,15 @@
{% extends 'dcim/device_component.html' %}
{% extends 'generic/object.html' %}
{% load helpers %}
{% load plugins %}
{% load render_table from django_tables2 %}
{% block breadcrumbs %}
{{ block.super }}
<li class="breadcrumb-item">
<a href="{% url 'dcim:device_interfaces' pk=object.device.pk %}">{{ object.device }}</a>
</li>
{% endblock %}
{% block extra_controls %}
{% if perms.dcim.add_interface and not object.is_virtual %}
<a href="{% url 'dcim:interface_add' %}?device={{ object.device.pk }}&parent={{ object.pk }}&return_url={{ object.get_absolute_url }}" class="btn btn-sm btn-success">
@@ -450,7 +457,7 @@
<h5 class="card-header">
IP Addresses
</h5>
<div class="card-body">
<div class="card-body table-responsive">
{% if ipaddress_table.rows %}
{% render_table ipaddress_table 'inc/table.html' %}
{% else %}

View File

@@ -1,7 +1,14 @@
{% extends 'dcim/device_component.html' %}
{% extends 'generic/object.html' %}
{% load helpers %}
{% load plugins %}
{% block breadcrumbs %}
{{ block.super }}
<li class="breadcrumb-item">
<a href="{% url 'dcim:device_inventory' pk=object.device.pk %}">{{ object.device }}</a>
</li>
{% endblock %}
{% block content %}
<div class="row mb-3">
<div class="col col-md-6">

View File

@@ -1,6 +1,7 @@
{% extends 'generic/object.html' %}
{% load helpers %}
{% load plugins %}
{% load render_table from django_tables2 %}
{% block breadcrumbs %}
{{ block.super }}
@@ -9,6 +10,14 @@
{% endfor %}
{% endblock %}
{% block extra_controls %}
{% if perms.dcim.add_location %}
<a href="{% url 'dcim:location_add' %}?site={{ object.site.pk }}&parent={{ object.pk }}" class="btn btn-sm btn-primary">
<span class="mdi mdi-plus-thick" aria-hidden="true"></span> Add Child Location
</a>
{% endif %}
{% endblock extra_controls %}
{% block content %}
<div class="row mb-3">
<div class="col col-md-6">
@@ -88,22 +97,13 @@
<div class="row mb-3">
<div class="col col-md-12">
<div class="card">
<h5 class="card-header">
Locations
</h5>
<div class="card-body">
{% include 'inc/table.html' with table=child_locations_table %}
<h5 class="card-header">Locations</h5>
<div class="card-body table-responsive">
{% render_table child_locations_table 'inc/table.html' %}
{% include 'inc/paginator.html' with paginator=child_locations_table.paginator page=child_locations_table.page %}
</div>
{% if perms.dcim.add_location %}
<div class="card-footer text-end noprint">
<a href="{% url 'dcim:location_add' %}?site={{ object.site.pk }}&parent={{ object.pk }}" class="btn btn-sm btn-primary">
<span class="mdi mdi-plus-thick" aria-hidden="true"></span> Add Location
</a>
</div>
{% endif %}
</div>
{% include 'inc/paginator.html' with paginator=child_locations_table.paginator page=child_locations_table.page %}
{% plugin_full_width_page object %}
</div>
{% plugin_full_width_page object %}
</div>
</div>
{% endblock %}

View File

@@ -1,6 +1,15 @@
{% extends 'generic/object.html' %}
{% load helpers %}
{% load plugins %}
{% load render_table from django_tables2 %}
{% block extra_controls %}
{% if perms.dcim.add_devicetype %}
<a href="{% url 'dcim:devicetype_add' %}?manufacturer={{ object.pk }}" class="btn btn-sm btn-primary">
<span class="mdi mdi-plus-thick" aria-hidden="true"></span> Add Device Type
</a>
{% endif %}
{% endblock extra_controls %}
{% block content %}
<div class="row mb-3">
@@ -46,21 +55,12 @@
<div class="row mb-3">
<div class="col col-md-12">
<div class="card">
<h5 class="card-header">
Device Types
</h5>
<div class="card-body">
{% include 'inc/table.html' with table=devicetypes_table %}
<h5 class="card-header">Device Types</h5>
<div class="card-body table-responsive">
{% render_table devicetypes_table 'inc/table.html' %}
{% include 'inc/paginator.html' with paginator=devicetypes_table.paginator page=devicetypes_table.page %}
</div>
{% if perms.dcim.add_devicetype %}
<div class="card-footer text-end noprint">
<a href="{% url 'dcim:devicetype_add' %}?manufacturer={{ object.pk }}" class="btn btn-sm btn-primary">
<span class="mdi mdi-plus-thick" aria-hidden="true"></span> Add device type
</a>
</div>
{% endif %}
</div>
{% include 'inc/paginator.html' with paginator=devicetypes_table.paginator page=devicetypes_table.page %}
{% plugin_full_width_page object %}
</div>
</div>

View File

@@ -1,6 +1,7 @@
{% extends 'generic/object.html' %}
{% load helpers %}
{% load plugins %}
{% load render_table from django_tables2 %}
{% block breadcrumbs %}
{{ block.super }}
@@ -9,6 +10,14 @@
{% endif %}
{% endblock %}
{% block extra_controls %}
{% if perms.dcim.add_device %}
<a href="{% url 'dcim:device_add' %}?device_role={{ object.pk }}" class="btn btn-sm btn-primary">
<span class="mdi mdi-plus-thick" aria-hidden="true"></span> Add Device
</a>
{% endif %}
{% endblock extra_controls %}
{% block content %}
<div class="row mb-3">
<div class="col col-md-6">
@@ -74,22 +83,13 @@
<div class="row mb-3">
<div class="col col-md-12">
<div class="card">
<h5 class="card-header">
Devices
</h5>
<div class="card-body">
{% include 'inc/table.html' with table=devices_table %}
<h5 class="card-header">Devices</h5>
<div class="card-body table-responsive">
{% render_table devices_table 'inc/table.html' %}
{% include 'inc/paginator.html' with paginator=devices_table.paginator page=devices_table.page %}
</div>
{% if perms.dcim.add_device %}
<div class="card-footer text-end noprint">
<a href="{% url 'dcim:device_add' %}?device_role={{ object.pk }}" class="btn btn-sm btn-primary">
<span class="mdi mdi-plus-thick" aria-hidden="true"></span> Add Device
</a>
</div>
{% endif %}
</div>
{% include 'inc/paginator.html' with paginator=devices_table.paginator page=devices_table.page %}
{% plugin_full_width_page object %}
</div>
{% plugin_full_width_page object %}
</div>
</div>
{% endblock %}

View File

@@ -1,7 +1,14 @@
{% extends 'dcim/device_component.html' %}
{% extends 'generic/object.html' %}
{% load helpers %}
{% load plugins %}
{% block breadcrumbs %}
{{ block.super }}
<li class="breadcrumb-item">
<a href="{% url 'dcim:device_poweroutlets' pk=object.device.pk %}">{{ object.device }}</a>
</li>
{% endblock %}
{% block content %}
<div class="row mb-3">
<div class="col col-md-6">

View File

@@ -54,7 +54,7 @@
<form method="post">
{% csrf_token %}
<div class="card">
<div class="card-body">
<div class="card-body table-responsive">
{% render_table powerfeed_table 'inc/table.html' %}
</div>
<div class="card-footer noprint">

View File

@@ -1,7 +1,14 @@
{% extends 'dcim/device_component.html' %}
{% extends 'generic/object.html' %}
{% load helpers %}
{% load plugins %}
{% block breadcrumbs %}
{{ block.super }}
<li class="breadcrumb-item">
<a href="{% url 'dcim:device_powerports' pk=object.device.pk %}">{{ object.device }}</a>
</li>
{% endblock %}
{% block content %}
<div class="row mb-3">
<div class="col col-md-6">

View File

@@ -1,6 +1,15 @@
{% extends 'generic/object.html' %}
{% load helpers %}
{% load plugins %}
{% load render_table from django_tables2 %}
{% block extra_controls %}
{% if perms.dcim.add_rack %}
<a href="{% url 'dcim:rack_add' %}?role={{ object.pk }}" class="btn btn-sm btn-primary">
<span class="mdi mdi-plus-thick" aria-hidden="true"></span> Add Rack
</a>
{% endif %}
{% endblock extra_controls %}
{% block content %}
<div class="row mb-3">
@@ -45,21 +54,12 @@
<div class="row mb-3">
<div class="col col-md-12">
<div class="card">
<h5 class="card-header">
Racks
</h5>
<div class="card-body">
{% include 'inc/table.html' with table=racks_table %}
<h5 class="card-header">Racks</h5>
<div class="card-body table-responsive">
{% render_table racks_table 'inc/table.html' %}
{% include 'inc/paginator.html' with paginator=racks_table.paginator page=racks_table.page %}
</div>
{% if perms.dcim.add_rack %}
<div class="card-footer text-end noprint">
<a href="{% url 'dcim:rack_add' %}?role={{ object.pk }}" class="btn btn-sm btn-primary">
<span class="mdi mdi-plus-thick" aria-hidden="true"></span> Add Rack
</a>
</div>
{% endif %}
</div>
{% include 'inc/paginator.html' with paginator=racks_table.paginator page=racks_table.page %}
{% plugin_full_width_page object %}
</div>
</div>

View File

@@ -1,7 +1,14 @@
{% extends 'dcim/device_component.html' %}
{% extends 'generic/object.html' %}
{% load helpers %}
{% load plugins %}
{% block breadcrumbs %}
{{ block.super }}
<li class="breadcrumb-item">
<a href="{% url 'dcim:device_rearports' pk=object.device.pk %}">{{ object.device }}</a>
</li>
{% endblock %}
{% block content %}
<div class="row">
<div class="col col-md-6">

View File

@@ -1,6 +1,7 @@
{% extends 'generic/object.html' %}
{% load helpers %}
{% load plugins %}
{% load render_table from django_tables2 %}
{% block breadcrumbs %}
{{ block.super }}
@@ -9,6 +10,14 @@
{% endfor %}
{% endblock %}
{% block extra_controls %}
{% if perms.dcim.add_site %}
<a href="{% url 'dcim:site_add' %}?region={{ object.pk }}" class="btn btn-sm btn-primary">
<span class="mdi mdi-plus-thick" aria-hidden="true"></span> Add Site
</a>
{% endif %}
{% endblock extra_controls %}
{% block content %}
<div class="row mb-3">
<div class="col col-md-6">
@@ -55,8 +64,8 @@
<h5 class="card-header">
Child Regions
</h5>
<div class="card-body">
{% include 'inc/table.html' with table=child_regions_table %}
<div class="card-body table-responsive">
{% render_table child_regions_table 'inc/table.html' %}
</div>
{% if perms.dcim.add_region %}
<div class="card-footer text-end noprint">
@@ -69,25 +78,16 @@
{% plugin_right_page object %}
</div>
</div>
<div class="row">
<div class="row mb-3">
<div class="col col-md-12">
<div class="card">
<h5 class="card-header">
Sites
</h5>
<div class="card-body">
{% include 'inc/table.html' with table=sites_table %}
<h5 class="card-header">Sites</h5>
<div class="card-body table-responsive">
{% render_table sites_table 'inc/table.html' %}
{% include 'inc/paginator.html' with paginator=sites_table.paginator page=sites_table.page %}
</div>
{% if perms.dcim.add_site %}
<div class="card-footer text-end noprint">
<a href="{% url 'dcim:site_add' %}?region={{ object.pk }}" class="btn btn-sm btn-primary">
<span class="mdi mdi-plus-thick" aria-hidden="true"></span> Add Site
</a>
</div>
{% endif %}
</div>
{% include 'inc/paginator.html' with paginator=sites_table.paginator page=sites_table.page %}
{% plugin_full_width_page object %}
</div>
{% plugin_full_width_page object %}
</div>
</div>
{% endblock %}

View File

@@ -1,6 +1,7 @@
{% extends 'generic/object.html' %}
{% load helpers %}
{% load plugins %}
{% load render_table from django_tables2 %}
{% block breadcrumbs %}
{{ block.super }}
@@ -9,6 +10,14 @@
{% endfor %}
{% endblock %}
{% block extra_controls %}
{% if perms.dcim.add_site %}
<a href="{% url 'dcim:site_add' %}?group={{ object.pk }}" class="btn btn-sm btn-primary">
<span class="mdi mdi-plus-thick" aria-hidden="true"></span> Add Site
</a>
{% endif %}
{% endblock extra_controls %}
{% block content %}
<div class="row mb-3">
<div class="col col-md-6">
@@ -55,8 +64,8 @@
<h5 class="card-header">
Child Groups
</h5>
<div class="card-body">
{% include 'inc/table.html' with table=child_groups_table %}
<div class="card-body table-responsive">
{% render_table child_groups_table 'inc/table.html' %}
</div>
{% if perms.dcim.add_sitegroup %}
<div class="card-footer text-end noprint">
@@ -72,21 +81,12 @@
<div class="row mb-3">
<div class="col col-md-12">
<div class="card">
<h5 class="card-header">
Sites
</h5>
<div class="card-body">
{% include 'inc/table.html' with table=sites_table %}
<h5 class="card-header">Sites</h5>
<div class="card-body table-responsive">
{% render_table sites_table 'inc/table.html' %}
{% include 'inc/paginator.html' with paginator=sites_table.paginator page=sites_table.page %}
</div>
{% if perms.dcim.add_site %}
<div class="card-footer text-end noprint">
<a href="{% url 'dcim:site_add' %}?group={{ object.pk }}" class="btn btn-sm btn-primary">
<span class="mdi mdi-plus-thick" aria-hidden="true"></span> Add Site
</a>
</div>
{% endif %}
</div>
{% include 'inc/paginator.html' with paginator=sites_table.paginator page=sites_table.page %}
{% plugin_full_width_page object %}
</div>
</div>

View File

@@ -2,9 +2,17 @@
{% load render_table from django_tables2 %}
{% block content %}
{% render_table table 'inc/table.html' %}
{% include 'inc/paginator.html' with paginator=table.paginator page=table.page %}
<div class="text-muted">
<div class="row mb-3">
<div class="col col-md-12">
<div class="card">
<div class="card-body table-responsive">
{% render_table table 'inc/table.html' %}
{% include 'inc/paginator.html' with paginator=table.paginator page=table.page %}
</div>
</div>
<div class="text-muted">
Change log retention: {% if settings.CHANGELOG_RETENTION %}{{ settings.CHANGELOG_RETENTION }} days{% else %}Indefinite{% endif %}
</div>
</div>
</div>
{% endblock %}

View File

@@ -24,6 +24,10 @@
</div>
</form>
{% endif %}
{% render_table table 'inc/table.html' %}
{% include 'inc/paginator.html' with paginator=table.paginator page=table.page %}
<div class="card">
<div class="card-body table-responsive">
{% render_table table 'inc/table.html' %}
{% include 'inc/paginator.html' with paginator=table.paginator page=table.page %}
</div>
</div>
{% endblock %}

View File

@@ -1,6 +1,7 @@
{% extends 'generic/object.html' %}
{% load helpers %}
{% load plugins %}
{% load render_table from django_tables2 %}
{% block content %}
<div class="row">
@@ -63,12 +64,18 @@
</table>
</div>
</div>
</div>
<div class="row">
<div class="col">
{% include 'inc/panel_table.html' with table=taggeditem_table heading='Tagged Objects' %}
{% include 'inc/paginator.html' with paginator=taggeditem_table.paginator page=items_table.page %}
</div>
</div>
{% plugin_full_width_page object %}
<div class="row">
<div class="col col-md-12">
<div class="card">
<h5 class="card-header">Tagged Objects</h5>
<div class="card-body table-responsive">
{% render_table taggeditem_table 'inc/table.html' %}
{% include 'inc/paginator.html' with paginator=taggeditem_table.paginator page=taggeditem_table.page %}
</div>
</div>
{% plugin_full_width_page object %}
</div>
</div>
{% endblock %}

View File

@@ -1,40 +1,73 @@
{% extends 'base/layout.html' %}
{% load helpers %}
{% load form_helpers %}
{% load render_table from django_tables2 %}
{% block title %}Add {{ model_name|title }}{% endblock %}
{% block content %}
<p>{{ table.rows|length }} {{ parent_model_name }} selected</p>
<form action="." method="post" class="form form-horizontal">
{% csrf_token %}
{% if request.POST.return_url %}
<input type="hidden" name="return_url" value="{{ request.POST.return_url }}" />
{% endif %}
{% for field in form.hidden_fields %}
{{ field }}
{% endfor %}
<div class="row">
<div class="col col-md-7">
<div class="card">
{% include 'inc/table.html' %}
{% block tabs %}
<ul class="nav nav-tabs px-3">
<li class="nav-item" role="presentation">
<button class="nav-link active" id="component-form-tab" data-bs-toggle="tab" data-bs-target="#component-form" type="button" role="tab" aria-controls="component-form" aria-selected="true">
Bulk Creation
</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="object-list-tab" data-bs-toggle="tab" data-bs-target="#object-list" type="button" role="tab" aria-controls="object-list" aria-selected="false">
Selected Objects
{% badge table.rows|length %}
</button>
</li>
</ul>
{% endblock %}
{% block content-wrapper %}
<div class="tab-content">
{% block content %}
{# Component creation form #}
<div class="tab-pane show active" id="component-form" role="tabpanel" aria-labelledby="component-form-tab">
<form action="" method="post" class="form form-horizontal">
{% csrf_token %}
{% if request.POST.return_url %}
<input type="hidden" name="return_url" value="{{ request.POST.return_url }}" />
{% endif %}
{% for field in form.hidden_fields %}
{{ field }}
{% endfor %}
<div class="row">
<div class="col col-md-12 col-lg-10 offset-lg-1">
<div class="card">
<h5 class="card-header">{{ model_name|title }} to Add</h5>
<div class="card-body">
{% for field in form.visible_fields %}
{% render_field field %}
{% endfor %}
</div>
</div>
<div class="form-group text-end">
<div class="col col-md-12">
<a href="{{ return_url }}" class="btn btn-outline-danger">Cancel</a>
<button type="submit" name="_create" class="btn btn-primary">Create</button>
</div>
</div>
</div>
</div>
</form>
</div>
{# Selected objects list #}
<div class="tab-pane" id="object-list" role="tabpanel" aria-labelledby="object-list-tab">
<div class="card">
<div class="card-body table-responsive">
{% render_table table 'inc/table.html' %}
</div>
</div>
<div class="col col-md-5">
<div class="card">
<h5 class="card-header">{{ model_name|title }} to Add</h5>
<div class="card-body">
{% for field in form.visible_fields %}
{% render_field field %}
{% endfor %}
</div>
</div>
<div class="form-group text-end">
<div class="col col-md-12">
<a href="{{ return_url }}" class="btn btn-outline-danger">Cancel</a>
<button type="submit" name="_create" class="btn btn-primary">Create</button>
</div>
</div>
</div>
</div>
</form>
{% endblock content %}
</div>
{% endblock %}
</div>
{% endblock %}

View File

@@ -1,5 +1,6 @@
{% extends 'base/layout.html' %}
{% load helpers %}
{% load render_table from django_tables2 %}
{% block title %}Delete {{ table.rows|length }} {{ obj_type_plural|bettertitle }}?{% endblock %}
@@ -15,7 +16,9 @@
</div>
</div>
<div class="container-xl px-0">
{% include 'inc/table.html' %}
<div class="table-responsive">
{% render_table table 'inc/table.html' %}
</div>
<div class="row mt-3">
<form action="" method="post">
{% csrf_token %}

View File

@@ -1,6 +1,7 @@
{% extends 'base/layout.html' %}
{% load helpers %}
{% load form_helpers %}
{% load render_table from django_tables2 %}
{% block title %}Editing {{ table.rows|length }} {{ obj_type_plural|bettertitle }}{% endblock %}
@@ -38,14 +39,17 @@
<div class="row">
<div class="col col-md-12 col-lg-10 offset-lg-1">
{% for field in form.visible_fields %}
{% if field.name in form.nullable_fields %}
<div class="card">
<div class="card-body">
{% for field in form.visible_fields %}
{% if field.name in form.nullable_fields %}
{% render_field field bulk_nullable=True %}
{% else %}
{% else %}
{% render_field field %}
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
</div>
</div>
<div class="text-end">
<a href="{{ return_url }}" class="btn btn-sm btn-outline-danger">Cancel</a>
@@ -59,7 +63,11 @@
{# Selected objects list #}
<div class="tab-pane" id="object-list" role="tabpanel" aria-labelledby="object-list-tab">
{% include 'inc/table.html' %}
<div class="card">
<div class="card-body table-responsive">
{% render_table table 'inc/table.html' %}
</div>
</div>
</div>
{% endblock %}

View File

@@ -1,5 +1,6 @@
{% extends 'base/layout.html' %}
{% load helpers %}
{% load render_table from django_tables2 %}
{% block title %}Remove {{ table.rows|length }} {{ obj_type_plural|bettertitle }}?{% endblock %}
@@ -13,7 +14,9 @@
</div>
</div>
<div class="container-xl px-0">
{% include 'inc/table.html' %}
<div class="table-responsive">
{% render_table table 'inc/table.html' %}
</div>
<form action="." method="post" class="form">
{% csrf_token %}
{% for field in form.hidden_fields %}

View File

@@ -87,7 +87,7 @@
{% endif %}
{# Object table controls #}
{% include 'inc/table_controls.html' with table_modal="ObjectTable_config" %}
{% include 'inc/table_controls_htmx.html' with table_modal="ObjectTable_config" %}
<form method="post" class="form form-horizontal">
{% csrf_token %}
@@ -95,10 +95,8 @@
{# Object table #}
<div class="card">
<div class="card-body">
<div class="table-responsive">
{% render_table table 'inc/table.html' %}
</div>
<div class="card-body" id="object_list">
{% include 'htmx/table.html' %}
</div>
</div>
@@ -125,8 +123,6 @@
</form>
{# Paginator #}
{% include 'inc/paginator.html' with paginator=table.paginator page=table.page %}
</div>
{# Filter form #}

View File

@@ -0,0 +1,5 @@
{# Render an HTMX-enabled table with paginator #}
{% load render_table from django_tables2 %}
{% render_table table 'inc/table_htmx.html' %}
{% include 'inc/paginator_htmx.html' with paginator=table.paginator page=table.page %}

View File

@@ -1,51 +1,52 @@
{% load helpers %}
<div class="paginator float-end text-end">
<div class="row">
<div class="col col-md-6 mb-0">
{# Page number carousel #}
{% if paginator.num_pages > 1 %}
<div class="btn-group btn-group-sm mb-3" role="group" aria-label="Pages">
{% if page.has_previous %}
<a href="{% querystring request page=page.previous_page_number %}" class="btn btn-outline-secondary">
<div class="btn-group btn-group-sm mb-3" role="group" aria-label="Pages">
{% if page.has_previous %}
<a href="{% querystring request page=page.previous_page_number %}" class="btn btn-outline-secondary">
<i class="mdi mdi-chevron-double-left"></i>
</a>
{% endif %}
{% for p in page.smart_pages %}
{% if p %}
<a href="{% querystring request page=p %}" class="btn btn-outline-secondary{% if page.number == p %} active{% endif %}">
{{ p }}
</a>
{% else %}
<button type="button" class="btn btn-outline-secondary" disabled>
<span>&hellip;</span>
</button>
</a>
{% endif %}
{% endfor %}
{% if page.has_next %}
<a href="{% querystring request page=page.next_page_number %}" class="btn btn-outline-secondary">
<i class="mdi mdi-chevron-double-right"></i>
</a>
{% endif %}
</div>
{% endif %}
<form method="get" class="mb-2">
{% for k, v_list in request.GET.lists %}
{% if k != 'per_page' %}
{% for v in v_list %}
<input type="hidden" name="{{ k }}" value="{{ v }}" />
{% endfor %}
{% endif %}
{% for p in page.smart_pages %}
{% if p %}
<a href="{% querystring request page=p %}" class="btn btn-outline-secondary{% if page.number == p %} active{% endif %}">
{{ p }}
</a>
{% else %}
<button type="button" class="btn btn-outline-secondary" disabled>
<span>&hellip;</span>
</button>
{% endif %}
{% endfor %}
<div class="input-group input-group-sm">
<select name="per_page" class="form-select per-page">
{% for n in page.paginator.get_page_lengths %}
<option value="{{ n }}"{% if page.paginator.per_page == n %} selected="selected"{% endif %}>{{ n }}</option>
{% endfor %}
</select>
<label class="input-group-text" for="per_page">Per Page</label>
</div>
</form>
{% if page %}
<small class="text-end text-muted">
Showing {{ page.start_index }}-{{ page.end_index }} of {{ page.paginator.count }}
</small>
{% if page.has_next %}
<a href="{% querystring request page=page.next_page_number %}" class="btn btn-outline-secondary">
<i class="mdi mdi-chevron-double-right"></i>
</a>
{% endif %}
</div>
{% endif %}
</div>
<div class="col col-md-6 mb-0 text-end">
{# Per-page count selector #}
{% if page %}
<div class="dropdown dropup">
<button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
Per Page
</button>
<ul class="dropdown-menu">
{% for n in page.paginator.get_page_lengths %}
<li>
<a href="{% querystring request per_page=n %}" class="dropdown-item">{{ n }}</a>
</li>
{% endfor %}
</ul>
</div>
<small class="text-end text-muted">
Showing {{ page.start_index }}-{{ page.end_index }} of {{ page.paginator.count }}
</small>
{% endif %}
</div>
</div>

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