model_forms.py 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659
  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.html import format_html
  5. from django.utils.translation import gettext_lazy as _
  6. from timezone_field import TimeZoneFormField
  7. from dcim.choices import *
  8. from dcim.constants import *
  9. from dcim.forms.mixins import FrontPortFormMixin
  10. from dcim.models import *
  11. from extras.models import ConfigTemplate
  12. from ipam.choices import VLANQinQRoleChoices
  13. from ipam.models import ASN, VLAN, VRF, IPAddress, VLANGroup, VLANTranslationPolicy
  14. from netbox.choices import WeightUnitChoices
  15. from netbox.forms import NestedGroupModelForm, NetBoxModelForm, OrganizationalModelForm, PrimaryModelForm
  16. from netbox.forms.mixins import ChangelogMessageMixin, OwnerMixin
  17. from tenancy.forms import TenancyForm
  18. from users.models import User
  19. from utilities.choices import Choice
  20. from utilities.forms import add_blank_choice, get_field_value
  21. from utilities.forms.fields import (
  22. ChoiceField,
  23. DynamicModelChoiceField,
  24. DynamicModelMultipleChoiceField,
  25. JSONField,
  26. NumericArrayField,
  27. SlugField,
  28. TypedChoiceField,
  29. )
  30. from utilities.forms.rendering import FieldSet, InlineFields, M2MAddRemoveFields, TabbedGroups
  31. from utilities.forms.widgets import (
  32. APISelect,
  33. ClearableFileInput,
  34. ClearableSelect,
  35. DatePicker,
  36. HTMXSelect,
  37. NumberWithOptions,
  38. SelectWithPK,
  39. )
  40. from utilities.jsonschema import JSONSchemaProperty
  41. from virtualization.models import Cluster, VMInterface
  42. from wireless.choices import WirelessChannelChoices, WirelessRoleChoices
  43. from wireless.models import WirelessLAN, WirelessLANGroup
  44. from .common import InterfaceCommonForm, ModuleCommonForm
  45. __all__ = (
  46. 'CableBundleForm',
  47. 'CableForm',
  48. 'ConsolePortForm',
  49. 'ConsolePortTemplateForm',
  50. 'ConsoleServerPortForm',
  51. 'ConsoleServerPortTemplateForm',
  52. 'CoolingFeedForm',
  53. 'CoolingIntakeForm',
  54. 'CoolingIntakeTemplateForm',
  55. 'CoolingOutflowForm',
  56. 'CoolingOutflowTemplateForm',
  57. 'CoolingSourceForm',
  58. 'DeviceBayForm',
  59. 'DeviceBayTemplateForm',
  60. 'DeviceForm',
  61. 'DeviceRoleForm',
  62. 'DeviceTypeForm',
  63. 'DeviceVCMembershipForm',
  64. 'FrontPortForm',
  65. 'FrontPortTemplateForm',
  66. 'InterfaceForm',
  67. 'InterfaceTemplateForm',
  68. 'InventoryItemForm',
  69. 'InventoryItemRoleForm',
  70. 'InventoryItemTemplateForm',
  71. 'LocationForm',
  72. 'MACAddressForm',
  73. 'MACBlockForm',
  74. 'ManufacturerForm',
  75. 'ModuleBayForm',
  76. 'ModuleBayTemplateForm',
  77. 'ModuleBayTypeForm',
  78. 'ModuleForm',
  79. 'ModuleTypeForm',
  80. 'ModuleTypeProfileForm',
  81. 'PlatformForm',
  82. 'PopulateDeviceBayForm',
  83. 'PowerFeedForm',
  84. 'PowerOutletForm',
  85. 'PowerOutletTemplateForm',
  86. 'PowerPanelForm',
  87. 'PowerPortForm',
  88. 'PowerPortTemplateForm',
  89. 'RackForm',
  90. 'RackGroupForm',
  91. 'RackReservationForm',
  92. 'RackRoleForm',
  93. 'RackTypeForm',
  94. 'RearPortForm',
  95. 'RearPortTemplateForm',
  96. 'RegionForm',
  97. 'SiteForm',
  98. 'SiteGroupForm',
  99. 'VCMemberSelectForm',
  100. 'VirtualChassisForm',
  101. 'VirtualDeviceContextForm'
  102. )
  103. class RegionForm(NestedGroupModelForm):
  104. parent = DynamicModelChoiceField(
  105. label=_('Parent'),
  106. queryset=Region.objects.all(),
  107. required=False
  108. )
  109. fieldsets = (
  110. FieldSet('parent', 'name', 'slug', 'description', 'tags'),
  111. )
  112. class Meta:
  113. model = Region
  114. fields = (
  115. 'parent', 'name', 'slug', 'description', 'owner', 'tags', 'comments',
  116. )
  117. class SiteGroupForm(NestedGroupModelForm):
  118. parent = DynamicModelChoiceField(
  119. label=_('Parent'),
  120. queryset=SiteGroup.objects.all(),
  121. required=False
  122. )
  123. fieldsets = (
  124. FieldSet('parent', 'name', 'slug', 'description', 'tags'),
  125. )
  126. class Meta:
  127. model = SiteGroup
  128. fields = (
  129. 'parent', 'name', 'slug', 'description', 'owner', 'comments', 'tags',
  130. )
  131. class SiteForm(TenancyForm, PrimaryModelForm):
  132. status = ChoiceField(
  133. label=_('Status'),
  134. choices=SiteStatusChoices,
  135. initial=SiteStatusChoices.STATUS_ACTIVE,
  136. )
  137. region = DynamicModelChoiceField(
  138. label=_('Region'),
  139. queryset=Region.objects.all(),
  140. required=False,
  141. quick_add=True
  142. )
  143. group = DynamicModelChoiceField(
  144. label=_('Group'),
  145. queryset=SiteGroup.objects.all(),
  146. required=False,
  147. quick_add=True
  148. )
  149. asns = DynamicModelMultipleChoiceField(
  150. queryset=ASN.objects.all(),
  151. label=_('ASNs'),
  152. required=False
  153. )
  154. add_asns = DynamicModelMultipleChoiceField(
  155. queryset=ASN.objects.all(),
  156. label=_('Add ASNs'),
  157. required=False
  158. )
  159. remove_asns = DynamicModelMultipleChoiceField(
  160. queryset=ASN.objects.all(),
  161. label=_('Remove ASNs'),
  162. required=False
  163. )
  164. slug = SlugField()
  165. time_zone = TimeZoneFormField(
  166. label=_('Time zone'),
  167. choices=add_blank_choice(TimeZoneFormField().choices),
  168. required=False
  169. )
  170. fieldsets = (
  171. FieldSet(
  172. 'name', 'slug', 'status', 'region', 'group', 'facility', M2MAddRemoveFields('asns'), 'time_zone',
  173. 'description', 'tags',
  174. name=_('Site')
  175. ),
  176. FieldSet('tenant_group', 'tenant', name=_('Tenancy')),
  177. FieldSet('physical_address', 'shipping_address', 'latitude', 'longitude', name=_('Contact Info')),
  178. )
  179. class Meta:
  180. model = Site
  181. fields = (
  182. 'name', 'slug', 'status', 'region', 'group', 'tenant_group', 'tenant', 'facility', 'time_zone',
  183. 'description', 'physical_address', 'shipping_address', 'latitude', 'longitude', 'owner', 'comments', 'tags',
  184. )
  185. widgets = {
  186. 'physical_address': forms.Textarea(
  187. attrs={
  188. 'rows': 3,
  189. }
  190. ),
  191. 'shipping_address': forms.Textarea(
  192. attrs={
  193. 'rows': 3,
  194. }
  195. ),
  196. }
  197. def __init__(self, *args, **kwargs):
  198. super().__init__(*args, **kwargs)
  199. if self.instance.pk and (count := self.instance.asns.count()) >= M2MAddRemoveFields.THRESHOLD:
  200. # Add/remove mode for large M2M sets
  201. self.fields.pop('asns')
  202. self.fields['add_asns'].widget.add_query_param('site_id__n', self.instance.pk)
  203. self.fields['remove_asns'].widget.add_query_param('site_id', self.instance.pk)
  204. self.fields['remove_asns'].help_text = _("{count} ASNs currently assigned").format(count=count)
  205. else:
  206. # Simple mode for new objects or small M2M sets
  207. self.fields.pop('add_asns')
  208. self.fields.pop('remove_asns')
  209. if self.instance.pk:
  210. self.initial['asns'] = list(self.instance.asns.values_list('pk', flat=True))
  211. class LocationForm(TenancyForm, NestedGroupModelForm):
  212. status = ChoiceField(
  213. label=_('Status'),
  214. choices=LocationStatusChoices,
  215. initial=LocationStatusChoices.STATUS_ACTIVE,
  216. )
  217. site = DynamicModelChoiceField(
  218. label=_('Site'),
  219. queryset=Site.objects.all(),
  220. selector=True
  221. )
  222. parent = DynamicModelChoiceField(
  223. label=_('Parent'),
  224. queryset=Location.objects.all(),
  225. required=False,
  226. query_params={
  227. 'site_id': '$site'
  228. }
  229. )
  230. fieldsets = (
  231. FieldSet('site', 'parent', 'name', 'slug', 'status', 'facility', 'description', 'tags', name=_('Location')),
  232. FieldSet('tenant_group', 'tenant', name=_('Tenancy')),
  233. )
  234. class Meta:
  235. model = Location
  236. fields = (
  237. 'site', 'parent', 'name', 'slug', 'status', 'description', 'tenant_group', 'tenant', 'facility', 'owner',
  238. 'comments', 'tags',
  239. )
  240. class RackGroupForm(OrganizationalModelForm):
  241. fieldsets = (
  242. FieldSet('name', 'slug', 'description', 'tags', name=_('Rack Group')),
  243. )
  244. class Meta:
  245. model = RackGroup
  246. fields = [
  247. 'name', 'slug', 'description', 'owner', 'comments', 'tags',
  248. ]
  249. class RackRoleForm(OrganizationalModelForm):
  250. fieldsets = (
  251. FieldSet('name', 'slug', 'color', 'description', 'tags', name=_('Rack Role')),
  252. )
  253. class Meta:
  254. model = RackRole
  255. fields = [
  256. 'name', 'slug', 'color', 'description', 'owner', 'comments', 'tags',
  257. ]
  258. class RackTypeForm(PrimaryModelForm):
  259. form_factor = ChoiceField(
  260. label=_('Form factor'),
  261. choices=RackFormFactorChoices,
  262. )
  263. outer_unit = TypedChoiceField(
  264. label=_('Outer unit'),
  265. choices=add_blank_choice(RackDimensionUnitChoices),
  266. required=False,
  267. )
  268. weight_unit = TypedChoiceField(
  269. label=_('Weight unit'),
  270. choices=add_blank_choice(WeightUnitChoices),
  271. required=False,
  272. )
  273. manufacturer = DynamicModelChoiceField(
  274. label=_('Manufacturer'),
  275. queryset=Manufacturer.objects.all(),
  276. quick_add=True
  277. )
  278. slug = SlugField(
  279. label=_('Slug'),
  280. slug_source='model'
  281. )
  282. fieldsets = (
  283. FieldSet('manufacturer', 'model', 'slug', 'description', 'form_factor', 'tags', name=_('Rack Type')),
  284. FieldSet(
  285. 'width', 'u_height',
  286. InlineFields('outer_width', 'outer_height', 'outer_depth', 'outer_unit', label=_('Outer Dimensions')),
  287. InlineFields('weight', 'max_weight', 'weight_unit', label=_('Weight')),
  288. 'mounting_depth', name=_('Dimensions')
  289. ),
  290. FieldSet('starting_unit', 'desc_units', name=_('Numbering')),
  291. FieldSet('cooling_capability', 'cooling_capacity', name=_('Cooling')),
  292. )
  293. class Meta:
  294. model = RackType
  295. fields = [
  296. 'manufacturer', 'model', 'slug', 'form_factor', 'width', 'u_height', 'starting_unit', 'desc_units',
  297. 'outer_width', 'outer_height', 'outer_depth', 'outer_unit', 'mounting_depth', 'weight', 'max_weight',
  298. 'weight_unit', 'cooling_capability', 'cooling_capacity', 'description', 'owner', 'comments', 'tags',
  299. ]
  300. class RackForm(TenancyForm, PrimaryModelForm):
  301. status = ChoiceField(
  302. label=_('Status'),
  303. choices=RackStatusChoices,
  304. initial=RackStatusChoices.STATUS_ACTIVE,
  305. )
  306. form_factor = TypedChoiceField(
  307. label=_('Form factor'),
  308. choices=add_blank_choice(RackFormFactorChoices),
  309. required=False,
  310. )
  311. outer_unit = TypedChoiceField(
  312. label=_('Outer unit'),
  313. choices=add_blank_choice(RackDimensionUnitChoices),
  314. required=False,
  315. )
  316. airflow = TypedChoiceField(
  317. label=_('Airflow'),
  318. choices=add_blank_choice(RackAirflowChoices),
  319. required=False,
  320. )
  321. weight_unit = TypedChoiceField(
  322. label=_('Weight unit'),
  323. choices=add_blank_choice(WeightUnitChoices),
  324. required=False,
  325. )
  326. site = DynamicModelChoiceField(
  327. label=_('Site'),
  328. queryset=Site.objects.all(),
  329. selector=True
  330. )
  331. location = DynamicModelChoiceField(
  332. label=_('Location'),
  333. queryset=Location.objects.all(),
  334. required=False,
  335. query_params={
  336. 'site_id': '$site'
  337. }
  338. )
  339. group = DynamicModelChoiceField(
  340. label=_('Rack Group'),
  341. queryset=RackGroup.objects.all(),
  342. required=False
  343. )
  344. role = DynamicModelChoiceField(
  345. label=_('Role'),
  346. queryset=RackRole.objects.all(),
  347. required=False
  348. )
  349. rack_type = DynamicModelChoiceField(
  350. label=_('Rack Type'),
  351. queryset=RackType.objects.all(),
  352. required=False,
  353. selector=True,
  354. help_text=_("Select a pre-defined rack type, or set physical characteristics below."),
  355. )
  356. fieldsets = (
  357. FieldSet(
  358. 'site', 'location', 'group', 'name', 'status', 'role', 'rack_type', 'description', 'airflow', 'tags',
  359. name=_('Rack')
  360. ),
  361. FieldSet('cooling_capability', 'cooling_capacity', name=_('Cooling')),
  362. FieldSet('facility_id', 'serial', 'asset_tag', name=_('Inventory Control')),
  363. FieldSet('tenant_group', 'tenant', name=_('Tenancy')),
  364. )
  365. class Meta:
  366. model = Rack
  367. fields = [
  368. 'site', 'location', 'group', 'name', 'facility_id', 'tenant_group', 'tenant', 'status', 'role', 'serial',
  369. 'asset_tag', 'rack_type', 'form_factor', 'width', 'u_height', 'starting_unit', 'desc_units', 'outer_width',
  370. 'outer_height', 'outer_depth', 'outer_unit', 'mounting_depth', 'airflow', 'cooling_capability',
  371. 'cooling_capacity', 'weight', 'max_weight', 'weight_unit', 'description', 'owner', 'comments', 'tags',
  372. ]
  373. def __init__(self, *args, **kwargs):
  374. super().__init__(*args, **kwargs)
  375. # Mimic HTMXSelect()
  376. self.fields['rack_type'].widget.attrs.update({
  377. 'hx-get': '.',
  378. 'hx-include': '#form_fields',
  379. 'hx-target': '#form_fields',
  380. })
  381. # Omit RackType-defined fields if rack_type is set
  382. if get_field_value(self, 'rack_type'):
  383. for field_name in Rack.RACKTYPE_FIELDS:
  384. del self.fields[field_name]
  385. else:
  386. # The form_factor, width, and outer_* fields are deprecated on the Rack model and will be removed in
  387. # NetBox v5.0. Their values should instead be defined on an assigned rack type. (See #22593.)
  388. deprecation_warning = format_html(
  389. '<span class="text-warning"><i class="mdi mdi-alert"></i> {}</span>',
  390. _(
  391. 'Deprecated and will be removed in NetBox v5.0. Assign a rack type to define this attribute '
  392. 'instead.'
  393. )
  394. )
  395. self.fields['form_factor'].help_text = deprecation_warning
  396. self.fields['width'].help_text = deprecation_warning
  397. self.fieldsets = (
  398. *self.fieldsets,
  399. FieldSet(
  400. 'form_factor',
  401. 'width',
  402. 'starting_unit',
  403. 'u_height',
  404. InlineFields(
  405. 'outer_width', 'outer_height', 'outer_depth', 'outer_unit',
  406. label=_('Outer Dimensions'),
  407. help_text=deprecation_warning,
  408. ),
  409. InlineFields(
  410. 'weight', 'max_weight', 'weight_unit', label=_('Weight'),
  411. ),
  412. 'mounting_depth',
  413. 'desc_units',
  414. name=_('Dimensions')
  415. ),
  416. )
  417. class RackReservationForm(TenancyForm, PrimaryModelForm):
  418. status = ChoiceField(
  419. label=_('Status'),
  420. choices=RackReservationStatusChoices,
  421. initial=RackReservationStatusChoices.STATUS_ACTIVE,
  422. )
  423. rack = DynamicModelChoiceField(
  424. label=_('Rack'),
  425. queryset=Rack.objects.all(),
  426. selector=True
  427. )
  428. units = NumericArrayField(
  429. label=_('Units'),
  430. base_field=forms.IntegerField(),
  431. help_text=_("Comma-separated list of numeric unit IDs. A range may be specified using a hyphen.")
  432. )
  433. user = forms.ModelChoiceField(
  434. label=_('User'),
  435. queryset=User.objects.order_by('username')
  436. )
  437. fieldsets = (
  438. FieldSet('rack', 'units', 'status', 'user', 'description', 'tags', name=_('Reservation')),
  439. FieldSet('tenant_group', 'tenant', name=_('Tenancy')),
  440. )
  441. class Meta:
  442. model = RackReservation
  443. fields = [
  444. 'rack', 'units', 'status', 'user', 'tenant_group', 'tenant', 'description', 'owner', 'comments', 'tags',
  445. ]
  446. class ManufacturerForm(OrganizationalModelForm):
  447. fieldsets = (
  448. FieldSet('name', 'slug', 'description', 'tags', name=_('Manufacturer')),
  449. )
  450. class Meta:
  451. model = Manufacturer
  452. fields = [
  453. 'name', 'slug', 'description', 'owner', 'comments', 'tags',
  454. ]
  455. class DeviceTypeForm(PrimaryModelForm):
  456. subdevice_role = TypedChoiceField(
  457. label=_('Parent/child status'),
  458. choices=add_blank_choice(SubdeviceRoleChoices),
  459. required=False,
  460. help_text=_(
  461. 'Parent devices house child devices in device bays. Leave blank if this device type is neither a '
  462. 'parent nor a child.'
  463. ),
  464. )
  465. airflow = TypedChoiceField(
  466. label=_('Airflow'),
  467. choices=add_blank_choice(DeviceAirflowChoices),
  468. required=False,
  469. )
  470. weight_unit = TypedChoiceField(
  471. label=_('Weight unit'),
  472. choices=add_blank_choice(WeightUnitChoices),
  473. required=False,
  474. )
  475. manufacturer = DynamicModelChoiceField(
  476. label=_('Manufacturer'),
  477. queryset=Manufacturer.objects.all(),
  478. quick_add=True
  479. )
  480. default_platform = DynamicModelChoiceField(
  481. label=_('Default platform'),
  482. queryset=Platform.objects.all(),
  483. required=False,
  484. selector=True,
  485. query_params={
  486. 'manufacturer_id': ['$manufacturer', 'null'],
  487. }
  488. )
  489. slug = SlugField(
  490. label=_('Slug'),
  491. slug_source='model'
  492. )
  493. fieldsets = (
  494. FieldSet('manufacturer', 'model', 'slug', 'default_platform', 'description', 'tags', name=_('Device Type')),
  495. FieldSet(
  496. 'u_height', 'exclude_from_utilization', 'is_full_depth', 'part_number', 'subdevice_role',
  497. 'weight', 'weight_unit', name=_('Chassis')
  498. ),
  499. FieldSet('cooling_method', 'airflow', name=_('Cooling')),
  500. FieldSet('end_of_life', name=_('Lifecycle')),
  501. FieldSet('front_image', 'rear_image', name=_('Images')),
  502. )
  503. class Meta:
  504. model = DeviceType
  505. fields = [
  506. 'manufacturer', 'model', 'slug', 'default_platform', 'part_number', 'u_height', 'exclude_from_utilization',
  507. 'is_full_depth', 'subdevice_role', 'airflow', 'cooling_method', 'weight', 'weight_unit', 'end_of_life',
  508. 'front_image',
  509. 'rear_image', 'description', 'owner', 'comments', 'tags',
  510. ]
  511. widgets = {
  512. 'front_image': ClearableFileInput(attrs={
  513. 'accept': DEVICETYPE_IMAGE_FORMATS
  514. }),
  515. 'rear_image': ClearableFileInput(attrs={
  516. 'accept': DEVICETYPE_IMAGE_FORMATS
  517. }),
  518. 'end_of_life': DatePicker(),
  519. }
  520. class ModuleBayTypeForm(PrimaryModelForm):
  521. manufacturer = DynamicModelChoiceField(
  522. label=_('Manufacturer'),
  523. queryset=Manufacturer.objects.all(),
  524. required=False,
  525. )
  526. slug = SlugField(
  527. slug_source='name',
  528. )
  529. fieldsets = (
  530. FieldSet('name', 'slug', 'manufacturer', 'color', 'description', 'tags', name=_('Module Bay Type')),
  531. )
  532. class Meta:
  533. model = ModuleBayType
  534. fields = [
  535. 'name', 'slug', 'manufacturer', 'color', 'description', 'owner', 'comments', 'tags',
  536. ]
  537. class ModuleTypeProfileForm(PrimaryModelForm):
  538. schema = JSONField(
  539. label=_('Schema'),
  540. required=False,
  541. help_text=_("Enter a valid JSON schema to define supported attributes.")
  542. )
  543. fieldsets = (
  544. FieldSet('name', 'description', 'schema', 'tags', name=_('Profile')),
  545. )
  546. class Meta:
  547. model = ModuleTypeProfile
  548. fields = [
  549. 'name', 'description', 'schema', 'owner', 'comments', 'tags',
  550. ]
  551. class ModuleTypeForm(PrimaryModelForm):
  552. airflow = TypedChoiceField(
  553. label=_('Airflow'),
  554. choices=add_blank_choice(ModuleAirflowChoices),
  555. required=False,
  556. )
  557. weight_unit = TypedChoiceField(
  558. label=_('Weight unit'),
  559. choices=add_blank_choice(WeightUnitChoices),
  560. required=False,
  561. )
  562. profile = forms.ModelChoiceField(
  563. queryset=ModuleTypeProfile.objects.all(),
  564. label=_('Profile'),
  565. required=False,
  566. widget=HTMXSelect(hx_target_id='profile-attributes')
  567. )
  568. manufacturer = DynamicModelChoiceField(
  569. label=_('Manufacturer'),
  570. queryset=Manufacturer.objects.all()
  571. )
  572. module_bay_types = DynamicModelMultipleChoiceField(
  573. label=_('Module bay types'),
  574. queryset=ModuleBayType.objects.all(),
  575. required=False,
  576. )
  577. @property
  578. def fieldsets(self):
  579. return [
  580. FieldSet('manufacturer', 'model', 'part_number', 'description', 'tags', name=_('Module Type')),
  581. FieldSet('weight', 'weight_unit', name=_('Hardware')),
  582. FieldSet('cooling_method', 'airflow', name=_('Cooling')),
  583. FieldSet('module_bay_types', name=_('Bay Type Compatibility')),
  584. FieldSet('end_of_life', name=_('Lifecycle')),
  585. FieldSet('profile', *self.attr_fields, name=_('Profile & Attributes'), html_id='profile-attributes')
  586. ]
  587. class Meta:
  588. model = ModuleType
  589. fields = [
  590. 'profile', 'manufacturer', 'model', 'part_number', 'description', 'cooling_method', 'airflow', 'weight',
  591. 'weight_unit', 'module_bay_types', 'end_of_life', 'owner', 'comments', 'tags',
  592. ]
  593. widgets = {
  594. 'end_of_life': DatePicker(),
  595. }
  596. def __init__(self, *args, **kwargs):
  597. super().__init__(*args, **kwargs)
  598. # Track profile-specific attribute fields
  599. self.attr_fields = []
  600. # Retrieve assigned ModuleTypeProfile, if any
  601. if not (profile_id := get_field_value(self, 'profile')):
  602. return
  603. if not (profile := ModuleTypeProfile.objects.filter(pk=profile_id).first()):
  604. return
  605. # Extend form with fields for profile attributes
  606. for attr, form_field in self._get_attr_form_fields(profile).items():
  607. field_name = f'attr_{attr}'
  608. self.attr_fields.append(field_name)
  609. self.fields[field_name] = form_field
  610. if self.instance.attribute_data:
  611. self.fields[field_name].initial = self.instance.attribute_data.get(attr)
  612. @staticmethod
  613. def _get_attr_form_fields(profile):
  614. """
  615. Return a dictionary mapping of attribute names to form fields, suitable for extending
  616. the form per the selected ModuleTypeProfile.
  617. """
  618. if not profile.schema:
  619. return {}
  620. properties = profile.schema.get('properties', {})
  621. required_fields = profile.schema.get('required', [])
  622. attr_fields = {}
  623. for name, options in properties.items():
  624. prop = JSONSchemaProperty(**options)
  625. attr_fields[name] = prop.to_form_field(name, required=name in required_fields)
  626. return dict(sorted(attr_fields.items()))
  627. def _post_clean(self):
  628. # Compile attribute data from the individual form fields
  629. if self.cleaned_data.get('profile'):
  630. self.instance.attribute_data = {
  631. name[5:]: self.cleaned_data[name] # Remove the attr_ prefix
  632. for name in self.attr_fields
  633. if self.cleaned_data.get(name) not in EMPTY_VALUES
  634. }
  635. return super()._post_clean()
  636. class DeviceRoleForm(NestedGroupModelForm):
  637. config_template = DynamicModelChoiceField(
  638. label=_('Config template'),
  639. queryset=ConfigTemplate.objects.all(),
  640. required=False
  641. )
  642. parent = DynamicModelChoiceField(
  643. label=_('Parent'),
  644. queryset=DeviceRole.objects.all(),
  645. required=False,
  646. )
  647. fieldsets = (
  648. FieldSet(
  649. 'name', 'slug', 'parent', 'color', 'vm_role', 'config_template', 'description',
  650. 'tags', name=_('Device Role')
  651. ),
  652. )
  653. class Meta:
  654. model = DeviceRole
  655. fields = [
  656. 'name', 'slug', 'parent', 'color', 'vm_role', 'config_template', 'description', 'owner', 'comments', 'tags',
  657. ]
  658. class PlatformForm(NestedGroupModelForm):
  659. parent = DynamicModelChoiceField(
  660. label=_('Parent'),
  661. queryset=Platform.objects.all(),
  662. required=False,
  663. )
  664. manufacturer = DynamicModelChoiceField(
  665. label=_('Manufacturer'),
  666. queryset=Manufacturer.objects.all(),
  667. required=False,
  668. quick_add=True
  669. )
  670. config_template = DynamicModelChoiceField(
  671. label=_('Config template'),
  672. queryset=ConfigTemplate.objects.all(),
  673. required=False
  674. )
  675. slug = SlugField(
  676. label=_('Slug'),
  677. max_length=64
  678. )
  679. fieldsets = (
  680. FieldSet(
  681. 'name', 'slug', 'parent', 'manufacturer', 'config_template', 'description', 'tags', name=_('Platform'),
  682. ),
  683. )
  684. class Meta:
  685. model = Platform
  686. fields = [
  687. 'name', 'slug', 'parent', 'manufacturer', 'config_template', 'description', 'owner', 'comments', 'tags',
  688. ]
  689. class DeviceForm(TenancyForm, PrimaryModelForm):
  690. status = ChoiceField(
  691. label=_('Status'),
  692. choices=DeviceStatusChoices,
  693. initial=DeviceStatusChoices.STATUS_ACTIVE,
  694. )
  695. airflow = TypedChoiceField(
  696. label=_('Airflow'),
  697. choices=add_blank_choice(DeviceAirflowChoices),
  698. required=False,
  699. )
  700. site = DynamicModelChoiceField(
  701. label=_('Site'),
  702. queryset=Site.objects.all(),
  703. selector=True
  704. )
  705. location = DynamicModelChoiceField(
  706. label=_('Location'),
  707. queryset=Location.objects.all(),
  708. required=False,
  709. query_params={
  710. 'site_id': '$site'
  711. },
  712. initial_params={
  713. 'racks': '$rack'
  714. }
  715. )
  716. rack = DynamicModelChoiceField(
  717. label=_('Rack'),
  718. queryset=Rack.objects.all(),
  719. required=False,
  720. query_params={
  721. 'site_id': '$site',
  722. 'location_id': '$location',
  723. }
  724. )
  725. position = forms.DecimalField(
  726. label=_('Position'),
  727. required=False,
  728. help_text=_("The lowest-numbered unit occupied by the device"),
  729. localize=True,
  730. widget=APISelect(
  731. api_url='/api/dcim/racks/{{rack}}/elevation/',
  732. attrs={
  733. 'ts-disabled-field': 'device',
  734. 'data-dynamic-params': '[{"fieldName":"face","queryParam":"face"}]'
  735. },
  736. )
  737. )
  738. face = TypedChoiceField(
  739. label=_('Face'),
  740. choices=add_blank_choice(DeviceFaceChoices),
  741. required=False,
  742. widget=ClearableSelect(
  743. requires_fields=['rack']
  744. )
  745. )
  746. device_type = DynamicModelChoiceField(
  747. label=_('Device type'),
  748. queryset=DeviceType.objects.all(),
  749. context={
  750. 'parent': 'manufacturer',
  751. },
  752. selector=True
  753. )
  754. role = DynamicModelChoiceField(
  755. label=_('Device role'),
  756. queryset=DeviceRole.objects.all(),
  757. quick_add=True
  758. )
  759. platform = DynamicModelChoiceField(
  760. label=_('Platform'),
  761. queryset=Platform.objects.all(),
  762. required=False,
  763. selector=True,
  764. query_params={
  765. 'available_for_device_type': '$device_type',
  766. }
  767. )
  768. cluster = DynamicModelChoiceField(
  769. label=_('Cluster'),
  770. queryset=Cluster.objects.all(),
  771. required=False,
  772. selector=True,
  773. query_params={
  774. 'site_id': ['$site', 'null']
  775. },
  776. )
  777. local_context_data = JSONField(
  778. required=False,
  779. label='',
  780. widget=forms.Textarea(attrs={'aria-label': _('Local config context data')})
  781. )
  782. virtual_chassis = DynamicModelChoiceField(
  783. label=_('Virtual chassis'),
  784. queryset=VirtualChassis.objects.all(),
  785. required=False,
  786. context={
  787. 'parent': 'master',
  788. },
  789. selector=True
  790. )
  791. vc_position = forms.IntegerField(
  792. required=False,
  793. label=_('Position'),
  794. help_text=_("The position in the virtual chassis this device is identified by")
  795. )
  796. vc_priority = forms.IntegerField(
  797. required=False,
  798. label=_('Priority'),
  799. help_text=_("The priority of the device in the virtual chassis")
  800. )
  801. config_template = DynamicModelChoiceField(
  802. label=_('Config template'),
  803. queryset=ConfigTemplate.objects.all(),
  804. required=False
  805. )
  806. replicate_components = forms.BooleanField(
  807. label=_('Replicate components'),
  808. required=False,
  809. initial=True,
  810. help_text=_("Automatically populate components associated with this device type")
  811. )
  812. class Meta:
  813. model = Device
  814. fields = [
  815. 'name', 'role', 'device_type', 'serial', 'asset_tag', 'site', 'rack', 'location', 'position', 'face',
  816. 'latitude', 'longitude', 'status', 'airflow', 'cooling_method', 'platform', 'primary_ip4', 'primary_ip6',
  817. 'oob_ip', 'cluster',
  818. 'tenant_group', 'tenant', 'virtual_chassis', 'vc_position', 'vc_priority', 'description', 'config_template',
  819. 'owner', 'comments', 'tags', 'local_context_data', 'replicate_components',
  820. ]
  821. def __init__(self, *args, **kwargs):
  822. super().__init__(*args, **kwargs)
  823. if self.instance.pk:
  824. # Component replication applies only to new devices
  825. del self.fields['replicate_components']
  826. # Compile list of choices for primary IPv4 and IPv6 addresses
  827. oob_ip_choices = [(None, '---------')]
  828. for family in [4, 6]:
  829. ip_choices = [(None, '---------')]
  830. # Gather PKs of all interfaces belonging to this Device or a peer VirtualChassis member
  831. interface_ids = self.instance.vc_interfaces(if_master=False).values_list('pk', flat=True)
  832. # Collect interface IPs
  833. interface_ips = IPAddress.objects.filter(
  834. address__family=family,
  835. assigned_object_type=ContentType.objects.get_for_model(Interface),
  836. assigned_object_id__in=interface_ids
  837. ).prefetch_related('assigned_object')
  838. if interface_ips:
  839. ip_list = [(ip.id, f'{ip.address} ({ip.assigned_object})') for ip in interface_ips]
  840. ip_choices.append(('Interface IPs', ip_list))
  841. oob_ip_choices.extend(ip_list)
  842. # Collect NAT IPs
  843. nat_ips = IPAddress.objects.prefetch_related('nat_inside').filter(
  844. address__family=family,
  845. nat_inside__assigned_object_type=ContentType.objects.get_for_model(Interface),
  846. nat_inside__assigned_object_id__in=interface_ids
  847. ).prefetch_related('assigned_object')
  848. if nat_ips:
  849. ip_list = [(ip.id, f'{ip.address} (NAT)') for ip in nat_ips]
  850. ip_choices.append(('NAT IPs', ip_list))
  851. self.fields['primary_ip{}'.format(family)].choices = ip_choices
  852. self.fields['oob_ip'].choices = oob_ip_choices
  853. # If editing an existing device, exclude it from the list of occupied rack units. This ensures that a device
  854. # can be flipped from one face to another.
  855. self.fields['position'].widget.add_query_param('exclude', self.instance.pk)
  856. # Disable rack assignment if this is a child device installed in a parent device
  857. if self.instance.device_type.is_child_device and hasattr(self.instance, 'parent_bay'):
  858. self.fields['site'].disabled = True
  859. self.fields['rack'].disabled = True
  860. self.initial['site'] = self.instance.parent_bay.device.site_id
  861. self.initial['rack'] = self.instance.parent_bay.device.rack_id
  862. else:
  863. # An object that doesn't exist yet can't have any IPs assigned to it
  864. self.fields['primary_ip4'].choices = []
  865. self.fields['primary_ip4'].widget.attrs['readonly'] = True
  866. self.fields['primary_ip6'].choices = []
  867. self.fields['primary_ip6'].widget.attrs['readonly'] = True
  868. self.fields['oob_ip'].choices = []
  869. self.fields['oob_ip'].widget.attrs['readonly'] = True
  870. # Rack position
  871. position = self.data.get('position') or self.initial.get('position')
  872. if position:
  873. self.fields['position'].widget.choices = [(position, f'U{position}')]
  874. def clean(self):
  875. super().clean()
  876. # Disable component replication for a new device if requested
  877. if not self.instance.pk and not self.cleaned_data.get('replicate_components'):
  878. self.instance._disable_replication = True
  879. class ModuleForm(ModuleCommonForm, PrimaryModelForm):
  880. status = ChoiceField(
  881. label=_('Status'),
  882. choices=ModuleStatusChoices,
  883. initial=ModuleStatusChoices.STATUS_ACTIVE,
  884. )
  885. device = DynamicModelChoiceField(
  886. label=_('Device'),
  887. queryset=Device.objects.all(),
  888. initial_params={
  889. 'modulebays': '$module_bay'
  890. }
  891. )
  892. module_bay = DynamicModelChoiceField(
  893. label=_('Module bay'),
  894. queryset=ModuleBay.objects.all(),
  895. query_params={
  896. 'device_id': '$device',
  897. },
  898. context={
  899. 'disabled': '_occupied',
  900. },
  901. )
  902. module_type = DynamicModelChoiceField(
  903. label=_('Module type'),
  904. queryset=ModuleType.objects.all(),
  905. context={
  906. 'parent': 'manufacturer',
  907. },
  908. selector=True
  909. )
  910. replicate_components = forms.BooleanField(
  911. label=_('Replicate components'),
  912. required=False,
  913. initial=True,
  914. help_text=_("Automatically populate components associated with this module type")
  915. )
  916. adopt_components = forms.BooleanField(
  917. label=_('Adopt components'),
  918. required=False,
  919. initial=False,
  920. help_text=_("Adopt already existing components")
  921. )
  922. fieldsets = (
  923. FieldSet('device', 'module_bay', 'module_type', 'status', 'description', 'tags', name=_('Module')),
  924. FieldSet('serial', 'asset_tag', 'replicate_components', 'adopt_components', name=_('Hardware')),
  925. )
  926. class Meta:
  927. model = Module
  928. fields = [
  929. 'device', 'module_bay', 'module_type', 'status', 'serial', 'asset_tag', 'tags', 'replicate_components',
  930. 'adopt_components', 'description', 'owner', 'comments',
  931. ]
  932. def __init__(self, *args, **kwargs):
  933. super().__init__(*args, **kwargs)
  934. if self.instance.pk:
  935. self.fields['replicate_components'].initial = False
  936. self.fields['replicate_components'].disabled = True
  937. self.fields['adopt_components'].initial = False
  938. self.fields['adopt_components'].disabled = True
  939. def get_termination_type_choices():
  940. return add_blank_choice([
  941. Choice(f'{ct.app_label}.{ct.model}', ct.model_class()._meta.verbose_name.title())
  942. for ct in ContentType.objects.filter(CABLE_TERMINATION_MODELS)
  943. ])
  944. class CableBundleForm(PrimaryModelForm):
  945. fieldsets = (
  946. FieldSet('name', 'description', 'tags', name=_('Cable Bundle')),
  947. )
  948. class Meta:
  949. model = CableBundle
  950. fields = ['name', 'description', 'owner', 'comments', 'tags']
  951. class CableForm(TenancyForm, PrimaryModelForm):
  952. type = TypedChoiceField(
  953. label=_('Type'),
  954. choices=add_blank_choice(CableTypeChoices),
  955. required=False,
  956. )
  957. status = ChoiceField(
  958. label=_('Status'),
  959. choices=LinkStatusChoices,
  960. initial=LinkStatusChoices.STATUS_CONNECTED,
  961. )
  962. profile = ChoiceField(
  963. label=_('Profile'),
  964. choices=add_blank_choice(CableProfileChoices),
  965. required=False,
  966. )
  967. length_unit = TypedChoiceField(
  968. label=_('Length unit'),
  969. choices=add_blank_choice(CableLengthUnitChoices),
  970. required=False,
  971. )
  972. a_terminations_type = ChoiceField(
  973. choices=get_termination_type_choices,
  974. required=False,
  975. widget=HTMXSelect(hx_target_id='cable-side-a'),
  976. label=_('Type')
  977. )
  978. b_terminations_type = ChoiceField(
  979. choices=get_termination_type_choices,
  980. required=False,
  981. widget=HTMXSelect(hx_target_id='cable-side-b'),
  982. label=_('Type')
  983. )
  984. bundle = DynamicModelChoiceField(
  985. queryset=CableBundle.objects.all(),
  986. required=False,
  987. label=_('Bundle'),
  988. )
  989. class Meta:
  990. model = Cable
  991. fields = [
  992. 'a_terminations_type', 'b_terminations_type', 'type', 'status', 'profile', 'tenant_group', 'tenant',
  993. 'bundle', 'label', 'color', 'length', 'length_unit', 'description', 'owner', 'comments', 'tags',
  994. ]
  995. class PowerPanelForm(PrimaryModelForm):
  996. site = DynamicModelChoiceField(
  997. label=_('Site'),
  998. queryset=Site.objects.all(),
  999. selector=True
  1000. )
  1001. location = DynamicModelChoiceField(
  1002. label=_('Location'),
  1003. queryset=Location.objects.all(),
  1004. required=False,
  1005. query_params={
  1006. 'site_id': '$site'
  1007. }
  1008. )
  1009. fieldsets = (
  1010. FieldSet('site', 'location', 'name', 'description', 'tags', name=_('Power Panel')),
  1011. )
  1012. class Meta:
  1013. model = PowerPanel
  1014. fields = [
  1015. 'site', 'location', 'name', 'description', 'owner', 'comments', 'tags',
  1016. ]
  1017. class PowerFeedForm(TenancyForm, PrimaryModelForm):
  1018. status = ChoiceField(
  1019. label=_('Status'),
  1020. choices=PowerFeedStatusChoices,
  1021. initial=PowerFeedStatusChoices.STATUS_ACTIVE,
  1022. )
  1023. type = ChoiceField(
  1024. label=_('Type'),
  1025. choices=PowerFeedTypeChoices,
  1026. initial=PowerFeedTypeChoices.TYPE_PRIMARY,
  1027. )
  1028. supply = ChoiceField(
  1029. label=_('Supply'),
  1030. choices=PowerFeedSupplyChoices,
  1031. initial=PowerFeedSupplyChoices.SUPPLY_AC,
  1032. )
  1033. phase = ChoiceField(
  1034. label=_('Phase'),
  1035. choices=PowerFeedPhaseChoices,
  1036. initial=PowerFeedPhaseChoices.PHASE_SINGLE,
  1037. )
  1038. power_panel = DynamicModelChoiceField(
  1039. label=_('Power panel'),
  1040. queryset=PowerPanel.objects.all(),
  1041. selector=True,
  1042. quick_add=True
  1043. )
  1044. rack = DynamicModelChoiceField(
  1045. label=_('Rack'),
  1046. queryset=Rack.objects.all(),
  1047. required=False,
  1048. selector=True
  1049. )
  1050. fieldsets = (
  1051. FieldSet(
  1052. 'power_panel', 'rack', 'name', 'status', 'type', 'description', 'mark_connected', 'tags',
  1053. name=_('Power Feed')
  1054. ),
  1055. FieldSet('supply', 'voltage', 'amperage', 'phase', 'max_utilization', name=_('Characteristics')),
  1056. FieldSet('tenant_group', 'tenant', name=_('Tenancy')),
  1057. )
  1058. class Meta:
  1059. model = PowerFeed
  1060. fields = [
  1061. 'power_panel', 'rack', 'name', 'status', 'type', 'mark_connected', 'supply', 'phase', 'voltage', 'amperage',
  1062. 'max_utilization', 'tenant_group', 'tenant', 'description', 'owner', 'comments', 'tags'
  1063. ]
  1064. #
  1065. # Cooling
  1066. #
  1067. class CoolingSourceForm(PrimaryModelForm):
  1068. site = DynamicModelChoiceField(
  1069. label=_('Site'),
  1070. queryset=Site.objects.all(),
  1071. selector=True
  1072. )
  1073. location = DynamicModelChoiceField(
  1074. label=_('Location'),
  1075. queryset=Location.objects.all(),
  1076. required=False,
  1077. query_params={
  1078. 'site_id': '$site'
  1079. }
  1080. )
  1081. fieldsets = (
  1082. FieldSet('site', 'location', 'name', 'type', 'status', 'description', 'tags', name=_('Cooling Source')),
  1083. FieldSet('fluid_type', 'cooling_capacity', name=_('Characteristics')),
  1084. )
  1085. class Meta:
  1086. model = CoolingSource
  1087. fields = [
  1088. 'site', 'location', 'name', 'type', 'status', 'fluid_type', 'cooling_capacity', 'description', 'owner',
  1089. 'comments', 'tags',
  1090. ]
  1091. class CoolingFeedForm(TenancyForm, PrimaryModelForm):
  1092. cooling_source = DynamicModelChoiceField(
  1093. label=_('Cooling source'),
  1094. queryset=CoolingSource.objects.all(),
  1095. selector=True,
  1096. quick_add=True
  1097. )
  1098. rack = DynamicModelChoiceField(
  1099. label=_('Rack'),
  1100. queryset=Rack.objects.all(),
  1101. required=False,
  1102. selector=True
  1103. )
  1104. fieldsets = (
  1105. FieldSet(
  1106. 'cooling_source', 'rack', 'name', 'status', 'description', 'tags',
  1107. name=_('Cooling Feed')
  1108. ),
  1109. FieldSet(
  1110. 'cooling_capacity',
  1111. InlineFields('max_flow', 'max_flow_unit', label=_('Max flow')),
  1112. name=_('Characteristics')
  1113. ),
  1114. FieldSet('tenant_group', 'tenant', name=_('Tenancy')),
  1115. )
  1116. class Meta:
  1117. model = CoolingFeed
  1118. fields = [
  1119. 'cooling_source', 'rack', 'name', 'status', 'cooling_capacity',
  1120. 'max_flow', 'max_flow_unit', 'tenant_group', 'tenant', 'description', 'owner', 'comments',
  1121. 'tags',
  1122. ]
  1123. #
  1124. # Virtual chassis
  1125. #
  1126. class VirtualChassisForm(PrimaryModelForm):
  1127. master = forms.ModelChoiceField(
  1128. label=_('Master'),
  1129. queryset=Device.objects.all(),
  1130. required=False,
  1131. widget=SelectWithPK(),
  1132. )
  1133. class Meta:
  1134. model = VirtualChassis
  1135. fields = [
  1136. 'name', 'domain', 'master', 'description', 'owner', 'comments', 'tags',
  1137. ]
  1138. def __init__(self, *args, **kwargs):
  1139. super().__init__(*args, **kwargs)
  1140. self.fields['master'].queryset = Device.objects.filter(virtual_chassis=self.instance)
  1141. class DeviceVCMembershipForm(forms.ModelForm):
  1142. class Meta:
  1143. model = Device
  1144. fields = [
  1145. 'vc_position', 'vc_priority',
  1146. ]
  1147. labels = {
  1148. 'vc_position': 'Position',
  1149. 'vc_priority': 'Priority',
  1150. }
  1151. def __init__(self, validate_vc_position=False, *args, **kwargs):
  1152. super().__init__(*args, **kwargs)
  1153. # Require VC position (only required when the Device is a VirtualChassis member)
  1154. self.fields['vc_position'].required = True
  1155. # Add bootstrap classes to form elements.
  1156. self.fields['vc_position'].widget.attrs = {'class': 'form-control'}
  1157. self.fields['vc_priority'].widget.attrs = {'class': 'form-control'}
  1158. # Validation of vc_position is optional. This is only required when adding a new member to an existing
  1159. # VirtualChassis. Otherwise, vc_position validation is handled by BaseVCMemberFormSet.
  1160. self.validate_vc_position = validate_vc_position
  1161. def clean_vc_position(self):
  1162. vc_position = self.cleaned_data['vc_position']
  1163. if self.validate_vc_position:
  1164. conflicting_members = Device.objects.filter(
  1165. virtual_chassis=self.instance.virtual_chassis,
  1166. vc_position=vc_position
  1167. )
  1168. if conflicting_members.exists():
  1169. raise forms.ValidationError(
  1170. 'A virtual chassis member already exists in position {}.'.format(vc_position)
  1171. )
  1172. return vc_position
  1173. class VCMemberSelectForm(forms.Form):
  1174. device = DynamicModelChoiceField(
  1175. label=_('Device'),
  1176. queryset=Device.objects.all(),
  1177. query_params={
  1178. 'virtual_chassis_id': 'null',
  1179. },
  1180. selector=True
  1181. )
  1182. def clean_device(self):
  1183. device = self.cleaned_data['device']
  1184. if device.virtual_chassis is not None:
  1185. raise forms.ValidationError(
  1186. f"Device {device} is already assigned to a virtual chassis."
  1187. )
  1188. return device
  1189. #
  1190. # Device component templates
  1191. #
  1192. class ComponentTemplateForm(ChangelogMessageMixin, forms.ModelForm):
  1193. device_type = DynamicModelChoiceField(
  1194. label=_('Device type'),
  1195. queryset=DeviceType.objects.all(),
  1196. context={
  1197. 'parent': 'manufacturer',
  1198. }
  1199. )
  1200. def __init__(self, *args, **kwargs):
  1201. super().__init__(*args, **kwargs)
  1202. # Disable reassignment of DeviceType when editing an existing instance
  1203. if self.instance.pk:
  1204. self.fields['device_type'].disabled = True
  1205. class ModularComponentTemplateForm(ComponentTemplateForm):
  1206. device_type = DynamicModelChoiceField(
  1207. label=_('Device type'),
  1208. queryset=DeviceType.objects.all(),
  1209. required=False,
  1210. context={
  1211. 'parent': 'manufacturer',
  1212. }
  1213. )
  1214. module_type = DynamicModelChoiceField(
  1215. label=_('Module type'),
  1216. queryset=ModuleType.objects.all(),
  1217. required=False,
  1218. context={
  1219. 'parent': 'manufacturer',
  1220. }
  1221. )
  1222. fieldsets = (
  1223. FieldSet(
  1224. TabbedGroups(
  1225. FieldSet('device_type', name=_('Device Type')),
  1226. FieldSet('module_type', name=_('Module Type')),
  1227. ),
  1228. 'name', 'label', 'type', 'description'
  1229. ),
  1230. )
  1231. def __init__(self, *args, **kwargs):
  1232. super().__init__(*args, **kwargs)
  1233. # Disable reassignment of ModuleType when editing an existing instance
  1234. if self.instance.pk:
  1235. self.fields['module_type'].disabled = True
  1236. # Components attached to a module need to present this standardized substitution help text.
  1237. self.fields['name'].help_text = _(
  1238. "Alphanumeric ranges are supported for bulk creation. Mixed cases and types within a single range are not "
  1239. "supported (example: <code>[ge,xe]-0/0/[0-9]</code>). The token <code>{module}</code>, if present, will be "
  1240. "automatically replaced with the position value when creating a new module. "
  1241. "The token <code>{vc_position}</code> will be replaced with the device's Virtual Chassis position "
  1242. "(use <code>{vc_position:1}</code> to specify a fallback (default is 0))"
  1243. )
  1244. class ConsolePortTemplateForm(ModularComponentTemplateForm):
  1245. type = TypedChoiceField(
  1246. label=_('Type'),
  1247. choices=add_blank_choice(ConsolePortTypeChoices),
  1248. required=False,
  1249. )
  1250. class Meta:
  1251. model = ConsolePortTemplate
  1252. fields = [
  1253. 'device_type', 'module_type', 'name', 'label', 'type', 'description',
  1254. ]
  1255. class ConsoleServerPortTemplateForm(ModularComponentTemplateForm):
  1256. type = TypedChoiceField(
  1257. label=_('Type'),
  1258. choices=add_blank_choice(ConsolePortTypeChoices),
  1259. required=False,
  1260. )
  1261. class Meta:
  1262. model = ConsoleServerPortTemplate
  1263. fields = [
  1264. 'device_type', 'module_type', 'name', 'label', 'type', 'description',
  1265. ]
  1266. class PowerPortTemplateForm(ModularComponentTemplateForm):
  1267. type = TypedChoiceField(
  1268. label=_('Type'),
  1269. choices=add_blank_choice(PowerPortTypeChoices),
  1270. required=False,
  1271. )
  1272. fieldsets = (
  1273. FieldSet(
  1274. TabbedGroups(
  1275. FieldSet('device_type', name=_('Device Type')),
  1276. FieldSet('module_type', name=_('Module Type')),
  1277. ),
  1278. 'name', 'label', 'type', 'maximum_draw', 'allocated_draw', 'description',
  1279. ),
  1280. )
  1281. class Meta:
  1282. model = PowerPortTemplate
  1283. fields = [
  1284. 'device_type', 'module_type', 'name', 'label', 'type', 'maximum_draw', 'allocated_draw', 'description',
  1285. ]
  1286. class PowerOutletTemplateForm(ModularComponentTemplateForm):
  1287. type = TypedChoiceField(
  1288. label=_('Type'),
  1289. choices=add_blank_choice(PowerOutletTypeChoices),
  1290. required=False,
  1291. )
  1292. feed_leg = TypedChoiceField(
  1293. label=_('Feed leg'),
  1294. choices=add_blank_choice(PowerOutletFeedLegChoices),
  1295. required=False,
  1296. help_text=_('Phase (for three-phase feeds)'),
  1297. )
  1298. power_port = DynamicModelChoiceField(
  1299. label=_('Power port'),
  1300. queryset=PowerPortTemplate.objects.all(),
  1301. required=False,
  1302. query_params={
  1303. 'device_type_id': '$device_type',
  1304. }
  1305. )
  1306. fieldsets = (
  1307. FieldSet(
  1308. TabbedGroups(
  1309. FieldSet('device_type', name=_('Device Type')),
  1310. FieldSet('module_type', name=_('Module Type')),
  1311. ),
  1312. 'name', 'label', 'type', 'color', 'power_port', 'feed_leg', 'description',
  1313. ),
  1314. )
  1315. class Meta:
  1316. model = PowerOutletTemplate
  1317. fields = [
  1318. 'device_type', 'module_type', 'name', 'label', 'type', 'color', 'power_port', 'feed_leg', 'description',
  1319. ]
  1320. class CoolingIntakeTemplateForm(ModularComponentTemplateForm):
  1321. fieldsets = (
  1322. FieldSet(
  1323. TabbedGroups(
  1324. FieldSet('device_type', name=_('Device Type')),
  1325. FieldSet('module_type', name=_('Module Type')),
  1326. ),
  1327. 'name', 'label', 'type',
  1328. InlineFields('diameter', 'diameter_unit', label=_('Diameter')),
  1329. InlineFields('max_flow', 'max_flow_unit', label=_('Max flow')),
  1330. 'description',
  1331. ),
  1332. )
  1333. class Meta:
  1334. model = CoolingIntakeTemplate
  1335. fields = [
  1336. 'device_type', 'module_type', 'name', 'label', 'type', 'diameter', 'diameter_unit',
  1337. 'max_flow', 'max_flow_unit', 'description',
  1338. ]
  1339. class CoolingOutflowTemplateForm(ModularComponentTemplateForm):
  1340. cooling_intake = DynamicModelChoiceField(
  1341. label=_('Cooling intake'),
  1342. queryset=CoolingIntakeTemplate.objects.all(),
  1343. required=False,
  1344. query_params={
  1345. 'device_type_id': '$device_type',
  1346. }
  1347. )
  1348. fieldsets = (
  1349. FieldSet(
  1350. TabbedGroups(
  1351. FieldSet('device_type', name=_('Device Type')),
  1352. FieldSet('module_type', name=_('Module Type')),
  1353. ),
  1354. 'name', 'label', 'type',
  1355. InlineFields('diameter', 'diameter_unit', label=_('Diameter')),
  1356. 'cooling_intake', 'description',
  1357. ),
  1358. )
  1359. class Meta:
  1360. model = CoolingOutflowTemplate
  1361. fields = [
  1362. 'device_type', 'module_type', 'name', 'label', 'type', 'diameter', 'diameter_unit',
  1363. 'cooling_intake', 'description',
  1364. ]
  1365. class InterfaceTemplateForm(ModularComponentTemplateForm):
  1366. type = ChoiceField(
  1367. label=_('Type'),
  1368. choices=InterfaceTypeChoices,
  1369. )
  1370. poe_mode = TypedChoiceField(
  1371. label=_('PoE mode'),
  1372. choices=add_blank_choice(InterfacePoEModeChoices),
  1373. required=False,
  1374. )
  1375. poe_type = TypedChoiceField(
  1376. label=_('PoE type'),
  1377. choices=add_blank_choice(InterfacePoETypeChoices),
  1378. required=False,
  1379. )
  1380. rf_role = TypedChoiceField(
  1381. label=_('Wireless role'),
  1382. choices=add_blank_choice(WirelessRoleChoices),
  1383. required=False,
  1384. )
  1385. parent = DynamicModelChoiceField(
  1386. label=_('Parent'),
  1387. queryset=InterfaceTemplate.objects.all(),
  1388. required=False,
  1389. query_params={
  1390. 'device_type_id': '$device_type',
  1391. 'module_type_id': '$module_type',
  1392. }
  1393. )
  1394. bridge = DynamicModelChoiceField(
  1395. label=_('Bridge'),
  1396. queryset=InterfaceTemplate.objects.all(),
  1397. required=False,
  1398. query_params={
  1399. 'device_type_id': '$device_type',
  1400. 'module_type_id': '$module_type',
  1401. }
  1402. )
  1403. fieldsets = (
  1404. FieldSet(
  1405. TabbedGroups(
  1406. FieldSet('device_type', name=_('Device Type')),
  1407. FieldSet('module_type', name=_('Module Type')),
  1408. ),
  1409. 'name', 'label', 'type', 'channels', 'channel_id', 'enabled', 'mgmt_only', 'description', 'parent',
  1410. 'bridge',
  1411. ),
  1412. FieldSet('poe_mode', 'poe_type', name=_('PoE')),
  1413. FieldSet('rf_role', name=_('Wireless')),
  1414. )
  1415. class Meta:
  1416. model = InterfaceTemplate
  1417. fields = [
  1418. 'device_type', 'module_type', 'name', 'label', 'type', 'channels', 'channel_id', 'mgmt_only', 'enabled',
  1419. 'description', 'poe_mode', 'poe_type', 'parent', 'bridge', 'rf_role',
  1420. ]
  1421. class FrontPortTemplateForm(FrontPortFormMixin, ModularComponentTemplateForm):
  1422. type = ChoiceField(
  1423. label=_('Type'),
  1424. choices=PortTypeChoices,
  1425. )
  1426. fieldsets = (
  1427. FieldSet(
  1428. TabbedGroups(
  1429. FieldSet('device_type', name=_('Device Type')),
  1430. FieldSet('module_type', name=_('Module Type')),
  1431. ),
  1432. 'name', 'label', 'type', 'color', 'positions', 'rear_ports', 'description',
  1433. ),
  1434. )
  1435. port_mapping_model = PortTemplateMapping
  1436. rear_port_model = RearPortTemplate
  1437. class Meta:
  1438. model = FrontPortTemplate
  1439. fields = [
  1440. 'device_type', 'module_type', 'name', 'label', 'type', 'color', 'positions', 'description',
  1441. ]
  1442. def __init__(self, *args, **kwargs):
  1443. super().__init__(*args, **kwargs)
  1444. # Populate rear port choices based on parent DeviceType or ModuleType
  1445. if device_type_id := self.data.get('device_type') or self.initial.get('device_type'):
  1446. parent_filter = Q(device_type=device_type_id)
  1447. elif module_type_id := self.data.get('module_type') or self.initial.get('module_type'):
  1448. parent_filter = Q(module_type=module_type_id)
  1449. else:
  1450. return
  1451. self.fields['rear_ports'].choices = self._get_rear_port_choices(parent_filter, self.instance)
  1452. # Set initial rear port mappings
  1453. if self.instance.pk:
  1454. self.initial['rear_ports'] = [
  1455. f'{mapping.rear_port_id}:{mapping.rear_port_position}'
  1456. for mapping in PortTemplateMapping.objects.filter(front_port_id=self.instance.pk)
  1457. ]
  1458. class RearPortTemplateForm(ModularComponentTemplateForm):
  1459. type = ChoiceField(
  1460. label=_('Type'),
  1461. choices=PortTypeChoices,
  1462. )
  1463. fieldsets = (
  1464. FieldSet(
  1465. TabbedGroups(
  1466. FieldSet('device_type', name=_('Device Type')),
  1467. FieldSet('module_type', name=_('Module Type')),
  1468. ),
  1469. 'name', 'label', 'type', 'color', 'positions', 'description',
  1470. ),
  1471. )
  1472. class Meta:
  1473. model = RearPortTemplate
  1474. fields = [
  1475. 'device_type', 'module_type', 'name', 'label', 'type', 'color', 'positions', 'description',
  1476. ]
  1477. class ModuleBayTemplateForm(ModularComponentTemplateForm):
  1478. module_bay_types = DynamicModelMultipleChoiceField(
  1479. label=_('Module bay types'),
  1480. queryset=ModuleBayType.objects.all(),
  1481. required=False,
  1482. )
  1483. fieldsets = (
  1484. FieldSet(
  1485. TabbedGroups(
  1486. FieldSet('device_type', name=_('Device Type')),
  1487. FieldSet('module_type', name=_('Module Type')),
  1488. ),
  1489. 'name', 'label', 'position', 'enabled', 'description', 'module_bay_types',
  1490. ),
  1491. )
  1492. class Meta:
  1493. model = ModuleBayTemplate
  1494. fields = [
  1495. 'device_type', 'module_type', 'name', 'label', 'position', 'enabled', 'description', 'module_bay_types',
  1496. ]
  1497. class DeviceBayTemplateForm(ComponentTemplateForm):
  1498. fieldsets = (
  1499. FieldSet('device_type', 'name', 'label', 'enabled', 'description'),
  1500. )
  1501. class Meta:
  1502. model = DeviceBayTemplate
  1503. fields = [
  1504. 'device_type', 'name', 'label', 'enabled', 'description',
  1505. ]
  1506. class InventoryItemTemplateForm(ComponentTemplateForm):
  1507. parent = DynamicModelChoiceField(
  1508. label=_('Parent'),
  1509. queryset=InventoryItemTemplate.objects.all(),
  1510. required=False,
  1511. query_params={
  1512. 'device_type_id': '$device_type'
  1513. }
  1514. )
  1515. role = DynamicModelChoiceField(
  1516. label=_('Role'),
  1517. queryset=InventoryItemRole.objects.all(),
  1518. required=False
  1519. )
  1520. manufacturer = DynamicModelChoiceField(
  1521. label=_('Manufacturer'),
  1522. queryset=Manufacturer.objects.all(),
  1523. required=False
  1524. )
  1525. # Assigned component selectors
  1526. consoleporttemplate = DynamicModelChoiceField(
  1527. queryset=ConsolePortTemplate.objects.all(),
  1528. required=False,
  1529. query_params={
  1530. 'device_type_id': '$device_type'
  1531. },
  1532. label=_('Console port template')
  1533. )
  1534. consoleserverporttemplate = DynamicModelChoiceField(
  1535. queryset=ConsoleServerPortTemplate.objects.all(),
  1536. required=False,
  1537. query_params={
  1538. 'device_type_id': '$device_type'
  1539. },
  1540. label=_('Console server port template')
  1541. )
  1542. frontporttemplate = DynamicModelChoiceField(
  1543. queryset=FrontPortTemplate.objects.all(),
  1544. required=False,
  1545. query_params={
  1546. 'device_type_id': '$device_type'
  1547. },
  1548. label=_('Front port template')
  1549. )
  1550. interfacetemplate = DynamicModelChoiceField(
  1551. queryset=InterfaceTemplate.objects.all(),
  1552. required=False,
  1553. query_params={
  1554. 'device_type_id': '$device_type'
  1555. },
  1556. label=_('Interface template')
  1557. )
  1558. poweroutlettemplate = DynamicModelChoiceField(
  1559. queryset=PowerOutletTemplate.objects.all(),
  1560. required=False,
  1561. query_params={
  1562. 'device_type_id': '$device_type'
  1563. },
  1564. label=_('Power outlet template')
  1565. )
  1566. powerporttemplate = DynamicModelChoiceField(
  1567. queryset=PowerPortTemplate.objects.all(),
  1568. required=False,
  1569. query_params={
  1570. 'device_type_id': '$device_type'
  1571. },
  1572. label=_('Power port template')
  1573. )
  1574. rearporttemplate = DynamicModelChoiceField(
  1575. queryset=RearPortTemplate.objects.all(),
  1576. required=False,
  1577. query_params={
  1578. 'device_type_id': '$device_type'
  1579. },
  1580. label=_('Rear port template')
  1581. )
  1582. fieldsets = (
  1583. FieldSet(
  1584. 'device_type', 'parent', 'name', 'label', 'role', 'manufacturer', 'part_id', 'description',
  1585. ),
  1586. FieldSet(
  1587. TabbedGroups(
  1588. FieldSet('interfacetemplate', name=_('Interface')),
  1589. FieldSet('consoleporttemplate', name=_('Console Port')),
  1590. FieldSet('consoleserverporttemplate', name=_('Console Server Port')),
  1591. FieldSet('frontporttemplate', name=_('Front Port')),
  1592. FieldSet('rearporttemplate', name=_('Rear Port')),
  1593. FieldSet('powerporttemplate', name=_('Power Port')),
  1594. FieldSet('poweroutlettemplate', name=_('Power Outlet')),
  1595. ),
  1596. name=_('Component Assignment')
  1597. )
  1598. )
  1599. class Meta:
  1600. model = InventoryItemTemplate
  1601. fields = [
  1602. 'device_type', 'parent', 'name', 'label', 'role', 'manufacturer', 'part_id', 'description',
  1603. ]
  1604. def __init__(self, *args, **kwargs):
  1605. instance = kwargs.get('instance')
  1606. initial = kwargs.get('initial', {}).copy()
  1607. component_type = initial.get('component_type')
  1608. component_id = initial.get('component_id')
  1609. if instance:
  1610. # When editing set the initial value for component selection
  1611. for component_model in ContentType.objects.filter(MODULAR_COMPONENT_TEMPLATE_MODELS):
  1612. if type(instance.component) is component_model.model_class():
  1613. initial[component_model.model] = instance.component
  1614. break
  1615. elif component_type and component_id:
  1616. # When adding the InventoryItem from a component page
  1617. content_type = ContentType.objects.filter(
  1618. MODULAR_COMPONENT_TEMPLATE_MODELS
  1619. ).filter(pk=component_type).first()
  1620. if content_type:
  1621. if component := content_type.model_class().objects.filter(pk=component_id).first():
  1622. initial[content_type.model] = component
  1623. kwargs['initial'] = initial
  1624. super().__init__(*args, **kwargs)
  1625. def clean(self):
  1626. super().clean()
  1627. # Handle object assignment
  1628. selected_objects = [
  1629. field for field in (
  1630. 'consoleporttemplate', 'consoleserverporttemplate', 'frontporttemplate', 'interfacetemplate',
  1631. 'poweroutlettemplate', 'powerporttemplate', 'rearporttemplate'
  1632. ) if self.cleaned_data[field]
  1633. ]
  1634. if len(selected_objects) > 1:
  1635. raise forms.ValidationError(_("An InventoryItem can only be assigned to a single component."))
  1636. if selected_objects:
  1637. self.instance.component = self.cleaned_data[selected_objects[0]]
  1638. else:
  1639. self.instance.component = None
  1640. #
  1641. # Device components
  1642. #
  1643. class DeviceComponentForm(OwnerMixin, NetBoxModelForm):
  1644. device = DynamicModelChoiceField(
  1645. label=_('Device'),
  1646. queryset=Device.objects.all(),
  1647. selector=True
  1648. )
  1649. def __init__(self, *args, **kwargs):
  1650. super().__init__(*args, **kwargs)
  1651. # Disable reassignment of Device when editing an existing instance
  1652. if self.instance.pk:
  1653. self.fields['device'].disabled = True
  1654. class ModularDeviceComponentForm(DeviceComponentForm):
  1655. module = DynamicModelChoiceField(
  1656. label=_('Module'),
  1657. queryset=Module.objects.all(),
  1658. required=False,
  1659. query_params={
  1660. 'device_id': '$device',
  1661. }
  1662. )
  1663. class ConsolePortForm(ModularDeviceComponentForm):
  1664. type = TypedChoiceField(
  1665. label=_('Type'),
  1666. choices=add_blank_choice(ConsolePortTypeChoices),
  1667. required=False,
  1668. help_text=_('Physical port type'),
  1669. )
  1670. fieldsets = (
  1671. FieldSet(
  1672. 'device', 'module', 'name', 'label', 'type', 'speed', 'mark_connected', 'description', 'tags',
  1673. ),
  1674. )
  1675. class Meta:
  1676. model = ConsolePort
  1677. fields = [
  1678. 'device', 'module', 'name', 'label', 'type', 'speed', 'mark_connected', 'description', 'owner', 'tags',
  1679. ]
  1680. class ConsoleServerPortForm(ModularDeviceComponentForm):
  1681. type = TypedChoiceField(
  1682. label=_('Type'),
  1683. choices=add_blank_choice(ConsolePortTypeChoices),
  1684. required=False,
  1685. help_text=_('Physical port type'),
  1686. )
  1687. fieldsets = (
  1688. FieldSet(
  1689. 'device', 'module', 'name', 'label', 'type', 'speed', 'mark_connected', 'description', 'tags',
  1690. ),
  1691. )
  1692. class Meta:
  1693. model = ConsoleServerPort
  1694. fields = [
  1695. 'device', 'module', 'name', 'label', 'type', 'speed', 'mark_connected', 'description', 'owner', 'tags',
  1696. ]
  1697. class PowerPortForm(ModularDeviceComponentForm):
  1698. type = TypedChoiceField(
  1699. label=_('Type'),
  1700. choices=add_blank_choice(PowerPortTypeChoices),
  1701. required=False,
  1702. help_text=_('Physical port type'),
  1703. )
  1704. fieldsets = (
  1705. FieldSet(
  1706. 'device', 'module', 'name', 'label', 'type', 'maximum_draw', 'allocated_draw', 'mark_connected',
  1707. 'description', 'tags',
  1708. ),
  1709. )
  1710. class Meta:
  1711. model = PowerPort
  1712. fields = [
  1713. 'device', 'module', 'name', 'label', 'type', 'maximum_draw', 'allocated_draw', 'mark_connected',
  1714. 'description', 'owner', 'tags',
  1715. ]
  1716. class PowerOutletForm(ModularDeviceComponentForm):
  1717. type = TypedChoiceField(
  1718. label=_('Type'),
  1719. choices=add_blank_choice(PowerOutletTypeChoices),
  1720. required=False,
  1721. help_text=_('Physical port type'),
  1722. )
  1723. status = ChoiceField(
  1724. label=_('Status'),
  1725. choices=PowerOutletStatusChoices,
  1726. initial=PowerOutletStatusChoices.STATUS_ENABLED,
  1727. )
  1728. feed_leg = TypedChoiceField(
  1729. label=_('Feed leg'),
  1730. choices=add_blank_choice(PowerOutletFeedLegChoices),
  1731. required=False,
  1732. help_text=_('Phase (for three-phase feeds)'),
  1733. )
  1734. power_port = DynamicModelChoiceField(
  1735. label=_('Power port'),
  1736. queryset=PowerPort.objects.all(),
  1737. required=False,
  1738. query_params={
  1739. 'device_id': '$device',
  1740. }
  1741. )
  1742. fieldsets = (
  1743. FieldSet(
  1744. 'device', 'module', 'name', 'label', 'type', 'status', 'color', 'power_port', 'feed_leg', 'mark_connected',
  1745. 'description', 'tags',
  1746. ),
  1747. )
  1748. class Meta:
  1749. model = PowerOutlet
  1750. fields = [
  1751. 'device', 'module', 'name', 'label', 'type', 'status', 'color', 'power_port', 'feed_leg', 'mark_connected',
  1752. 'description', 'owner', 'tags',
  1753. ]
  1754. class CoolingIntakeForm(ModularDeviceComponentForm):
  1755. cooling_outflow = DynamicModelChoiceField(
  1756. label=_('Cooling outflow'),
  1757. queryset=CoolingOutflow.objects.all(),
  1758. required=False,
  1759. selector=True
  1760. )
  1761. fieldsets = (
  1762. FieldSet(
  1763. 'device', 'module', 'name', 'label', 'type',
  1764. InlineFields('diameter', 'diameter_unit', label=_('Diameter')),
  1765. InlineFields('max_flow', 'max_flow_unit', label=_('Max flow')),
  1766. 'cooling_outflow', 'description', 'tags',
  1767. ),
  1768. )
  1769. class Meta:
  1770. model = CoolingIntake
  1771. fields = [
  1772. 'device', 'module', 'name', 'label', 'type', 'diameter', 'diameter_unit', 'max_flow',
  1773. 'max_flow_unit', 'cooling_outflow', 'description', 'owner', 'tags',
  1774. ]
  1775. class CoolingOutflowForm(ModularDeviceComponentForm):
  1776. cooling_intake = DynamicModelChoiceField(
  1777. label=_('Cooling intake'),
  1778. queryset=CoolingIntake.objects.all(),
  1779. required=False,
  1780. query_params={
  1781. 'device_id': '$device',
  1782. }
  1783. )
  1784. fieldsets = (
  1785. FieldSet(
  1786. 'device', 'module', 'name', 'label', 'type',
  1787. InlineFields('diameter', 'diameter_unit', label=_('Diameter')),
  1788. 'cooling_intake', 'description', 'tags',
  1789. ),
  1790. )
  1791. class Meta:
  1792. model = CoolingOutflow
  1793. fields = [
  1794. 'device', 'module', 'name', 'label', 'type', 'diameter', 'diameter_unit', 'cooling_intake', 'description',
  1795. 'owner', 'tags',
  1796. ]
  1797. class InterfaceForm(InterfaceCommonForm, ModularDeviceComponentForm):
  1798. type = ChoiceField(
  1799. label=_('Type'),
  1800. choices=InterfaceTypeChoices,
  1801. )
  1802. duplex = TypedChoiceField(
  1803. label=_('Duplex'),
  1804. choices=add_blank_choice(InterfaceDuplexChoices),
  1805. required=False,
  1806. )
  1807. poe_mode = TypedChoiceField(
  1808. label=_('PoE mode'),
  1809. choices=add_blank_choice(InterfacePoEModeChoices),
  1810. required=False,
  1811. )
  1812. poe_type = TypedChoiceField(
  1813. label=_('PoE type'),
  1814. choices=add_blank_choice(InterfacePoETypeChoices),
  1815. required=False,
  1816. )
  1817. lag_mode = TypedChoiceField(
  1818. label=_('LAG mode'),
  1819. choices=add_blank_choice(InterfaceLAGModeChoices),
  1820. required=False,
  1821. widget=HTMXSelect(hx_target_id='lag-attributes'),
  1822. )
  1823. lag_hash_policy = TypedChoiceField(
  1824. label=_('LAG hash policy'),
  1825. choices=add_blank_choice(InterfaceLAGHashPolicyChoices),
  1826. required=False,
  1827. )
  1828. mode = TypedChoiceField(
  1829. label=_('802.1Q Mode'),
  1830. choices=add_blank_choice(InterfaceModeChoices),
  1831. required=False,
  1832. help_text=_('IEEE 802.1Q tagging strategy'),
  1833. widget=HTMXSelect(hx_target_id='dot1q-switching'),
  1834. )
  1835. rf_role = TypedChoiceField(
  1836. label=_('Wireless role'),
  1837. choices=add_blank_choice(WirelessRoleChoices),
  1838. required=False,
  1839. )
  1840. rf_channel = TypedChoiceField(
  1841. label=_('Wireless channel'),
  1842. choices=add_blank_choice(WirelessChannelChoices),
  1843. required=False,
  1844. )
  1845. vdcs = DynamicModelMultipleChoiceField(
  1846. queryset=VirtualDeviceContext.objects.all(),
  1847. required=False,
  1848. label=_('Virtual device contexts'),
  1849. initial_params={
  1850. 'interfaces': '$parent',
  1851. },
  1852. query_params={
  1853. 'device_id': '$device',
  1854. }
  1855. )
  1856. parent = DynamicModelChoiceField(
  1857. queryset=Interface.objects.all(),
  1858. required=False,
  1859. label=_('Parent interface'),
  1860. query_params={
  1861. 'virtual_chassis_member_id': '$device',
  1862. }
  1863. )
  1864. bridge = DynamicModelChoiceField(
  1865. queryset=Interface.objects.all(),
  1866. required=False,
  1867. label=_('Bridged interface'),
  1868. query_params={
  1869. 'virtual_chassis_member_id': '$device',
  1870. }
  1871. )
  1872. lag = DynamicModelChoiceField(
  1873. queryset=Interface.objects.all(),
  1874. required=False,
  1875. label=_('LAG interface'),
  1876. query_params={
  1877. 'virtual_chassis_member_id': '$device',
  1878. 'type': 'lag',
  1879. }
  1880. )
  1881. wireless_lan_group = DynamicModelChoiceField(
  1882. queryset=WirelessLANGroup.objects.all(),
  1883. required=False,
  1884. label=_('Wireless LAN group')
  1885. )
  1886. wireless_lans = DynamicModelMultipleChoiceField(
  1887. queryset=WirelessLAN.objects.all(),
  1888. required=False,
  1889. label=_('Wireless LANs'),
  1890. query_params={
  1891. 'group_id': '$wireless_lan_group',
  1892. }
  1893. )
  1894. vlan_group = DynamicModelChoiceField(
  1895. queryset=VLANGroup.objects.all(),
  1896. required=False,
  1897. label=_('VLAN group'),
  1898. help_text=_("Filter VLANs available for assignment by group.")
  1899. )
  1900. untagged_vlan = DynamicModelChoiceField(
  1901. queryset=VLAN.objects.all(),
  1902. required=False,
  1903. label=_('Untagged VLAN'),
  1904. query_params={
  1905. 'group_id': '$vlan_group',
  1906. 'available_on_device': '$device',
  1907. }
  1908. )
  1909. tagged_vlans = DynamicModelMultipleChoiceField(
  1910. queryset=VLAN.objects.all(),
  1911. required=False,
  1912. label=_('Tagged VLANs'),
  1913. query_params={
  1914. 'group_id': '$vlan_group',
  1915. 'available_on_device': '$device',
  1916. }
  1917. )
  1918. qinq_svlan = DynamicModelChoiceField(
  1919. queryset=VLAN.objects.all(),
  1920. required=False,
  1921. label=_('Q-in-Q Service VLAN'),
  1922. query_params={
  1923. 'group_id': '$vlan_group',
  1924. 'available_on_device': '$device',
  1925. 'qinq_role': VLANQinQRoleChoices.ROLE_SERVICE,
  1926. }
  1927. )
  1928. vrf = DynamicModelChoiceField(
  1929. queryset=VRF.objects.all(),
  1930. required=False,
  1931. label=_('VRF')
  1932. )
  1933. wwn = forms.CharField(
  1934. empty_value=None,
  1935. required=False,
  1936. label=_('WWN')
  1937. )
  1938. vlan_translation_policy = DynamicModelChoiceField(
  1939. queryset=VLANTranslationPolicy.objects.all(),
  1940. required=False,
  1941. label=_('VLAN Translation Policy')
  1942. )
  1943. fieldsets = (
  1944. FieldSet(
  1945. 'device', 'module', 'name', 'label', 'type', 'channels', 'speed', 'duplex', 'description', 'tags',
  1946. name=_('Interface')
  1947. ),
  1948. FieldSet('vrf', 'mac_address', 'wwn', name=_('Addressing')),
  1949. FieldSet('vdcs', 'mtu', 'tx_power', 'enabled', 'mgmt_only', 'mark_connected', name=_('Operation')),
  1950. FieldSet('parent', 'channel_id', 'bridge', 'lag', name=_('Related Interfaces')),
  1951. FieldSet('poe_mode', 'poe_type', name=_('PoE')),
  1952. FieldSet('lag_mode', 'lag_hash_policy', name=_('LAG'), html_id='lag-attributes'),
  1953. FieldSet(
  1954. 'mode', 'vlan_group', 'untagged_vlan', 'tagged_vlans', 'qinq_svlan', 'vlan_translation_policy',
  1955. name=_('802.1Q Switching'),
  1956. html_id='dot1q-switching',
  1957. ),
  1958. FieldSet(
  1959. 'rf_role', 'rf_channel', 'rf_channel_frequency', 'rf_channel_width', 'wireless_lan_group', 'wireless_lans',
  1960. name=_('Wireless')
  1961. ),
  1962. )
  1963. class Meta:
  1964. model = Interface
  1965. fields = [
  1966. 'device', 'module', 'vdcs', 'name', 'label', 'type', 'channels', 'channel_id', 'speed', 'duplex', 'enabled',
  1967. 'parent', 'bridge', 'lag', 'wwn', 'mtu', 'mgmt_only', 'mark_connected', 'description', 'poe_mode',
  1968. 'poe_type', 'lag_mode', 'lag_hash_policy', 'mode', 'rf_role', 'rf_channel', 'rf_channel_frequency',
  1969. 'rf_channel_width', 'tx_power', 'wireless_lans', 'untagged_vlan', 'tagged_vlans', 'qinq_svlan',
  1970. 'vlan_translation_policy', 'vrf', 'owner', 'tags',
  1971. ]
  1972. widgets = {
  1973. 'speed': NumberWithOptions(
  1974. options=InterfaceSpeedChoices
  1975. ),
  1976. }
  1977. def __init__(self, *args, **kwargs):
  1978. super().__init__(*args, **kwargs)
  1979. # A hash policy applies only to LAG modes which hash
  1980. if get_field_value(self, 'lag_mode') not in LAG_HASH_MODES:
  1981. del self.fields['lag_hash_policy']
  1982. def clean(self):
  1983. super().clean()
  1984. # Clear a hash policy left over from a previous LAG mode
  1985. if 'lag_hash_policy' not in self.fields:
  1986. self.instance.lag_hash_policy = None
  1987. # Clear LAG attributes left over when changing a LAG interface to another type
  1988. if self.instance.is_lag and self.cleaned_data.get('type') != InterfaceTypeChoices.TYPE_LAG:
  1989. self.cleaned_data['lag_mode'] = None
  1990. self.instance.lag_hash_policy = None
  1991. if 'lag_hash_policy' in self.fields:
  1992. self.cleaned_data['lag_hash_policy'] = None
  1993. class FrontPortForm(FrontPortFormMixin, ModularDeviceComponentForm):
  1994. type = ChoiceField(
  1995. label=_('Type'),
  1996. choices=PortTypeChoices,
  1997. )
  1998. fieldsets = (
  1999. FieldSet(
  2000. 'device', 'module', 'name', 'label', 'type', 'color', 'positions', 'rear_ports', 'mark_connected',
  2001. 'description', 'tags',
  2002. ),
  2003. )
  2004. port_mapping_model = PortMapping
  2005. rear_port_model = RearPort
  2006. class Meta:
  2007. model = FrontPort
  2008. fields = [
  2009. 'device', 'module', 'name', 'label', 'type', 'color', 'positions', 'mark_connected', 'description', 'owner',
  2010. 'tags',
  2011. ]
  2012. def __init__(self, *args, **kwargs):
  2013. super().__init__(*args, **kwargs)
  2014. # Populate rear port choices
  2015. if device_id := self.data.get('device') or self.initial.get('device'):
  2016. parent_filter = Q(device=device_id)
  2017. else:
  2018. return
  2019. self.fields['rear_ports'].choices = self._get_rear_port_choices(parent_filter, self.instance)
  2020. # Set initial rear port mappings
  2021. if self.instance.pk:
  2022. self.initial['rear_ports'] = [
  2023. f'{mapping.rear_port_id}:{mapping.rear_port_position}'
  2024. for mapping in PortMapping.objects.filter(front_port_id=self.instance.pk)
  2025. ]
  2026. class RearPortForm(ModularDeviceComponentForm):
  2027. type = ChoiceField(
  2028. label=_('Type'),
  2029. choices=PortTypeChoices,
  2030. )
  2031. fieldsets = (
  2032. FieldSet(
  2033. 'device', 'module', 'name', 'label', 'type', 'color', 'positions', 'mark_connected', 'description', 'tags',
  2034. ),
  2035. )
  2036. class Meta:
  2037. model = RearPort
  2038. fields = [
  2039. 'device', 'module', 'name', 'label', 'type', 'color', 'positions', 'mark_connected', 'description', 'owner',
  2040. 'tags',
  2041. ]
  2042. class ModuleBayForm(ModularDeviceComponentForm):
  2043. module_bay_types = DynamicModelMultipleChoiceField(
  2044. label=_('Module bay types'),
  2045. queryset=ModuleBayType.objects.all(),
  2046. required=False,
  2047. )
  2048. fieldsets = (
  2049. FieldSet('device', 'module', 'name', 'label', 'position', 'enabled', 'description', 'module_bay_types', 'tags'),
  2050. )
  2051. class Meta:
  2052. model = ModuleBay
  2053. fields = [
  2054. 'device', 'module', 'name', 'label', 'position', 'enabled', 'description', 'module_bay_types', 'owner',
  2055. 'tags',
  2056. ]
  2057. class DeviceBayForm(DeviceComponentForm):
  2058. fieldsets = (
  2059. FieldSet('device', 'name', 'label', 'enabled', 'description', 'tags',),
  2060. )
  2061. class Meta:
  2062. model = DeviceBay
  2063. fields = [
  2064. 'device', 'name', 'label', 'enabled', 'description', 'owner', 'tags',
  2065. ]
  2066. class PopulateDeviceBayForm(forms.Form):
  2067. installed_device = forms.ModelChoiceField(
  2068. queryset=Device.objects.all(),
  2069. label=_('Child Device'),
  2070. help_text=_("Child devices must first be created and assigned to the site and rack of the parent device.")
  2071. )
  2072. def __init__(self, device_bay, *args, **kwargs):
  2073. super().__init__(*args, **kwargs)
  2074. self.fields['installed_device'].queryset = Device.objects.filter(
  2075. site=device_bay.device.site,
  2076. rack=device_bay.device.rack,
  2077. parent_bay__isnull=True,
  2078. device_type__u_height=0,
  2079. device_type__subdevice_role=SubdeviceRoleChoices.ROLE_CHILD
  2080. ).exclude(pk=device_bay.device.pk)
  2081. class InventoryItemForm(DeviceComponentForm):
  2082. status = ChoiceField(
  2083. label=_('Status'),
  2084. choices=InventoryItemStatusChoices,
  2085. initial=InventoryItemStatusChoices.STATUS_ACTIVE,
  2086. )
  2087. parent = DynamicModelChoiceField(
  2088. label=_('Parent'),
  2089. queryset=InventoryItem.objects.all(),
  2090. required=False,
  2091. query_params={
  2092. 'device_id': '$device'
  2093. }
  2094. )
  2095. role = DynamicModelChoiceField(
  2096. label=_('Role'),
  2097. queryset=InventoryItemRole.objects.all(),
  2098. required=False
  2099. )
  2100. manufacturer = DynamicModelChoiceField(
  2101. label=_('Manufacturer'),
  2102. queryset=Manufacturer.objects.all(),
  2103. required=False
  2104. )
  2105. # Assigned component selectors
  2106. consoleport = DynamicModelChoiceField(
  2107. queryset=ConsolePort.objects.all(),
  2108. required=False,
  2109. query_params={
  2110. 'device_id': '$device'
  2111. },
  2112. label=_('Console port')
  2113. )
  2114. consoleserverport = DynamicModelChoiceField(
  2115. queryset=ConsoleServerPort.objects.all(),
  2116. required=False,
  2117. query_params={
  2118. 'device_id': '$device'
  2119. },
  2120. label=_('Console server port')
  2121. )
  2122. frontport = DynamicModelChoiceField(
  2123. queryset=FrontPort.objects.all(),
  2124. required=False,
  2125. query_params={
  2126. 'device_id': '$device'
  2127. },
  2128. label=_('Front port')
  2129. )
  2130. interface = DynamicModelChoiceField(
  2131. queryset=Interface.objects.all(),
  2132. required=False,
  2133. query_params={
  2134. 'device_id': '$device'
  2135. },
  2136. label=_('Interface')
  2137. )
  2138. poweroutlet = DynamicModelChoiceField(
  2139. queryset=PowerOutlet.objects.all(),
  2140. required=False,
  2141. query_params={
  2142. 'device_id': '$device'
  2143. },
  2144. label=_('Power outlet')
  2145. )
  2146. powerport = DynamicModelChoiceField(
  2147. queryset=PowerPort.objects.all(),
  2148. required=False,
  2149. query_params={
  2150. 'device_id': '$device'
  2151. },
  2152. label=_('Power port')
  2153. )
  2154. rearport = DynamicModelChoiceField(
  2155. queryset=RearPort.objects.all(),
  2156. required=False,
  2157. query_params={
  2158. 'device_id': '$device'
  2159. },
  2160. label=_('Rear port')
  2161. )
  2162. fieldsets = (
  2163. FieldSet(
  2164. 'device', 'parent', 'name', 'label', 'status', 'role', 'description', 'tags',
  2165. name=_('Inventory Item')
  2166. ),
  2167. FieldSet('manufacturer', 'part_id', 'serial', 'asset_tag', name=_('Hardware')),
  2168. FieldSet(
  2169. TabbedGroups(
  2170. FieldSet('interface', name=_('Interface')),
  2171. FieldSet('consoleport', name=_('Console Port')),
  2172. FieldSet('consoleserverport', name=_('Console Server Port')),
  2173. FieldSet('frontport', name=_('Front Port')),
  2174. FieldSet('rearport', name=_('Rear Port')),
  2175. FieldSet('powerport', name=_('Power Port')),
  2176. FieldSet('poweroutlet', name=_('Power Outlet')),
  2177. ),
  2178. name=_('Component Assignment')
  2179. )
  2180. )
  2181. class Meta:
  2182. model = InventoryItem
  2183. fields = [
  2184. 'device', 'parent', 'name', 'label', 'role', 'manufacturer', 'part_id', 'serial', 'asset_tag',
  2185. 'status', 'description', 'owner', 'tags',
  2186. ]
  2187. def __init__(self, *args, **kwargs):
  2188. instance = kwargs.get('instance')
  2189. initial = kwargs.get('initial', {}).copy()
  2190. component_type = initial.get('component_type')
  2191. component_id = initial.get('component_id')
  2192. if instance:
  2193. # When editing set the initial value for component selection
  2194. for component_model in ContentType.objects.filter(MODULAR_COMPONENT_MODELS):
  2195. if type(instance.component) is component_model.model_class():
  2196. initial[component_model.model] = instance.component
  2197. break
  2198. elif component_type and component_id:
  2199. # When adding the InventoryItem from a component page
  2200. if content_type := ContentType.objects.filter(MODULAR_COMPONENT_MODELS).filter(pk=component_type).first():
  2201. if component := content_type.model_class().objects.filter(pk=component_id).first():
  2202. initial[content_type.model] = component
  2203. kwargs['initial'] = initial
  2204. super().__init__(*args, **kwargs)
  2205. # Specifically allow editing the device of IntentoryItems
  2206. if self.instance.pk:
  2207. self.fields['device'].disabled = False
  2208. def clean(self):
  2209. super().clean()
  2210. # Handle object assignment
  2211. selected_objects = [
  2212. field for field in (
  2213. 'consoleport', 'consoleserverport', 'frontport', 'interface', 'poweroutlet', 'powerport', 'rearport'
  2214. ) if self.cleaned_data[field]
  2215. ]
  2216. if len(selected_objects) > 1:
  2217. raise forms.ValidationError(_("An InventoryItem can only be assigned to a single component."))
  2218. if selected_objects:
  2219. self.instance.component = self.cleaned_data[selected_objects[0]]
  2220. else:
  2221. self.instance.component = None
  2222. class InventoryItemRoleForm(OrganizationalModelForm):
  2223. fieldsets = (
  2224. FieldSet('name', 'slug', 'color', 'description', 'tags', name=_('Inventory Item Role')),
  2225. )
  2226. class Meta:
  2227. model = InventoryItemRole
  2228. fields = [
  2229. 'name', 'slug', 'color', 'description', 'owner', 'comments', 'tags',
  2230. ]
  2231. class VirtualDeviceContextForm(TenancyForm, PrimaryModelForm):
  2232. status = ChoiceField(
  2233. label=_('Status'),
  2234. choices=VirtualDeviceContextStatusChoices,
  2235. )
  2236. device = DynamicModelChoiceField(
  2237. label=_('Device'),
  2238. queryset=Device.objects.all(),
  2239. selector=True
  2240. )
  2241. primary_ip4 = DynamicModelChoiceField(
  2242. queryset=IPAddress.objects.all(),
  2243. label=_('Primary IPv4'),
  2244. required=False,
  2245. query_params={
  2246. 'device_id': '$device',
  2247. 'family': '4',
  2248. }
  2249. )
  2250. primary_ip6 = DynamicModelChoiceField(
  2251. queryset=IPAddress.objects.all(),
  2252. label=_('Primary IPv6'),
  2253. required=False,
  2254. query_params={
  2255. 'device_id': '$device',
  2256. 'family': '6',
  2257. }
  2258. )
  2259. fieldsets = (
  2260. FieldSet(
  2261. 'device', 'name', 'status', 'identifier', 'primary_ip4', 'primary_ip6', 'tags',
  2262. name=_('Virtual Device Context')
  2263. ),
  2264. FieldSet('tenant_group', 'tenant', name=_('Tenancy'))
  2265. )
  2266. class Meta:
  2267. model = VirtualDeviceContext
  2268. fields = [
  2269. 'device', 'name', 'status', 'identifier', 'primary_ip4', 'primary_ip6', 'tenant_group', 'tenant', 'owner',
  2270. 'comments', 'tags'
  2271. ]
  2272. #
  2273. # Addressing
  2274. #
  2275. class MACAddressForm(PrimaryModelForm):
  2276. mac_address = forms.CharField(
  2277. required=True,
  2278. label=_('MAC address')
  2279. )
  2280. interface = DynamicModelChoiceField(
  2281. label=_('Interface'),
  2282. queryset=Interface.objects.all(),
  2283. required=False,
  2284. selector=True,
  2285. context={
  2286. 'parent': 'device',
  2287. },
  2288. )
  2289. vminterface = DynamicModelChoiceField(
  2290. label=_('VM Interface'),
  2291. queryset=VMInterface.objects.all(),
  2292. required=False,
  2293. selector=True,
  2294. context={
  2295. 'parent': 'virtual_machine',
  2296. },
  2297. )
  2298. fieldsets = (
  2299. FieldSet(
  2300. 'mac_address', 'description', 'tags',
  2301. ),
  2302. FieldSet(
  2303. TabbedGroups(
  2304. FieldSet('interface', name=_('Device')),
  2305. FieldSet('vminterface', name=_('Virtual Machine')),
  2306. ),
  2307. ),
  2308. )
  2309. class Meta:
  2310. model = MACAddress
  2311. fields = [
  2312. 'mac_address', 'interface', 'vminterface', 'description', 'owner', 'comments', 'tags',
  2313. ]
  2314. def __init__(self, *args, **kwargs):
  2315. # Initialize helper selectors
  2316. instance = kwargs.get('instance')
  2317. initial = kwargs.get('initial', {}).copy()
  2318. if instance:
  2319. if type(instance.assigned_object) is Interface:
  2320. initial['interface'] = instance.assigned_object
  2321. elif type(instance.assigned_object) is VMInterface:
  2322. initial['vminterface'] = instance.assigned_object
  2323. kwargs['initial'] = initial
  2324. super().__init__(*args, **kwargs)
  2325. if instance and instance.assigned_object and instance.assigned_object.primary_mac_address:
  2326. if instance.assigned_object.primary_mac_address.pk == instance.pk:
  2327. self.fields['interface'].disabled = True
  2328. self.fields['vminterface'].disabled = True
  2329. def clean(self):
  2330. super().clean()
  2331. # Handle object assignment
  2332. selected_objects = [
  2333. field for field in ('interface', 'vminterface') if self.cleaned_data[field]
  2334. ]
  2335. if len(selected_objects) > 1:
  2336. raise forms.ValidationError({
  2337. selected_objects[1]: _("A MAC address can only be assigned to a single object.")
  2338. })
  2339. if selected_objects:
  2340. self.instance.assigned_object = self.cleaned_data[selected_objects[0]]
  2341. else:
  2342. self.instance.assigned_object = None
  2343. class MACBlockForm(PrimaryModelForm):
  2344. prefix = forms.CharField(
  2345. required=True,
  2346. label=_('Prefix'),
  2347. help_text=_('The first MAC address in the block (e.g. BC:24:11:00:00:00)')
  2348. )
  2349. fieldsets = (
  2350. FieldSet(
  2351. 'prefix', 'prefix_length', 'name', 'enforce_unique', 'description', 'tags', name=_('MAC Address Block')
  2352. ),
  2353. )
  2354. class Meta:
  2355. model = MACBlock
  2356. fields = [
  2357. 'prefix', 'prefix_length', 'name', 'enforce_unique', 'description', 'owner', 'comments', 'tags',
  2358. ]