model_forms.py 63 KB

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