model_forms.py 61 KB

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