model_forms.py 62 KB

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