Skip to content

Forms

Form Classes

NetBox provides several base form classes for use by plugins. Additional form classes are also available for other standard base model classes (PrimaryModel, OrganizationalModel, and NestedGroupModel).

Form Class Purpose
NetBoxModelForm Create/edit individual objects
NetBoxModelImportForm Bulk import objects from CSV data
NetBoxModelBulkEditForm Edit multiple objects simultaneously
NetBoxModelFilterSetForm Filter objects within a list view

NetBoxModelForm

This is the base form for creating and editing NetBox models. It extends Django's ModelForm to add support for tags and custom fields.

Attribute Description
fieldsets A tuple of FieldSet instances which control how form fields are rendered (optional)

Subclasses

The corresponding model-specific subclasses of NetBoxModelForm are documented below.

Model Class Form Class
PrimaryModel PrimaryModelForm
OrganizationalModel OrganizationalModelForm
NestedGroupModel NestedGroupModelForm

Example

from django.utils.translation import gettext_lazy as _
from dcim.models import Site
from netbox.forms import NetBoxModelForm
from utilities.forms.fields import CommentField, DynamicModelChoiceField
from utilities.forms.rendering import FieldSet
from .models import MyModel

class MyModelForm(NetBoxModelForm):
    site = DynamicModelChoiceField(
        queryset=Site.objects.all()
    )
    comments = CommentField()
    fieldsets = (
        FieldSet('name', 'status', 'site', 'tags', name=_('Model Stuff')),
        FieldSet('tenant_group', 'tenant', name=_('Tenancy')),
    )

    class Meta:
        model = MyModel
        fields = ('name', 'status', 'site', 'comments', 'tags')

Comment fields

If your form has a comments field, there's no need to list it; this will always appear last on the page.

NetBoxModelImportForm

This form facilitates the bulk import of new objects from CSV, JSON, or YAML data. As with model forms, you'll need to declare a Meta subclass specifying the associated model and fields. NetBox also provides several form fields suitable for importing various types of CSV data, listed below.

Subclasses

The corresponding model-specific subclasses of NetBoxModelImportForm are documented below.

Model Class Form Class
PrimaryModel PrimaryModelImportForm
OrganizationalModel OrganizationalModelImportForm
NestedGroupModel NestedGroupModelImportForm

Example

from django.utils.translation import gettext_lazy as _
from dcim.models import Site
from netbox.forms import NetBoxModelImportForm
from utilities.forms import CSVModelChoiceField
from .models import MyModel


class MyModelImportForm(NetBoxModelImportForm):
    site = CSVModelChoiceField(
        queryset=Site.objects.all(),
        to_field_name='name',
        help_text=_('Assigned site')
    )

    class Meta:
        model = MyModel
        fields = ('name', 'status', 'site', 'comments')

NetBoxModelBulkEditForm

This form facilitates editing multiple objects in bulk. Unlike a model form, this form does not have a child Meta class, and must explicitly define each field. All fields in a bulk edit form are generally declared with required=False.

Attribute Description
model The model of object being edited
fieldsets A tuple of FieldSet instances which control how form fields are rendered (optional)
nullable_fields A tuple of fields which can be nullified (set to empty) using the bulk edit form (optional)

Subclasses

The corresponding model-specific subclasses of NetBoxModelBulkEditForm are documented below.

Model Class Form Class
PrimaryModel PrimaryModelBulkEditForm
OrganizationalModel OrganizationalModelBulkEditForm
NestedGroupModel NestedGroupModelBulkEditForm

Example

from django import forms
from django.utils.translation import gettext_lazy as _
from dcim.models import Site
from netbox.forms import NetBoxModelBulkEditForm
from utilities.forms import CommentField, DynamicModelChoiceField
from utilities.forms.rendering import FieldSet
from .models import MyModel, MyModelStatusChoices


