model_forms.py 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938
  1. from django import forms
  2. from django.contrib.contenttypes.models import ContentType
  3. from django.core.validators import EMPTY_VALUES
  4. from django.utils.translation import gettext_lazy as _
  5. from timezone_field import TimeZoneFormField
  6. from dcim.choices import *
  7. from dcim.constants import *
  8. from dcim.models import *
  9. from extras.models import ConfigTemplate
  10. from ipam.choices import VLANQinQRoleChoices
  11. from ipam.models import ASN, IPAddress, VLAN, VLANGroup, VLANTranslationPolicy, VRF
  12. from netbox.forms import NestedGroupModelForm, NetBoxModelForm, OrganizationalModelForm, PrimaryModelForm
  13. from netbox.forms.mixins import ChangelogMessageMixin, OwnerMixin
  14. from tenancy.forms import TenancyForm
  15. from users.models import User
  16. from utilities.forms import add_blank_choice, get_field_value
  17. from utilities.forms.fields import (
  18. DynamicModelChoiceField, DynamicModelMultipleChoiceField, JSONField, NumericArrayField, SlugField,
  19. )
  20. from utilities.forms.rendering import FieldSet, InlineFields, TabbedGroups
  21. from utilities.forms.widgets import APISelect, ClearableFileInput, HTMXSelect, NumberWithOptions, SelectWithPK
  22. from utilities.jsonschema import JSONSchemaProperty
  23. from virtualization.models import Cluster, VMInterface
  24. from wireless.models import WirelessLAN, WirelessLANGroup
  25. from .common import InterfaceCommonForm, ModuleCommonForm
  26. __all__ = (
  27. 'CableForm',
  28. 'ConsolePortForm',
  29. 'ConsolePortTemplateForm',
  30. 'ConsoleServerPortForm',
  31. 'ConsoleServerPortTemplateForm',
  32. 'DeviceBayForm',
  33. 'DeviceBayTemplateForm',
  34. 'DeviceForm',
  35. 'DeviceRoleForm',
  36. 'DeviceTypeForm',
  37. 'DeviceVCMembershipForm',
  38. 'FrontPortForm',
  39. 'FrontPortTemplateForm',
  40. 'InterfaceForm',
  41. 'InterfaceTemplateForm',
  42. 'InventoryItemForm',
  43. 'InventoryItemRoleForm',
  44. 'InventoryItemTemplateForm',
  45. 'LocationForm',
  46. 'MACAddressForm',
  47. 'ManufacturerForm',
  48. 'ModuleForm',
  49. 'ModuleBayForm',
  50. 'ModuleBayTemplateForm',
  51. 'ModuleTypeForm',
  52. 'ModuleTypeProfileForm',
  53. 'PlatformForm',
  54. 'PopulateDeviceBayForm',
  55. 'PowerFeedForm',
  56. 'PowerOutletForm',
  57. 'PowerOutletTemplateForm',
  58. 'PowerPanelForm',
  59. 'PowerPortForm',
  60. 'PowerPortTemplateForm',
  61. 'RackForm',
  62. 'RackReservationForm',
  63. 'RackRoleForm',
  64. 'RackTypeForm',
  65. 'RearPortForm',
  66. 'RearPortTemplateForm',
  67. 'RegionForm',
  68. 'SiteForm',
  69. 'SiteGroupForm',
  70. 'VCMemberSelectForm',
  71. 'VirtualChassisForm',
  72. 'VirtualDeviceContextForm'
  73. )
  74. class RegionForm(NestedGroupModelForm):
  75. parent = DynamicModelChoiceField(
  76. label=_('Parent'),
  77. queryset=Region.objects.all(),
  78. required=False
  79. )
  80. fieldsets = (
  81. FieldSet('parent', 'name', 'slug', 'description', 'tags'),
  82. )
  83. class Meta:
  84. model = Region
  85. fields = (
  86. 'parent', 'name', 'slug', 'description', 'owner', 'tags', 'comments',
  87. )
  88. class SiteGroupForm(NestedGroupModelForm):
  89. parent = DynamicModelChoiceField(
  90. label=_('Parent'),
  91. queryset=SiteGroup.objects.all(),
  92. required=False
  93. )
  94. fieldsets = (
  95. FieldSet('parent', 'name', 'slug', 'description', 'tags'),
  96. )
  97. class Meta:
  98. model = SiteGroup
  99. fields = (
  100. 'parent', 'name', 'slug', 'description', 'owner', 'comments', 'tags',
  101. )
  102. class SiteForm(TenancyForm, PrimaryModelForm):
  103. region = DynamicModelChoiceField(
  104. label=_('Region'),
  105. queryset=Region.objects.all(),
  106. required=False,
  107. quick_add=True
  108. )
  109. group = DynamicModelChoiceField(
  110. label=_('Group'),
  111. queryset=SiteGroup.objects.all(),
  112. required=False,
  113. quick_add=True
  114. )
  115. asns = DynamicModelMultipleChoiceField(
  116. queryset=ASN.objects.all(),
  117. label=_('ASNs'),
  118. required=False
  119. )
  120. slug = SlugField()
  121. time_zone = TimeZoneFormField(
  122. label=_('Time zone'),
  123. choices=add_blank_choice(TimeZoneFormField().choices),
  124. required=False
  125. )
  126. fieldsets = (
  127. FieldSet(
  128. 'name', 'slug', 'status', 'region', 'group', 'facility', 'asns', 'time_zone', 'description', 'tags',
  129. name=_('Site')
  130. ),
  131. FieldSet('tenant_group', 'tenant', name=_('Tenancy')),
  132. FieldSet('physical_address', 'shipping_address', 'latitude', 'longitude', name=_('Contact Info')),
  133. )
  134. class Meta:
  135. model = Site
  136. fields = (
  137. 'name', 'slug', 'status', 'region', 'group', 'tenant_group', 'tenant', 'facility', 'asns', 'time_zone',
  138. 'description', 'physical_address', 'shipping_address', 'latitude', 'longitude', 'owner', 'comments', 'tags',
  139. )
  140. widgets = {
  141. 'physical_address': forms.Textarea(
  142. attrs={
  143. 'rows': 3,
  144. }
  145. ),
  146. 'shipping_address': forms.Textarea(
  147. attrs={
  148. 'rows': 3,
  149. }
  150. ),
  151. }
  152. class LocationForm(TenancyForm, NestedGroupModelForm):
  153. site = DynamicModelChoiceField(
  154. label=_('Site'),
  155. queryset=Site.objects.all(),
  156. selector=True
  157. )
  158. parent = DynamicModelChoiceField(
  159. label=_('Parent'),
  160. queryset=Location.objects.all(),
  161. required=False,
  162. query_params={
  163. 'site_id': '$site'
  164. }
  165. )
  166. fieldsets = (
  167. FieldSet('site', 'parent', 'name', 'slug', 'status', 'facility', 'description', 'tags', name=_('Location')),
  168. FieldSet('tenant_group', 'tenant', name=_('Tenancy')),
  169. )
  170. class Meta:
  171. model = Location
  172. fields = (
  173. 'site', 'parent', 'name', 'slug', 'status', 'description', 'tenant_group', 'tenant', 'facility', 'owner',
  174. 'comments', 'tags',
  175. )
  176. class RackRoleForm(OrganizationalModelForm):
  177. fieldsets = (
  178. FieldSet('name', 'slug', 'color', 'description', 'tags', name=_('Rack Role')),
  179. )
  180. class Meta:
  181. model = RackRole
  182. fields = [
  183. 'name', 'slug', 'color', 'description', 'owner', 'tags',
  184. ]
  185. class RackTypeForm(PrimaryModelForm):
  186. manufacturer = DynamicModelChoiceField(
  187. label=_('Manufacturer'),
  188. queryset=Manufacturer.objects.all(),
  189. quick_add=True
  190. )
  191. slug = SlugField(
  192. label=_('Slug'),
  193. slug_source='model'
  194. )
  195. fieldsets = (
  196. FieldSet('manufacturer', 'model', 'slug', 'description', 'form_factor', 'tags', name=_('Rack Type')),
  197. FieldSet(
  198. 'width', 'u_height',
  199. InlineFields('outer_width', 'outer_height', 'outer_depth', 'outer_unit', label=_('Outer Dimensions')),
  200. InlineFields('weight', 'max_weight', 'weight_unit', label=_('Weight')),
  201. 'mounting_depth', name=_('Dimensions')
  202. ),
  203. FieldSet('starting_unit', 'desc_units', name=_('Numbering')),
  204. )
  205. class Meta:
  206. model = RackType
  207. fields = [
  208. 'manufacturer', 'model', 'slug', 'form_factor', 'width', 'u_height', 'starting_unit', 'desc_units',
  209. 'outer_width', 'outer_height', 'outer_depth', 'outer_unit', 'mounting_depth', 'weight', 'max_weight',
  210. 'weight_unit', 'description', 'owner', 'comments', 'tags',
  211. ]
  212. class RackForm(TenancyForm, PrimaryModelForm):
  213. site = DynamicModelChoiceField(
  214. label=_('Site'),
  215. queryset=Site.objects.all(),
  216. selector=True
  217. )
  218. location = DynamicModelChoiceField(
  219. label=_('Location'),
  220. queryset=Location.objects.all(),
  221. required=False,
  222. query_params={
  223. 'site_id': '$site'
  224. }
  225. )
  226. role = DynamicModelChoiceField(
  227. label=_('Role'),
  228. queryset=RackRole.objects.all(),
  229. required=False
  230. )
  231. rack_type = DynamicModelChoiceField(
  232. label=_('Rack Type'),
  233. queryset=RackType.objects.all(),
  234. required=False,
  235. help_text=_("Select a pre-defined rack type, or set physical characteristics below.")
  236. )
  237. fieldsets = (
  238. FieldSet(
  239. 'site', 'location', 'name', 'status', 'role', 'rack_type', 'description', 'airflow', 'tags',
  240. name=_('Rack')
  241. ),
  242. FieldSet('facility_id', 'serial', 'asset_tag', name=_('Inventory Control')),
  243. FieldSet('tenant_group', 'tenant', name=_('Tenancy')),
  244. )
  245. class Meta:
  246. model = Rack
  247. fields = [
  248. 'site', 'location', 'name', 'facility_id', 'tenant_group', 'tenant', 'status', 'role', 'serial',
  249. 'asset_tag', 'rack_type', 'form_factor', 'width', 'u_height', 'starting_unit', 'desc_units', 'outer_width',
  250. 'outer_height', 'outer_depth', 'outer_unit', 'mounting_depth', 'airflow', 'weight', 'max_weight',
  251. 'weight_unit', 'description', 'owner', 'comments', 'tags',
  252. ]
  253. def __init__(self, *args, **kwargs):
  254. super().__init__(*args, **kwargs)
  255. # Mimic HTMXSelect()
  256. self.fields['rack_type'].widget.attrs.update({
  257. 'hx-get': '.',
  258. 'hx-include': '#form_fields',
  259. 'hx-target': '#form_fields',
  260. })
  261. # Omit RackType-defined fields if rack_type is set
  262. if get_field_value(self, 'rack_type'):
  263. for field_name in Rack.RACKTYPE_FIELDS:
  264. del self.fields[field_name]
  265. else:
  266. self.fieldsets = (
  267. *self.fieldsets,
  268. FieldSet(
  269. 'form_factor', 'width', 'starting_unit', 'u_height',
  270. InlineFields('outer_width', 'outer_height', 'outer_depth', 'outer_unit',
  271. label=_('Outer Dimensions')),
  272. InlineFields('weight', 'max_weight', 'weight_unit', label=_('Weight')),
  273. 'mounting_depth', 'desc_units', name=_('Dimensions')
  274. ),
  275. )
  276. class RackReservationForm(TenancyForm, PrimaryModelForm):
  277. rack = DynamicModelChoiceField(
  278. label=_('Rack'),
  279. queryset=Rack.objects.all(),
  280. selector=True
  281. )
  282. units = NumericArrayField(
  283. label=_('Units'),
  284. base_field=forms.IntegerField(),
  285. help_text=_("Comma-separated list of numeric unit IDs. A range may be specified using a hyphen.")
  286. )
  287. user = forms.ModelChoiceField(
  288. label=_('User'),
  289. queryset=User.objects.order_by('username')
  290. )
  291. fieldsets = (
  292. FieldSet('rack', 'units', 'status', 'user', 'description', 'tags', name=_('Reservation')),
  293. FieldSet('tenant_group', 'tenant', name=_('Tenancy')),
  294. )
  295. class Meta:
  296. model = RackReservation
  297. fields = [
  298. 'rack', 'units', 'status', 'user', 'tenant_group', 'tenant', 'description', 'owner', 'comments', 'tags',
  299. ]
  300. class ManufacturerForm(OrganizationalModelForm):
  301. fieldsets = (
  302. FieldSet('name', 'slug', 'description', 'tags', name=_('Manufacturer')),
  303. )
  304. class Meta:
  305. model = Manufacturer
  306. fields = [
  307. 'name', 'slug', 'description', 'owner', 'tags',
  308. ]
  309. class DeviceTypeForm(PrimaryModelForm):
  310. manufacturer = DynamicModelChoiceField(
  311. label=_('Manufacturer'),
  312. queryset=Manufacturer.objects.all(),
  313. quick_add=True
  314. )
  315. default_platform = DynamicModelChoiceField(
  316. label=_('Default platform'),
  317. queryset=Platform.objects.all(),
  318. required=False,
  319. selector=True,
  320. query_params={
  321. 'manufacturer_id': ['$manufacturer', 'null'],
  322. }
  323. )
  324. slug = SlugField(
  325. label=_('Slug'),
  326. slug_source='model'
  327. )
  328. fieldsets = (
  329. FieldSet('manufacturer', 'model', 'slug', 'default_platform', 'description', 'tags', name=_('Device Type')),
  330. FieldSet(
  331. 'u_height', 'exclude_from_utilization', 'is_full_depth', 'part_number', 'subdevice_role', 'airflow',
  332. 'weight', 'weight_unit', name=_('Chassis')
  333. ),
  334. FieldSet('front_image', 'rear_image', name=_('Images')),
  335. )
  336. class Meta:
  337. model = DeviceType
  338. fields = [
  339. 'manufacturer', 'model', 'slug', 'default_platform', 'part_number', 'u_height', 'exclude_from_utilization',
  340. 'is_full_depth', 'subdevice_role', 'airflow', 'weight', 'weight_unit', 'front_image', 'rear_image',
  341. 'description', 'owner', 'comments', 'tags',
  342. ]
  343. widgets = {
  344. 'front_image': ClearableFileInput(attrs={
  345. 'accept': DEVICETYPE_IMAGE_FORMATS
  346. }),
  347. 'rear_image': ClearableFileInput(attrs={
  348. 'accept': DEVICETYPE_IMAGE_FORMATS
  349. }),
  350. }
  351. class ModuleTypeProfileForm(PrimaryModelForm):
  352. schema = JSONField(
  353. label=_('Schema'),
  354. required=False,
  355. help_text=_("Enter a valid JSON schema to define supported attributes.")
  356. )
  357. fieldsets = (
  358. FieldSet('name', 'description', 'schema', 'tags', name=_('Profile')),
  359. )
  360. class Meta:
  361. model = ModuleTypeProfile
  362. fields = [
  363. 'name', 'description', 'schema', 'owner', 'comments', 'tags',
  364. ]
  365. class ModuleTypeForm(PrimaryModelForm):
  366. profile = forms.ModelChoiceField(
  367. queryset=ModuleTypeProfile.objects.all(),
  368. label=_('Profile'),
  369. required=False,
  370. widget=HTMXSelect()
  371. )
  372. manufacturer = DynamicModelChoiceField(
  373. label=_('Manufacturer'),
  374. queryset=Manufacturer.objects.all()
  375. )
  376. @property
  377. def fieldsets(self):
  378. return [
  379. FieldSet('manufacturer', 'model', 'part_number', 'description', 'tags', name=_('Module Type')),
  380. FieldSet('airflow', 'weight', 'weight_unit', name=_('Hardware')),
  381. FieldSet('profile', *self.attr_fields, name=_('Profile & Attributes'))
  382. ]
  383. class Meta:
  384. model = ModuleType
  385. fields = [
  386. 'profile', 'manufacturer', 'model', 'part_number', 'description', 'airflow', 'weight', 'weight_unit',
  387. 'owner', 'comments', 'tags',
  388. ]
  389. def __init__(self, *args, **kwargs):
  390. super().__init__(*args, **kwargs)
  391. # Track profile-specific attribute fields
  392. self.attr_fields = []
  393. # Retrieve assigned ModuleTypeProfile, if any
  394. if not (profile_id := get_field_value(self, 'profile')):
  395. return
  396. if not (profile := ModuleTypeProfile.objects.filter(pk=profile_id).first()):
  397. return
  398. # Extend form with fields for profile attributes
  399. for attr, form_field in self._get_attr_form_fields(profile).items():
  400. field_name = f'attr_{attr}'
  401. self.attr_fields.append(field_name)
  402. self.fields[field_name] = form_field
  403. if self.instance.attribute_data:
  404. self.fields[field_name].initial = self.instance.attribute_data.get(attr)
  405. @staticmethod
  406. def _get_attr_form_fields(profile):
  407. """
  408. Return a dictionary mapping of attribute names to form fields, suitable for extending
  409. the form per the selected ModuleTypeProfile.
  410. """
  411. if not profile.schema:
  412. return {}
  413. properties = profile.schema.get('properties', {})
  414. required_fields = profile.schema.get('required', [])
  415. attr_fields = {}
  416. for name, options in properties.items():
  417. prop = JSONSchemaProperty(**options)
  418. attr_fields[name] = prop.to_form_field(name, required=name in required_fields)
  419. return dict(sorted(attr_fields.items()))
  420. def _post_clean(self):
  421. # Compile attribute data from the individual form fields
  422. if self.cleaned_data.get('profile'):
  423. self.instance.attribute_data = {
  424. name[5:]: self.cleaned_data[name] # Remove the attr_ prefix
  425. for name in self.attr_fields
  426. if self.cleaned_data.get(name) not in EMPTY_VALUES
  427. }
  428. return super()._post_clean()
  429. class DeviceRoleForm(NestedGroupModelForm):
  430. config_template = DynamicModelChoiceField(
  431. label=_('Config template'),
  432. queryset=ConfigTemplate.objects.all(),
  433. required=False
  434. )
  435. parent = DynamicModelChoiceField(
  436. label=_('Parent'),
  437. queryset=DeviceRole.objects.all(),
  438. required=False,
  439. )
  440. fieldsets = (
  441. FieldSet(
  442. 'name', 'slug', 'parent', 'color', 'vm_role', 'config_template', 'description',
  443. 'tags', name=_('Device Role')
  444. ),
  445. )
  446. class Meta:
  447. model = DeviceRole
  448. fields = [
  449. 'name', 'slug', 'parent', 'color', 'vm_role', 'config_template', 'description', 'owner', 'comments', 'tags',
  450. ]
  451. class PlatformForm(NestedGroupModelForm):
  452. parent = DynamicModelChoiceField(
  453. label=_('Parent'),
  454. queryset=Platform.objects.all(),
  455. required=False,
  456. )
  457. manufacturer = DynamicModelChoiceField(
  458. label=_('Manufacturer'),
  459. queryset=Manufacturer.objects.all(),
  460. required=False,
  461. quick_add=True
  462. )
  463. config_template = DynamicModelChoiceField(
  464. label=_('Config template'),
  465. queryset=ConfigTemplate.objects.all(),
  466. required=False
  467. )
  468. slug = SlugField(
  469. label=_('Slug'),
  470. max_length=64
  471. )
  472. fieldsets = (
  473. FieldSet(
  474. 'name', 'slug', 'parent', 'manufacturer', 'config_template', 'description', 'tags', name=_('Platform'),
  475. ),
  476. )
  477. class Meta:
  478. model = Platform
  479. fields = [
  480. 'name', 'slug', 'parent', 'manufacturer', 'config_template', 'description', 'owner', 'comments', 'tags',
  481. ]
  482. class DeviceForm(TenancyForm, PrimaryModelForm):
  483. site = DynamicModelChoiceField(
  484. label=_('Site'),
  485. queryset=Site.objects.all(),
  486. selector=True
  487. )
  488. location = DynamicModelChoiceField(
  489. label=_('Location'),
  490. queryset=Location.objects.all(),
  491. required=False,
  492. query_params={
  493. 'site_id': '$site'
  494. },
  495. initial_params={
  496. 'racks': '$rack'
  497. }
  498. )
  499. rack = DynamicModelChoiceField(
  500. label=_('Rack'),
  501. queryset=Rack.objects.all(),
  502. required=False,
  503. query_params={
  504. 'site_id': '$site',
  505. 'location_id': '$location',
  506. }
  507. )
  508. position = forms.DecimalField(
  509. label=_('Position'),
  510. required=False,
  511. help_text=_("The lowest-numbered unit occupied by the device"),
  512. localize=True,
  513. widget=APISelect(
  514. api_url='/api/dcim/racks/{{rack}}/elevation/',
  515. attrs={
  516. 'ts-disabled-field': 'device',
  517. 'data-dynamic-params': '[{"fieldName":"face","queryParam":"face"}]'
  518. },
  519. )
  520. )
  521. device_type = DynamicModelChoiceField(
  522. label=_('Device type'),
  523. queryset=DeviceType.objects.all(),
  524. context={
  525. 'parent': 'manufacturer',
  526. },
  527. selector=True
  528. )
  529. role = DynamicModelChoiceField(
  530. label=_('Device role'),
  531. queryset=DeviceRole.objects.all(),
  532. quick_add=True
  533. )
  534. platform = DynamicModelChoiceField(
  535. label=_('Platform'),
  536. queryset=Platform.objects.all(),
  537. required=False,
  538. selector=True,
  539. query_params={
  540. 'available_for_device_type': '$device_type',
  541. }
  542. )
  543. cluster = DynamicModelChoiceField(
  544. label=_('Cluster'),
  545. queryset=Cluster.objects.all(),
  546. required=False,
  547. selector=True,
  548. query_params={
  549. 'site_id': ['$site', 'null']
  550. },
  551. )
  552. local_context_data = JSONField(
  553. required=False,
  554. label=''
  555. )
  556. virtual_chassis = DynamicModelChoiceField(
  557. label=_('Virtual chassis'),
  558. queryset=VirtualChassis.objects.all(),
  559. required=False,
  560. context={
  561. 'parent': 'master',
  562. },
  563. selector=True
  564. )
  565. vc_position = forms.IntegerField(
  566. required=False,
  567. label=_('Position'),
  568. help_text=_("The position in the virtual chassis this device is identified by")
  569. )
  570. vc_priority = forms.IntegerField(
  571. required=False,
  572. label=_('Priority'),
  573. help_text=_("The priority of the device in the virtual chassis")
  574. )
  575. config_template = DynamicModelChoiceField(
  576. label=_('Config template'),
  577. queryset=ConfigTemplate.objects.all(),
  578. required=False
  579. )
  580. class Meta:
  581. model = Device
  582. fields = [
  583. 'name', 'role', 'device_type', 'serial', 'asset_tag', 'site', 'rack', 'location', 'position', 'face',
  584. 'latitude', 'longitude', 'status', 'airflow', 'platform', 'primary_ip4', 'primary_ip6', 'oob_ip', 'cluster',
  585. 'tenant_group', 'tenant', 'virtual_chassis', 'vc_position', 'vc_priority', 'description', 'config_template',
  586. 'owner', 'comments', 'tags', 'local_context_data',
  587. ]
  588. def __init__(self, *args, **kwargs):
  589. super().__init__(*args, **kwargs)
  590. if self.instance.pk:
  591. # Compile list of choices for primary IPv4 and IPv6 addresses
  592. oob_ip_choices = [(None, '---------')]
  593. for family in [4, 6]:
  594. ip_choices = [(None, '---------')]
  595. # Gather PKs of all interfaces belonging to this Device or a peer VirtualChassis member
  596. interface_ids = self.instance.vc_interfaces(if_master=False).values_list('pk', flat=True)
  597. # Collect interface IPs
  598. interface_ips = IPAddress.objects.filter(
  599. address__family=family,
  600. assigned_object_type=ContentType.objects.get_for_model(Interface),
  601. assigned_object_id__in=interface_ids
  602. ).prefetch_related('assigned_object')
  603. if interface_ips:
  604. ip_list = [(ip.id, f'{ip.address} ({ip.assigned_object})') for ip in interface_ips]
  605. ip_choices.append(('Interface IPs', ip_list))
  606. oob_ip_choices.extend(ip_list)
  607. # Collect NAT IPs
  608. nat_ips = IPAddress.objects.prefetch_related('nat_inside').filter(
  609. address__family=family,
  610. nat_inside__assigned_object_type=ContentType.objects.get_for_model(Interface),
  611. nat_inside__assigned_object_id__in=interface_ids
  612. ).prefetch_related('assigned_object')
  613. if nat_ips:
  614. ip_list = [(ip.id, f'{ip.address} (NAT)') for ip in nat_ips]
  615. ip_choices.append(('NAT IPs', ip_list))
  616. self.fields['primary_ip{}'.format(family)].choices = ip_choices
  617. self.fields['oob_ip'].choices = oob_ip_choices
  618. # If editing an existing device, exclude it from the list of occupied rack units. This ensures that a device
  619. # can be flipped from one face to another.
  620. self.fields['position'].widget.add_query_param('exclude', self.instance.pk)
  621. # Disable rack assignment if this is a child device installed in a parent device
  622. if self.instance.device_type.is_child_device and hasattr(self.instance, 'parent_bay'):
  623. self.fields['site'].disabled = True
  624. self.fields['rack'].disabled = True
  625. self.initial['site'] = self.instance.parent_bay.device.site_id
  626. self.initial['rack'] = self.instance.parent_bay.device.rack_id
  627. else:
  628. # An object that doesn't exist yet can't have any IPs assigned to it
  629. self.fields['primary_ip4'].choices = []
  630. self.fields['primary_ip4'].widget.attrs['readonly'] = True
  631. self.fields['primary_ip6'].choices = []
  632. self.fields['primary_ip6'].widget.attrs['readonly'] = True
  633. self.fields['oob_ip'].choices = []
  634. self.fields['oob_ip'].widget.attrs['readonly'] = True
  635. # Rack position
  636. position = self.data.get('position') or self.initial.get('position')
  637. if position:
  638. self.fields['position'].widget.choices = [(position, f'U{position}')]
  639. class ModuleForm(ModuleCommonForm, PrimaryModelForm):
  640. device = DynamicModelChoiceField(
  641. label=_('Device'),
  642. queryset=Device.objects.all(),
  643. initial_params={
  644. 'modulebays': '$module_bay'
  645. }
  646. )
  647. module_bay = DynamicModelChoiceField(
  648. label=_('Module bay'),
  649. queryset=ModuleBay.objects.all(),
  650. query_params={
  651. 'device_id': '$device'
  652. }
  653. )
  654. module_type = DynamicModelChoiceField(
  655. label=_('Module type'),
  656. queryset=ModuleType.objects.all(),
  657. context={
  658. 'parent': 'manufacturer',
  659. },
  660. selector=True
  661. )
  662. replicate_components = forms.BooleanField(
  663. label=_('Replicate components'),
  664. required=False,
  665. initial=True,
  666. help_text=_("Automatically populate components associated with this module type")
  667. )
  668. adopt_components = forms.BooleanField(
  669. label=_('Adopt components'),
  670. required=False,
  671. initial=False,
  672. help_text=_("Adopt already existing components")
  673. )
  674. fieldsets = (
  675. FieldSet('device', 'module_bay', 'module_type', 'status', 'description', 'tags', name=_('Module')),
  676. FieldSet('serial', 'asset_tag', 'replicate_components', 'adopt_components', name=_('Hardware')),
  677. )
  678. class Meta:
  679. model = Module
  680. fields = [
  681. 'device', 'module_bay', 'module_type', 'status', 'serial', 'asset_tag', 'tags', 'replicate_components',
  682. 'adopt_components', 'description', 'owner', 'comments',
  683. ]
  684. def __init__(self, *args, **kwargs):
  685. super().__init__(*args, **kwargs)
  686. if self.instance.pk:
  687. self.fields['device'].disabled = True
  688. self.fields['replicate_components'].initial = False
  689. self.fields['replicate_components'].disabled = True
  690. self.fields['adopt_components'].initial = False
  691. self.fields['adopt_components'].disabled = True
  692. def get_termination_type_choices():
  693. return add_blank_choice([
  694. (f'{ct.app_label}.{ct.model}', ct.model_class()._meta.verbose_name.title())
  695. for ct in ContentType.objects.filter(CABLE_TERMINATION_MODELS)
  696. ])
  697. class CableForm(TenancyForm, PrimaryModelForm):
  698. a_terminations_type = forms.ChoiceField(
  699. choices=get_termination_type_choices,
  700. required=False,
  701. widget=HTMXSelect(),
  702. label=_('Type')
  703. )
  704. b_terminations_type = forms.ChoiceField(
  705. choices=get_termination_type_choices,
  706. required=False,
  707. widget=HTMXSelect(),
  708. label=_('Type')
  709. )
  710. class Meta:
  711. model = Cable
  712. fields = [
  713. 'a_terminations_type', 'b_terminations_type', 'type', 'status', 'tenant_group', 'tenant', 'label', 'color',
  714. 'length', 'length_unit', 'description', 'owner', 'comments', 'tags',
  715. ]
  716. class PowerPanelForm(PrimaryModelForm):
  717. site = DynamicModelChoiceField(
  718. label=_('Site'),
  719. queryset=Site.objects.all(),
  720. selector=True
  721. )
  722. location = DynamicModelChoiceField(
  723. label=_('Location'),
  724. queryset=Location.objects.all(),
  725. required=False,
  726. query_params={
  727. 'site_id': '$site'
  728. }
  729. )
  730. fieldsets = (
  731. FieldSet('site', 'location', 'name', 'description', 'tags', name=_('Power Panel')),
  732. )
  733. class Meta:
  734. model = PowerPanel
  735. fields = [
  736. 'site', 'location', 'name', 'description', 'owner', 'comments', 'tags',
  737. ]
  738. class PowerFeedForm(TenancyForm, PrimaryModelForm):
  739. power_panel = DynamicModelChoiceField(
  740. label=_('Power panel'),
  741. queryset=PowerPanel.objects.all(),
  742. selector=True,
  743. quick_add=True
  744. )
  745. rack = DynamicModelChoiceField(
  746. label=_('Rack'),
  747. queryset=Rack.objects.all(),
  748. required=False,
  749. selector=True
  750. )
  751. fieldsets = (
  752. FieldSet(
  753. 'power_panel', 'rack', 'name', 'status', 'type', 'description', 'mark_connected', 'tags',
  754. name=_('Power Feed')
  755. ),
  756. FieldSet('supply', 'voltage', 'amperage', 'phase', 'max_utilization', name=_('Characteristics')),
  757. FieldSet('tenant_group', 'tenant', name=_('Tenancy')),
  758. )
  759. class Meta:
  760. model = PowerFeed
  761. fields = [
  762. 'power_panel', 'rack', 'name', 'status', 'type', 'mark_connected', 'supply', 'phase', 'voltage', 'amperage',
  763. 'max_utilization', 'tenant_group', 'tenant', 'description', 'owner', 'comments', 'tags'
  764. ]
  765. #
  766. # Virtual chassis
  767. #
  768. class VirtualChassisForm(PrimaryModelForm):
  769. master = forms.ModelChoiceField(
  770. label=_('Master'),
  771. queryset=Device.objects.all(),
  772. required=False,
  773. )
  774. class Meta:
  775. model = VirtualChassis
  776. fields = [
  777. 'name', 'domain', 'master', 'description', 'owner', 'comments', 'tags',
  778. ]
  779. widgets = {
  780. 'master': SelectWithPK(),
  781. }
  782. def __init__(self, *args, **kwargs):
  783. super().__init__(*args, **kwargs)
  784. self.fields['master'].queryset = Device.objects.filter(virtual_chassis=self.instance)
  785. class DeviceVCMembershipForm(forms.ModelForm):
  786. class Meta:
  787. model = Device
  788. fields = [
  789. 'vc_position', 'vc_priority',
  790. ]
  791. labels = {
  792. 'vc_position': 'Position',
  793. 'vc_priority': 'Priority',
  794. }
  795. def __init__(self, validate_vc_position=False, *args, **kwargs):
  796. super().__init__(*args, **kwargs)
  797. # Require VC position (only required when the Device is a VirtualChassis member)
  798. self.fields['vc_position'].required = True
  799. # Add bootstrap classes to form elements.
  800. self.fields['vc_position'].widget.attrs = {'class': 'form-control'}
  801. self.fields['vc_priority'].widget.attrs = {'class': 'form-control'}
  802. # Validation of vc_position is optional. This is only required when adding a new member to an existing
  803. # VirtualChassis. Otherwise, vc_position validation is handled by BaseVCMemberFormSet.
  804. self.validate_vc_position = validate_vc_position
  805. def clean_vc_position(self):
  806. vc_position = self.cleaned_data['vc_position']
  807. if self.validate_vc_position:
  808. conflicting_members = Device.objects.filter(
  809. virtual_chassis=self.instance.virtual_chassis,
  810. vc_position=vc_position
  811. )
  812. if conflicting_members.exists():
  813. raise forms.ValidationError(
  814. 'A virtual chassis member already exists in position {}.'.format(vc_position)
  815. )
  816. return vc_position
  817. class VCMemberSelectForm(forms.Form):
  818. device = DynamicModelChoiceField(
  819. label=_('Device'),
  820. queryset=Device.objects.all(),
  821. query_params={
  822. 'virtual_chassis_id': 'null',
  823. },
  824. selector=True
  825. )
  826. def clean_device(self):
  827. device = self.cleaned_data['device']
  828. if device.virtual_chassis is not None:
  829. raise forms.ValidationError(
  830. f"Device {device} is already assigned to a virtual chassis."
  831. )
  832. return device
  833. #
  834. # Device component templates
  835. #
  836. class ComponentTemplateForm(ChangelogMessageMixin, forms.ModelForm):
  837. device_type = DynamicModelChoiceField(
  838. label=_('Device type'),
  839. queryset=DeviceType.objects.all(),
  840. context={
  841. 'parent': 'manufacturer',
  842. }
  843. )
  844. def __init__(self, *args, **kwargs):
  845. super().__init__(*args, **kwargs)
  846. # Disable reassignment of DeviceType when editing an existing instance
  847. if self.instance.pk:
  848. self.fields['device_type'].disabled = True
  849. class ModularComponentTemplateForm(ComponentTemplateForm):
  850. device_type = DynamicModelChoiceField(
  851. label=_('Device type'),
  852. queryset=DeviceType.objects.all(),
  853. required=False,
  854. context={
  855. 'parent': 'manufacturer',
  856. }
  857. )
  858. module_type = DynamicModelChoiceField(
  859. label=_('Module type'),
  860. queryset=ModuleType.objects.all(),
  861. required=False,
  862. context={
  863. 'parent': 'manufacturer',
  864. }
  865. )
  866. fieldsets = (
  867. FieldSet(
  868. TabbedGroups(
  869. FieldSet('device_type', name=_('Device Type')),
  870. FieldSet('module_type', name=_('Module Type')),
  871. ),
  872. 'name', 'label', 'type', 'description'
  873. ),
  874. )
  875. def __init__(self, *args, **kwargs):
  876. super().__init__(*args, **kwargs)
  877. # Disable reassignment of ModuleType when editing an existing instance
  878. if self.instance.pk:
  879. self.fields['module_type'].disabled = True
  880. # Components attached to a module need to present this standardized substitution help text.
  881. self.fields['name'].help_text = _(
  882. "Alphanumeric ranges are supported for bulk creation. Mixed cases and types within a single range are not "
  883. "supported (example: <code>[ge,xe]-0/0/[0-9]</code>). The token <code>{module}</code>, if present, will be "
  884. "automatically replaced with the position value when creating a new module."
  885. )
  886. class ConsolePortTemplateForm(ModularComponentTemplateForm):
  887. class Meta:
  888. model = ConsolePortTemplate
  889. fields = [
  890. 'device_type', 'module_type', 'name', 'label', 'type', 'description',
  891. ]
  892. class ConsoleServerPortTemplateForm(ModularComponentTemplateForm):
  893. class Meta:
  894. model = ConsoleServerPortTemplate
  895. fields = [
  896. 'device_type', 'module_type', 'name', 'label', 'type', 'description',
  897. ]
  898. class PowerPortTemplateForm(ModularComponentTemplateForm):
  899. fieldsets = (
  900. FieldSet(
  901. TabbedGroups(
  902. FieldSet('device_type', name=_('Device Type')),
  903. FieldSet('module_type', name=_('Module Type')),
  904. ),
  905. 'name', 'label', 'type', 'maximum_draw', 'allocated_draw', 'description',
  906. ),
  907. )
  908. class Meta:
  909. model = PowerPortTemplate
  910. fields = [
  911. 'device_type', 'module_type', 'name', 'label', 'type', 'maximum_draw', 'allocated_draw', 'description',
  912. ]
  913. class PowerOutletTemplateForm(ModularComponentTemplateForm):
  914. power_port = DynamicModelChoiceField(
  915. label=_('Power port'),
  916. queryset=PowerPortTemplate.objects.all(),
  917. required=False,
  918. query_params={
  919. 'device_type_id': '$device_type',
  920. }
  921. )
  922. fieldsets = (
  923. FieldSet(
  924. TabbedGroups(
  925. FieldSet('device_type', name=_('Device Type')),
  926. FieldSet('module_type', name=_('Module Type')),
  927. ),
  928. 'name', 'label', 'type', 'color', 'power_port', 'feed_leg', 'description',
  929. ),
  930. )
  931. class Meta:
  932. model = PowerOutletTemplate
  933. fields = [
  934. 'device_type', 'module_type', 'name', 'label', 'type', 'color', 'power_port', 'feed_leg', 'description',
  935. ]
  936. class InterfaceTemplateForm(ModularComponentTemplateForm):
  937. bridge = DynamicModelChoiceField(
  938. label=_('Bridge'),
  939. queryset=InterfaceTemplate.objects.all(),
  940. required=False,
  941. query_params={
  942. 'device_type_id': '$device_type',
  943. 'module_type_id': '$module_type',
  944. }
  945. )
  946. fieldsets = (
  947. FieldSet(
  948. TabbedGroups(
  949. FieldSet('device_type', name=_('Device Type')),
  950. FieldSet('module_type', name=_('Module Type')),
  951. ),
  952. 'name', 'label', 'type', 'enabled', 'mgmt_only', 'description', 'bridge',
  953. ),
  954. FieldSet('poe_mode', 'poe_type', name=_('PoE')),
  955. FieldSet('rf_role', name=_('Wireless')),
  956. )
  957. class Meta:
  958. model = InterfaceTemplate
  959. fields = [
  960. 'device_type', 'module_type', 'name', 'label', 'type', 'mgmt_only', 'enabled', 'description', 'poe_mode',
  961. 'poe_type', 'bridge', 'rf_role',
  962. ]
  963. class FrontPortTemplateForm(ModularComponentTemplateForm):
  964. rear_port = DynamicModelChoiceField(
  965. label=_('Rear port'),
  966. queryset=RearPortTemplate.objects.all(),
  967. required=False,
  968. query_params={
  969. 'device_type_id': '$device_type',
  970. 'module_type_id': '$module_type',
  971. }
  972. )
  973. fieldsets = (
  974. FieldSet(
  975. TabbedGroups(
  976. FieldSet('device_type', name=_('Device Type')),
  977. FieldSet('module_type', name=_('Module Type')),
  978. ),
  979. 'name', 'label', 'type', 'color', 'rear_port', 'rear_port_position', 'description',
  980. ),
  981. )
  982. class Meta:
  983. model = FrontPortTemplate
  984. fields = [
  985. 'device_type', 'module_type', 'name', 'label', 'type', 'color', 'rear_port', 'rear_port_position',
  986. 'description',
  987. ]
  988. class RearPortTemplateForm(ModularComponentTemplateForm):
  989. fieldsets = (
  990. FieldSet(
  991. TabbedGroups(
  992. FieldSet('device_type', name=_('Device Type')),
  993. FieldSet('module_type', name=_('Module Type')),
  994. ),
  995. 'name', 'label', 'type', 'color', 'positions', 'description',
  996. ),
  997. )
  998. class Meta:
  999. model = RearPortTemplate
  1000. fields = [
  1001. 'device_type', 'module_type', 'name', 'label', 'type', 'color', 'positions', 'description',
  1002. ]
  1003. class ModuleBayTemplateForm(ModularComponentTemplateForm):
  1004. fieldsets = (
  1005. FieldSet(
  1006. TabbedGroups(
  1007. FieldSet('device_type', name=_('Device Type')),
  1008. FieldSet('module_type', name=_('Module Type')),
  1009. ),
  1010. 'name', 'label', 'position', 'description',
  1011. ),
  1012. )
  1013. class Meta:
  1014. model = ModuleBayTemplate
  1015. fields = [
  1016. 'device_type', 'module_type', 'name', 'label', 'position', 'description',
  1017. ]
  1018. class DeviceBayTemplateForm(ComponentTemplateForm):
  1019. fieldsets = (
  1020. FieldSet('device_type', 'name', 'label', 'description'),
  1021. )
  1022. class Meta:
  1023. model = DeviceBayTemplate
  1024. fields = [
  1025. 'device_type', 'name', 'label', 'description',
  1026. ]
  1027. class InventoryItemTemplateForm(ComponentTemplateForm):
  1028. parent = DynamicModelChoiceField(
  1029. label=_('Parent'),
  1030. queryset=InventoryItemTemplate.objects.all(),
  1031. required=False,
  1032. query_params={
  1033. 'device_type_id': '$device_type'
  1034. }
  1035. )
  1036. role = DynamicModelChoiceField(
  1037. label=_('Role'),
  1038. queryset=InventoryItemRole.objects.all(),
  1039. required=False
  1040. )
  1041. manufacturer = DynamicModelChoiceField(
  1042. label=_('Manufacturer'),
  1043. queryset=Manufacturer.objects.all(),
  1044. required=False
  1045. )
  1046. # Assigned component selectors
  1047. consoleporttemplate = DynamicModelChoiceField(
  1048. queryset=ConsolePortTemplate.objects.all(),
  1049. required=False,
  1050. query_params={
  1051. 'device_type_id': '$device_type'
  1052. },
  1053. label=_('Console port template')
  1054. )
  1055. consoleserverporttemplate = DynamicModelChoiceField(
  1056. queryset=ConsoleServerPortTemplate.objects.all(),
  1057. required=False,
  1058. query_params={
  1059. 'device_type_id': '$device_type'
  1060. },
  1061. label=_('Console server port template')
  1062. )
  1063. frontporttemplate = DynamicModelChoiceField(
  1064. queryset=FrontPortTemplate.objects.all(),
  1065. required=False,
  1066. query_params={
  1067. 'device_type_id': '$device_type'
  1068. },
  1069. label=_('Front port template')
  1070. )
  1071. interfacetemplate = DynamicModelChoiceField(
  1072. queryset=InterfaceTemplate.objects.all(),
  1073. required=False,
  1074. query_params={
  1075. 'device_type_id': '$device_type'
  1076. },
  1077. label=_('Interface template')
  1078. )
  1079. poweroutlettemplate = DynamicModelChoiceField(
  1080. queryset=PowerOutletTemplate.objects.all(),
  1081. required=False,
  1082. query_params={
  1083. 'device_type_id': '$device_type'
  1084. },
  1085. label=_('Power outlet template')
  1086. )
  1087. powerporttemplate = DynamicModelChoiceField(
  1088. queryset=PowerPortTemplate.objects.all(),
  1089. required=False,
  1090. query_params={
  1091. 'device_type_id': '$device_type'
  1092. },
  1093. label=_('Power port template')
  1094. )
  1095. rearporttemplate = DynamicModelChoiceField(
  1096. queryset=RearPortTemplate.objects.all(),
  1097. required=False,
  1098. query_params={
  1099. 'device_type_id': '$device_type'
  1100. },
  1101. label=_('Rear port template')
  1102. )
  1103. fieldsets = (
  1104. FieldSet(
  1105. 'device_type', 'parent', 'name', 'label', 'role', 'manufacturer', 'part_id', 'description',
  1106. ),
  1107. FieldSet(
  1108. TabbedGroups(
  1109. FieldSet('interfacetemplate', name=_('Interface')),
  1110. FieldSet('consoleporttemplate', name=_('Console Port')),
  1111. FieldSet('consoleserverporttemplate', name=_('Console Server Port')),
  1112. FieldSet('frontporttemplate', name=_('Front Port')),
  1113. FieldSet('rearporttemplate', name=_('Rear Port')),
  1114. FieldSet('powerporttemplate', name=_('Power Port')),
  1115. FieldSet('poweroutlettemplate', name=_('Power Outlet')),
  1116. ),
  1117. name=_('Component Assignment')
  1118. )
  1119. )
  1120. class Meta:
  1121. model = InventoryItemTemplate
  1122. fields = [
  1123. 'device_type', 'parent', 'name', 'label', 'role', 'manufacturer', 'part_id', 'description',
  1124. ]
  1125. def __init__(self, *args, **kwargs):
  1126. instance = kwargs.get('instance')
  1127. initial = kwargs.get('initial', {}).copy()
  1128. component_type = initial.get('component_type')
  1129. component_id = initial.get('component_id')
  1130. if instance:
  1131. # When editing set the initial value for component selection
  1132. for component_model in ContentType.objects.filter(MODULAR_COMPONENT_TEMPLATE_MODELS):
  1133. if type(instance.component) is component_model.model_class():
  1134. initial[component_model.model] = instance.component
  1135. break
  1136. elif component_type and component_id:
  1137. # When adding the InventoryItem from a component page
  1138. content_type = ContentType.objects.filter(
  1139. MODULAR_COMPONENT_TEMPLATE_MODELS
  1140. ).filter(pk=component_type).first()
  1141. if content_type:
  1142. if component := content_type.model_class().objects.filter(pk=component_id).first():
  1143. initial[content_type.model] = component
  1144. kwargs['initial'] = initial
  1145. super().__init__(*args, **kwargs)
  1146. def clean(self):
  1147. super().clean()
  1148. # Handle object assignment
  1149. selected_objects = [
  1150. field for field in (
  1151. 'consoleporttemplate', 'consoleserverporttemplate', 'frontporttemplate', 'interfacetemplate',
  1152. 'poweroutlettemplate', 'powerporttemplate', 'rearporttemplate'
  1153. ) if self.cleaned_data[field]
  1154. ]
  1155. if len(selected_objects) > 1:
  1156. raise forms.ValidationError(_("An InventoryItem can only be assigned to a single component."))
  1157. elif selected_objects:
  1158. self.instance.component = self.cleaned_data[selected_objects[0]]
  1159. else:
  1160. self.instance.component = None
  1161. #
  1162. # Device components
  1163. #
  1164. class DeviceComponentForm(OwnerMixin, NetBoxModelForm):
  1165. device = DynamicModelChoiceField(
  1166. label=_('Device'),
  1167. queryset=Device.objects.all(),
  1168. selector=True
  1169. )
  1170. def __init__(self, *args, **kwargs):
  1171. super().__init__(*args, **kwargs)
  1172. # Disable reassignment of Device when editing an existing instance
  1173. if self.instance.pk:
  1174. self.fields['device'].disabled = True
  1175. class ModularDeviceComponentForm(DeviceComponentForm):
  1176. module = DynamicModelChoiceField(
  1177. label=_('Module'),
  1178. queryset=Module.objects.all(),
  1179. required=False,
  1180. query_params={
  1181. 'device_id': '$device',
  1182. }
  1183. )
  1184. class ConsolePortForm(ModularDeviceComponentForm):
  1185. fieldsets = (
  1186. FieldSet(
  1187. 'device', 'module', 'name', 'label', 'type', 'speed', 'mark_connected', 'description', 'tags',
  1188. ),
  1189. )
  1190. class Meta:
  1191. model = ConsolePort
  1192. fields = [
  1193. 'device', 'module', 'name', 'label', 'type', 'speed', 'mark_connected', 'description', 'owner', 'tags',
  1194. ]
  1195. class ConsoleServerPortForm(ModularDeviceComponentForm):
  1196. fieldsets = (
  1197. FieldSet(
  1198. 'device', 'module', 'name', 'label', 'type', 'speed', 'mark_connected', 'description', 'tags',
  1199. ),
  1200. )
  1201. class Meta:
  1202. model = ConsoleServerPort
  1203. fields = [
  1204. 'device', 'module', 'name', 'label', 'type', 'speed', 'mark_connected', 'description', 'owner', 'tags',
  1205. ]
  1206. class PowerPortForm(ModularDeviceComponentForm):
  1207. fieldsets = (
  1208. FieldSet(
  1209. 'device', 'module', 'name', 'label', 'type', 'maximum_draw', 'allocated_draw', 'mark_connected',
  1210. 'description', 'tags',
  1211. ),
  1212. )
  1213. class Meta:
  1214. model = PowerPort
  1215. fields = [
  1216. 'device', 'module', 'name', 'label', 'type', 'maximum_draw', 'allocated_draw', 'mark_connected',
  1217. 'description', 'owner', 'tags',
  1218. ]
  1219. class PowerOutletForm(ModularDeviceComponentForm):
  1220. power_port = DynamicModelChoiceField(
  1221. label=_('Power port'),
  1222. queryset=PowerPort.objects.all(),
  1223. required=False,
  1224. query_params={
  1225. 'device_id': '$device',
  1226. }
  1227. )
  1228. fieldsets = (
  1229. FieldSet(
  1230. 'device', 'module', 'name', 'label', 'type', 'status', 'color', 'power_port', 'feed_leg', 'mark_connected',
  1231. 'description', 'owner', 'tags',
  1232. ),
  1233. )
  1234. class Meta:
  1235. model = PowerOutlet
  1236. fields = [
  1237. 'device', 'module', 'name', 'label', 'type', 'status', 'color', 'power_port', 'feed_leg', 'mark_connected',
  1238. 'description', 'tags',
  1239. ]
  1240. class InterfaceForm(InterfaceCommonForm, ModularDeviceComponentForm):
  1241. vdcs = DynamicModelMultipleChoiceField(
  1242. queryset=VirtualDeviceContext.objects.all(),
  1243. required=False,
  1244. label=_('Virtual device contexts'),
  1245. initial_params={
  1246. 'interfaces': '$parent',
  1247. },
  1248. query_params={
  1249. 'device_id': '$device',
  1250. }
  1251. )
  1252. parent = DynamicModelChoiceField(
  1253. queryset=Interface.objects.all(),
  1254. required=False,
  1255. label=_('Parent interface'),
  1256. query_params={
  1257. 'virtual_chassis_member_id': '$device',
  1258. }
  1259. )
  1260. bridge = DynamicModelChoiceField(
  1261. queryset=Interface.objects.all(),
  1262. required=False,
  1263. label=_('Bridged interface'),
  1264. query_params={
  1265. 'virtual_chassis_member_id': '$device',
  1266. }
  1267. )
  1268. lag = DynamicModelChoiceField(
  1269. queryset=Interface.objects.all(),
  1270. required=False,
  1271. label=_('LAG interface'),
  1272. query_params={
  1273. 'virtual_chassis_member_id': '$device',
  1274. 'type': 'lag',
  1275. }
  1276. )
  1277. wireless_lan_group = DynamicModelChoiceField(
  1278. queryset=WirelessLANGroup.objects.all(),
  1279. required=False,
  1280. label=_('Wireless LAN group')
  1281. )
  1282. wireless_lans = DynamicModelMultipleChoiceField(
  1283. queryset=WirelessLAN.objects.all(),
  1284. required=False,
  1285. label=_('Wireless LANs'),
  1286. query_params={
  1287. 'group_id': '$wireless_lan_group',
  1288. }
  1289. )
  1290. vlan_group = DynamicModelChoiceField(
  1291. queryset=VLANGroup.objects.all(),
  1292. required=False,
  1293. label=_('VLAN group'),
  1294. help_text=_("Filter VLANs available for assignment by group.")
  1295. )
  1296. untagged_vlan = DynamicModelChoiceField(
  1297. queryset=VLAN.objects.all(),
  1298. required=False,
  1299. label=_('Untagged VLAN'),
  1300. query_params={
  1301. 'group_id': '$vlan_group',
  1302. 'available_on_device': '$device',
  1303. }
  1304. )
  1305. tagged_vlans = DynamicModelMultipleChoiceField(
  1306. queryset=VLAN.objects.all(),
  1307. required=False,
  1308. label=_('Tagged VLANs'),
  1309. query_params={
  1310. 'group_id': '$vlan_group',
  1311. 'available_on_device': '$device',
  1312. }
  1313. )
  1314. qinq_svlan = DynamicModelChoiceField(
  1315. queryset=VLAN.objects.all(),
  1316. required=False,
  1317. label=_('Q-in-Q Service VLAN'),
  1318. query_params={
  1319. 'group_id': '$vlan_group',
  1320. 'available_on_device': '$device',
  1321. 'qinq_role': VLANQinQRoleChoices.ROLE_SERVICE,
  1322. }
  1323. )
  1324. vrf = DynamicModelChoiceField(
  1325. queryset=VRF.objects.all(),
  1326. required=False,
  1327. label=_('VRF')
  1328. )
  1329. primary_mac_address = DynamicModelChoiceField(
  1330. queryset=MACAddress.objects.all(),
  1331. label=_('Primary MAC address'),
  1332. required=False,
  1333. quick_add=True,
  1334. quick_add_params={'interface': '$pk'}
  1335. )
  1336. wwn = forms.CharField(
  1337. empty_value=None,
  1338. required=False,
  1339. label=_('WWN')
  1340. )
  1341. vlan_translation_policy = DynamicModelChoiceField(
  1342. queryset=VLANTranslationPolicy.objects.all(),
  1343. required=False,
  1344. label=_('VLAN Translation Policy')
  1345. )
  1346. fieldsets = (
  1347. FieldSet(
  1348. 'device', 'module', 'name', 'label', 'type', 'speed', 'duplex', 'description', 'tags', name=_('Interface')
  1349. ),
  1350. FieldSet('vrf', 'primary_mac_address', 'wwn', name=_('Addressing')),
  1351. FieldSet('vdcs', 'mtu', 'tx_power', 'enabled', 'mgmt_only', 'mark_connected', name=_('Operation')),
  1352. FieldSet('parent', 'bridge', 'lag', name=_('Related Interfaces')),
  1353. FieldSet('poe_mode', 'poe_type', name=_('PoE')),
  1354. FieldSet(
  1355. 'mode', 'vlan_group', 'untagged_vlan', 'tagged_vlans', 'qinq_svlan', 'vlan_translation_policy',
  1356. name=_('802.1Q Switching')
  1357. ),
  1358. FieldSet(
  1359. 'rf_role', 'rf_channel', 'rf_channel_frequency', 'rf_channel_width', 'wireless_lan_group', 'wireless_lans',
  1360. name=_('Wireless')
  1361. ),
  1362. )
  1363. class Meta:
  1364. model = Interface
  1365. fields = [
  1366. 'device', 'module', 'vdcs', 'name', 'label', 'type', 'speed', 'duplex', 'enabled', 'parent', 'bridge',
  1367. 'lag', 'wwn', 'mtu', 'mgmt_only', 'mark_connected', 'description', 'poe_mode', 'poe_type', 'mode',
  1368. 'rf_role', 'rf_channel', 'rf_channel_frequency', 'rf_channel_width', 'tx_power', 'wireless_lans',
  1369. 'untagged_vlan', 'tagged_vlans', 'qinq_svlan', 'vlan_translation_policy', 'vrf', 'primary_mac_address',
  1370. 'owner', 'tags',
  1371. ]
  1372. widgets = {
  1373. 'speed': NumberWithOptions(
  1374. options=InterfaceSpeedChoices
  1375. ),
  1376. 'mode': HTMXSelect(),
  1377. }
  1378. labels = {
  1379. 'mode': '802.1Q Mode',
  1380. }
  1381. class FrontPortForm(ModularDeviceComponentForm):
  1382. rear_port = DynamicModelChoiceField(
  1383. queryset=RearPort.objects.all(),
  1384. query_params={
  1385. 'device_id': '$device',
  1386. }
  1387. )
  1388. fieldsets = (
  1389. FieldSet(
  1390. 'device', 'module', 'name', 'label', 'type', 'color', 'rear_port', 'rear_port_position', 'mark_connected',
  1391. 'description', 'tags',
  1392. ),
  1393. )
  1394. class Meta:
  1395. model = FrontPort
  1396. fields = [
  1397. 'device', 'module', 'name', 'label', 'type', 'color', 'rear_port', 'rear_port_position', 'mark_connected',
  1398. 'description', 'owner', 'tags',
  1399. ]
  1400. class RearPortForm(ModularDeviceComponentForm):
  1401. fieldsets = (
  1402. FieldSet(
  1403. 'device', 'module', 'name', 'label', 'type', 'color', 'positions', 'mark_connected', 'description', 'tags',
  1404. ),
  1405. )
  1406. class Meta:
  1407. model = RearPort
  1408. fields = [
  1409. 'device', 'module', 'name', 'label', 'type', 'color', 'positions', 'mark_connected', 'description', 'owner',
  1410. 'tags',
  1411. ]
  1412. class ModuleBayForm(ModularDeviceComponentForm):
  1413. fieldsets = (
  1414. FieldSet('device', 'module', 'name', 'label', 'position', 'description', 'tags',),
  1415. )
  1416. class Meta:
  1417. model = ModuleBay
  1418. fields = [
  1419. 'device', 'module', 'name', 'label', 'position', 'description', 'owner', 'tags',
  1420. ]
  1421. class DeviceBayForm(DeviceComponentForm):
  1422. fieldsets = (
  1423. FieldSet('device', 'name', 'label', 'description', 'tags',),
  1424. )
  1425. class Meta:
  1426. model = DeviceBay
  1427. fields = [
  1428. 'device', 'name', 'label', 'description', 'owner', 'tags',
  1429. ]
  1430. class PopulateDeviceBayForm(forms.Form):
  1431. installed_device = forms.ModelChoiceField(
  1432. queryset=Device.objects.all(),
  1433. label=_('Child Device'),
  1434. help_text=_("Child devices must first be created and assigned to the site and rack of the parent device.")
  1435. )
  1436. def __init__(self, device_bay, *args, **kwargs):
  1437. super().__init__(*args, **kwargs)
  1438. self.fields['installed_device'].queryset = Device.objects.filter(
  1439. site=device_bay.device.site,
  1440. rack=device_bay.device.rack,
  1441. parent_bay__isnull=True,
  1442. device_type__u_height=0,
  1443. device_type__subdevice_role=SubdeviceRoleChoices.ROLE_CHILD
  1444. ).exclude(pk=device_bay.device.pk)
  1445. class InventoryItemForm(DeviceComponentForm):
  1446. parent = DynamicModelChoiceField(
  1447. label=_('Parent'),
  1448. queryset=InventoryItem.objects.all(),
  1449. required=False,
  1450. query_params={
  1451. 'device_id': '$device'
  1452. }
  1453. )
  1454. role = DynamicModelChoiceField(
  1455. label=_('Role'),
  1456. queryset=InventoryItemRole.objects.all(),
  1457. required=False
  1458. )
  1459. manufacturer = DynamicModelChoiceField(
  1460. label=_('Manufacturer'),
  1461. queryset=Manufacturer.objects.all(),
  1462. required=False
  1463. )
  1464. # Assigned component selectors
  1465. consoleport = DynamicModelChoiceField(
  1466. queryset=ConsolePort.objects.all(),
  1467. required=False,
  1468. query_params={
  1469. 'device_id': '$device'
  1470. },
  1471. label=_('Console port')
  1472. )
  1473. consoleserverport = DynamicModelChoiceField(
  1474. queryset=ConsoleServerPort.objects.all(),
  1475. required=False,
  1476. query_params={
  1477. 'device_id': '$device'
  1478. },
  1479. label=_('Console server port')
  1480. )
  1481. frontport = DynamicModelChoiceField(
  1482. queryset=FrontPort.objects.all(),
  1483. required=False,
  1484. query_params={
  1485. 'device_id': '$device'
  1486. },
  1487. label=_('Front port')
  1488. )
  1489. interface = DynamicModelChoiceField(
  1490. queryset=Interface.objects.all(),
  1491. required=False,
  1492. query_params={
  1493. 'device_id': '$device'
  1494. },
  1495. label=_('Interface')
  1496. )
  1497. poweroutlet = DynamicModelChoiceField(
  1498. queryset=PowerOutlet.objects.all(),
  1499. required=False,
  1500. query_params={
  1501. 'device_id': '$device'
  1502. },
  1503. label=_('Power outlet')
  1504. )
  1505. powerport = DynamicModelChoiceField(
  1506. queryset=PowerPort.objects.all(),
  1507. required=False,
  1508. query_params={
  1509. 'device_id': '$device'
  1510. },
  1511. label=_('Power port')
  1512. )
  1513. rearport = DynamicModelChoiceField(
  1514. queryset=RearPort.objects.all(),
  1515. required=False,
  1516. query_params={
  1517. 'device_id': '$device'
  1518. },
  1519. label=_('Rear port')
  1520. )
  1521. fieldsets = (
  1522. FieldSet(
  1523. 'device', 'parent', 'name', 'label', 'status', 'role', 'description', 'tags',
  1524. name=_('Inventory Item')
  1525. ),
  1526. FieldSet('manufacturer', 'part_id', 'serial', 'asset_tag', name=_('Hardware')),
  1527. FieldSet(
  1528. TabbedGroups(
  1529. FieldSet('interface', name=_('Interface')),
  1530. FieldSet('consoleport', name=_('Console Port')),
  1531. FieldSet('consoleserverport', name=_('Console Server Port')),
  1532. FieldSet('frontport', name=_('Front Port')),
  1533. FieldSet('rearport', name=_('Rear Port')),
  1534. FieldSet('powerport', name=_('Power Port')),
  1535. FieldSet('poweroutlet', name=_('Power Outlet')),
  1536. ),
  1537. name=_('Component Assignment')
  1538. )
  1539. )
  1540. class Meta:
  1541. model = InventoryItem
  1542. fields = [
  1543. 'device', 'parent', 'name', 'label', 'role', 'manufacturer', 'part_id', 'serial', 'asset_tag',
  1544. 'status', 'description', 'owner', 'tags',
  1545. ]
  1546. def __init__(self, *args, **kwargs):
  1547. instance = kwargs.get('instance')
  1548. initial = kwargs.get('initial', {}).copy()
  1549. component_type = initial.get('component_type')
  1550. component_id = initial.get('component_id')
  1551. if instance:
  1552. # When editing set the initial value for component selection
  1553. for component_model in ContentType.objects.filter(MODULAR_COMPONENT_MODELS):
  1554. if type(instance.component) is component_model.model_class():
  1555. initial[component_model.model] = instance.component
  1556. break
  1557. elif component_type and component_id:
  1558. # When adding the InventoryItem from a component page
  1559. if content_type := ContentType.objects.filter(MODULAR_COMPONENT_MODELS).filter(pk=component_type).first():
  1560. if component := content_type.model_class().objects.filter(pk=component_id).first():
  1561. initial[content_type.model] = component
  1562. kwargs['initial'] = initial
  1563. super().__init__(*args, **kwargs)
  1564. # Specifically allow editing the device of IntentoryItems
  1565. if self.instance.pk:
  1566. self.fields['device'].disabled = False
  1567. def clean(self):
  1568. super().clean()
  1569. # Handle object assignment
  1570. selected_objects = [
  1571. field for field in (
  1572. 'consoleport', 'consoleserverport', 'frontport', 'interface', 'poweroutlet', 'powerport', 'rearport'
  1573. ) if self.cleaned_data[field]
  1574. ]
  1575. if len(selected_objects) > 1:
  1576. raise forms.ValidationError(_("An InventoryItem can only be assigned to a single component."))
  1577. elif selected_objects:
  1578. self.instance.component = self.cleaned_data[selected_objects[0]]
  1579. else:
  1580. self.instance.component = None
  1581. class InventoryItemRoleForm(OrganizationalModelForm):
  1582. fieldsets = (
  1583. FieldSet('name', 'slug', 'color', 'description', 'tags', name=_('Inventory Item Role')),
  1584. )
  1585. class Meta:
  1586. model = InventoryItemRole
  1587. fields = [
  1588. 'name', 'slug', 'color', 'description', 'owner', 'tags',
  1589. ]
  1590. class VirtualDeviceContextForm(TenancyForm, PrimaryModelForm):
  1591. device = DynamicModelChoiceField(
  1592. label=_('Device'),
  1593. queryset=Device.objects.all(),
  1594. selector=True
  1595. )
  1596. primary_ip4 = DynamicModelChoiceField(
  1597. queryset=IPAddress.objects.all(),
  1598. label=_('Primary IPv4'),
  1599. required=False,
  1600. query_params={
  1601. 'device_id': '$device',
  1602. 'family': '4',
  1603. }
  1604. )
  1605. primary_ip6 = DynamicModelChoiceField(
  1606. queryset=IPAddress.objects.all(),
  1607. label=_('Primary IPv6'),
  1608. required=False,
  1609. query_params={
  1610. 'device_id': '$device',
  1611. 'family': '6',
  1612. }
  1613. )
  1614. fieldsets = (
  1615. FieldSet(
  1616. 'device', 'name', 'status', 'identifier', 'primary_ip4', 'primary_ip6', 'tags',
  1617. name=_('Virtual Device Context')
  1618. ),
  1619. FieldSet('tenant_group', 'tenant', name=_('Tenancy'))
  1620. )
  1621. class Meta:
  1622. model = VirtualDeviceContext
  1623. fields = [
  1624. 'device', 'name', 'status', 'identifier', 'primary_ip4', 'primary_ip6', 'tenant_group', 'tenant', 'owner',
  1625. 'comments', 'tags'
  1626. ]
  1627. #
  1628. # Addressing
  1629. #
  1630. class MACAddressForm(PrimaryModelForm):
  1631. mac_address = forms.CharField(
  1632. required=True,
  1633. label=_('MAC address')
  1634. )
  1635. interface = DynamicModelChoiceField(
  1636. label=_('Interface'),
  1637. queryset=Interface.objects.all(),
  1638. required=False,
  1639. selector=True,
  1640. context={
  1641. 'parent': 'device',
  1642. },
  1643. )
  1644. vminterface = DynamicModelChoiceField(
  1645. label=_('VM Interface'),
  1646. queryset=VMInterface.objects.all(),
  1647. required=False,
  1648. selector=True,
  1649. context={
  1650. 'parent': 'virtual_machine',
  1651. },
  1652. )
  1653. fieldsets = (
  1654. FieldSet(
  1655. 'mac_address', 'description', 'tags',
  1656. ),
  1657. FieldSet(
  1658. TabbedGroups(
  1659. FieldSet('interface', name=_('Device')),
  1660. FieldSet('vminterface', name=_('Virtual Machine')),
  1661. ),
  1662. ),
  1663. )
  1664. class Meta:
  1665. model = MACAddress
  1666. fields = [
  1667. 'mac_address', 'interface', 'vminterface', 'description', 'owner', 'tags',
  1668. ]
  1669. def __init__(self, *args, **kwargs):
  1670. # Initialize helper selectors
  1671. instance = kwargs.get('instance')
  1672. initial = kwargs.get('initial', {}).copy()
  1673. if instance:
  1674. if type(instance.assigned_object) is Interface:
  1675. initial['interface'] = instance.assigned_object
  1676. elif type(instance.assigned_object) is VMInterface:
  1677. initial['vminterface'] = instance.assigned_object
  1678. kwargs['initial'] = initial
  1679. super().__init__(*args, **kwargs)
  1680. if instance and instance.assigned_object and instance.assigned_object.primary_mac_address:
  1681. if instance.assigned_object.primary_mac_address.pk == instance.pk:
  1682. self.fields['interface'].disabled = True
  1683. self.fields['vminterface'].disabled = True
  1684. def clean(self):
  1685. super().clean()
  1686. # Handle object assignment
  1687. selected_objects = [
  1688. field for field in ('interface', 'vminterface') if self.cleaned_data[field]
  1689. ]
  1690. if len(selected_objects) > 1:
  1691. raise forms.ValidationError({
  1692. selected_objects[1]: _("A MAC address can only be assigned to a single object.")
  1693. })
  1694. elif selected_objects:
  1695. self.instance.assigned_object = self.cleaned_data[selected_objects[0]]
  1696. else:
  1697. self.instance.assigned_object = None