model_forms.py 61 KB

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