class MyModelBulkEditForm(NetBoxModelBulkEditForm):
    name = forms.CharField(
        required=False
    )
    status = forms.ChoiceField(
        choices=MyModelStatusChoices,
        required=False
    )
    site = DynamicModelChoiceField(
        queryset=Site.objects.all(),
        required=False
    )
    comments = CommentField()

    model = MyModel
    fieldsets = (
        FieldSet('name', 'status', 'site', name=_('Model Stuff')),
    )
    nullable_fields = ('site', 'comments')

NetBoxModelFilterSetForm

This form class is used to render a form expressly for filtering a list of objects. Its fields should correspond to filters defined on the model's filter set.

Attribute Description
model The model of object being edited
fieldsets A tuple of FieldSet instances which control how form fields are rendered (optional)

Subclasses

The corresponding model-specific subclasses of NetBoxModelFilterSetForm are documented below.

Model Class Form Class
PrimaryModel PrimaryModelFilterSetForm
OrganizationalModel OrganizationalModelFilterSetForm
NestedGroupModel NestedGroupModelFilterSetForm

Example

from dcim.models import Site
from netbox.forms import NetBoxModelFilterSetForm
from utilities.forms import DynamicModelMultipleChoiceField, MultipleChoiceField
from .models import MyModel, MyModelStatusChoices

class MyModelFilterForm(NetBoxModelFilterSetForm):
    site_id = DynamicModelMultipleChoiceField(
        queryset=Site.objects.all(),
        required=False
    )
    status = MultipleChoiceField(
        choices=MyModelStatusChoices,
        required=False
    )

    model = MyModel

General Purpose Fields

In addition to the form fields provided by Django, NetBox provides several field classes for use within forms to handle specific types of data. These can be imported from utilities.forms.fields and are documented below.

ColorField

Bases: CharField

A field which represents a color value in hexadecimal RRGGBB format. Utilizes NetBox's ColorSelect widget to render choices.

CommentField

Bases: CharField

A textarea with support for Markdown rendering. Exists mostly just to add a standard help_text.

JSONField

Bases: JSONField

Custom wrapper around Django's built-in JSONField to avoid presenting "null" as the default text.

MACAddressField

Bases: Field

Validates a 48-bit MAC address.

SlugField

Bases: SlugField

Extend Django's built-in SlugField to automatically populate from a field called name unless otherwise specified.

Parameters:

Name Type Description Default
slug_source

Name of the form field from which the slug value will be derived

'name'

Static Choice Fields

These fields render a standard HTML <select> element (as opposed to the API-backed widgets used by the dynamic object fields below). They extend Django's built-in choice fields to optionally display a short description beneath each option's label.

For choice set-backed fields, descriptions are defined per choice using a Choice object in the ChoiceSet and are rendered automatically. Pass show_descriptions=False to suppress them for a particular field.

from utilities.choices import Choice, ChoiceSet
from utilities.forms.fields import ChoiceField

class StatusChoices(ChoiceSet):
    ACTIVE = 'active'
    RETIRED = 'retired'
    CHOICES = (
        Choice(ACTIVE, 'Active', description='Currently in service'),
        Choice(RETIRED, 'Retired', description='No longer in service'),
    )

status = ChoiceField(choices=StatusChoices)

ChoiceField

Bases: AttrChoiceMixin, ChoiceField

Extends Django's ChoiceField to render the description defined on each Choice as an option subtitle.

MultipleChoiceField

Bases: AttrChoiceMixin, MultipleChoiceField

Extends Django's MultipleChoiceField to render the description defined on each Choice as an option subtitle.

Dynamic Object Fields

DynamicModelChoiceField

Bases: DynamicModelChoiceMixin, ModelChoiceField

Dynamic selection field for a single object, backed by NetBox's REST API.

DynamicModelMultipleChoiceField

Bases: DynamicModelChoiceMixin, ModelMultipleChoiceField

A multiple-choice version of DynamicModelChoiceField.

Content Type Fields

ContentTypeChoiceField

Bases: ContentTypeChoiceMixin, ModelChoiceField

Selection field for a single content type.

ContentTypeMultipleChoiceField

Bases: ContentTypeChoiceMixin, ModelMultipleChoiceField

Selection field for one or more content types.

Generic Object Fields

GenericObjectChoiceField represents a generic foreign key (a content_type plus object_id pair) as a single, REST API-backed form field. Pair it with GenericObjectFormMixin on the form to seed the field's initial value from the model's GFK descriptor and assign the selected object back to it automatically.

GenericObjectChoiceField

Bases: MultiValueField

Select an object for assignment to a generic foreign key.

Renders a content-type selector (HTMXSelect) plus an API-backed object selector (APISelect) as a single field. Changing the content type re-renders the form so the object selector is rebuilt for the new model. The field's cleaned value is the selected model instance (or None); assignment to the GFK descriptor is handled by GenericObjectFormMixin (or the consuming form's clean()).

Parameters:

Name Type Description Default
content_type_queryset

Queryset of ContentTypes the user may choose from.

required
query_params

Optional dict of static/dynamic ($field) query params forwarded to the object selector.

None
selector

If True, expose the advanced object-selector modal for the object subwidget.

False
gfk_name

Name of the model's GenericForeignKey descriptor, if it differs from the form field name.

None
hx_method

HTTP method for the content-type HTMXSelect ('get' for model forms, 'post' for bulk edit).

'get'
hx_include_id

HTML id of the container whose fields are included in the HTMX request. This should generally remain 'form_fields' so dependent fields can resolve against the full form state.

'form_fields'
hx_target_id

html_id of the enclosing FieldSet for an HTMX partial swap. If omitted, the whole

form_fields container is re-rendered.

None

GenericObjectFormMixin

Initialize and assign any GenericObjectChoiceField fields on a form.

Seeds each field's initial value from the model's GFK descriptor, configures the API-backed object selector for the current content type, and copies the cleaned object back to the instance before model validation runs. Keeps the common GFK form pattern out of individual model forms.

CSV Import Fields

CSVChoiceField

Bases: CSVChoicesMixin, ChoiceField

A CSV field which accepts a single selection value. Treats blank CSV values as omitted to allow model defaults.

CSVMultipleChoiceField

Bases: CSVChoicesMixin, MultipleChoiceField

A CSV field which accepts multiple selection values.

CSVModelChoiceField

Bases: ModelChoiceField

Extends Django's ModelChoiceField to provide additional validation for CSV values.

CSVContentTypeField

Bases: CSVModelChoiceField

CSV field for referencing a single content type, in the form <app>.<model>.

CSVMultipleContentTypeField

Bases: ModelMultipleChoiceField

CSV field for referencing one or more content types, in the form <app>.<model>.

Form Rendering

FieldSet

A generic grouping of fields, with an optional name. Each item will be rendered on its own row under the provided heading (name), if any. The following types may be passed as items:

  • Field name (string)
  • InlineFields instance
  • TabbedGroups instance
  • ObjectAttribute instance

Parameters:

Name Type Description Default
items

An iterable of items to be rendered (one per row)

()
name

The fieldset's name, displayed as a heading (optional)

None
html_id

An HTML id for the rendered fieldset div, enabling HTMX partial swaps (optional). Must be a valid CSS identifier: start with a letter, use only letters, digits, hyphens, underscores.

None

InlineFields

A set of fields rendered inline (side-by-side) with a shared label.

Parameters:

Name Type Description Default
fields

An iterable of form field names

()
label

The label text to render for the row (optional)

None

TabbedGroups

Two or more groups of fields (FieldSets) arranged under tabs among which the user can toggle.

Parameters:

Name Type Description Default
fieldsets

An iterable of FieldSet instances, one per tab. Each FieldSet must have a name assigned, which will be employed as the tab's label.

()

ObjectAttribute

Renders the value for a specific attribute on the form's instance. This may be used to display a read-only value and convey additional context to the user. If the attribute has a get_absolute_url() method, it will be rendered as a hyperlink.

Parameters:

Name Type Description Default
name

The name of the attribute to be displayed

required