bulk_import.py 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757
  1. from django import forms
  2. from django.contrib.contenttypes.models import ContentType
  3. from django.contrib.postgres.forms.array import SimpleArrayField
  4. from django.core.exceptions import ObjectDoesNotExist
  5. from django.utils.safestring import mark_safe
  6. from django.utils.translation import gettext_lazy as _
  7. from dcim.choices import *
  8. from dcim.constants import *
  9. from dcim.models import *
  10. from extras.models import ConfigTemplate
  11. from ipam.choices import VLANQinQRoleChoices
  12. from ipam.models import VLAN, VRF, IPAddress, VLANGroup
  13. from netbox.choices import *
  14. from netbox.forms import (
  15. NestedGroupModelImportForm, NetBoxModelImportForm, OrganizationalModelImportForm, OwnerCSVMixin,
  16. PrimaryModelImportForm,
  17. )
  18. from tenancy.models import Tenant
  19. from utilities.forms.fields import (
  20. CSVChoiceField, CSVContentTypeField, CSVModelChoiceField, CSVModelMultipleChoiceField, CSVTypedChoiceField,
  21. SlugField,
  22. )
  23. from virtualization.models import Cluster, VirtualMachine, VMInterface
  24. from wireless.choices import WirelessRoleChoices
  25. from .common import ModuleCommonForm
  26. __all__ = (
  27. 'CableImportForm',
  28. 'ConsolePortImportForm',
  29. 'ConsoleServerPortImportForm',
  30. 'DeviceBayImportForm',
  31. 'DeviceImportForm',
  32. 'DeviceRoleImportForm',
  33. 'DeviceTypeImportForm',
  34. 'FrontPortImportForm',
  35. 'InterfaceImportForm',
  36. 'InventoryItemImportForm',
  37. 'InventoryItemRoleImportForm',
  38. 'LocationImportForm',
  39. 'MACAddressImportForm',
  40. 'ManufacturerImportForm',
  41. 'ModuleImportForm',
  42. 'ModuleBayImportForm',
  43. 'ModuleTypeImportForm',
  44. 'ModuleTypeProfileImportForm',
  45. 'PlatformImportForm',
  46. 'PowerFeedImportForm',
  47. 'PowerOutletImportForm',
  48. 'PowerPanelImportForm',
  49. 'PowerPortImportForm',
  50. 'RackImportForm',
  51. 'RackReservationImportForm',
  52. 'RackRoleImportForm',
  53. 'RackTypeImportForm',
  54. 'RearPortImportForm',
  55. 'RegionImportForm',
  56. 'SiteImportForm',
  57. 'SiteGroupImportForm',
  58. 'VirtualChassisImportForm',
  59. 'VirtualDeviceContextImportForm'
  60. )
  61. class RegionImportForm(NestedGroupModelImportForm):
  62. parent = CSVModelChoiceField(
  63. label=_('Parent'),
  64. queryset=Region.objects.all(),
  65. required=False,
  66. to_field_name='name',
  67. help_text=_('Name of parent region')
  68. )
  69. class Meta:
  70. model = Region
  71. fields = ('name', 'slug', 'parent', 'description', 'owner', 'comments', 'tags')
  72. class SiteGroupImportForm(NestedGroupModelImportForm):
  73. parent = CSVModelChoiceField(
  74. label=_('Parent'),
  75. queryset=SiteGroup.objects.all(),
  76. required=False,
  77. to_field_name='name',
  78. help_text=_('Name of parent site group')
  79. )
  80. class Meta:
  81. model = SiteGroup
  82. fields = ('name', 'slug', 'parent', 'description', 'owner', 'comments', 'tags')
  83. class SiteImportForm(PrimaryModelImportForm):
  84. status = CSVChoiceField(
  85. label=_('Status'),
  86. choices=SiteStatusChoices,
  87. help_text=_('Operational status')
  88. )
  89. region = CSVModelChoiceField(
  90. label=_('Region'),
  91. queryset=Region.objects.all(),
  92. required=False,
  93. to_field_name='name',
  94. help_text=_('Assigned region')
  95. )
  96. group = CSVModelChoiceField(
  97. label=_('Group'),
  98. queryset=SiteGroup.objects.all(),
  99. required=False,
  100. to_field_name='name',
  101. help_text=_('Assigned group')
  102. )
  103. tenant = CSVModelChoiceField(
  104. label=_('Tenant'),
  105. queryset=Tenant.objects.all(),
  106. required=False,
  107. to_field_name='name',
  108. help_text=_('Assigned tenant')
  109. )
  110. class Meta:
  111. model = Site
  112. fields = (
  113. 'name', 'slug', 'status', 'region', 'group', 'tenant', 'facility', 'time_zone', 'description',
  114. 'physical_address', 'shipping_address', 'latitude', 'longitude', 'owner', 'comments', 'tags'
  115. )
  116. help_texts = {
  117. 'time_zone': mark_safe(
  118. '{} (<a href="https://en.wikipedia.org/wiki/List_of_tz_database_time_zones">{}</a>)'.format(
  119. _('Time zone'), _('available options')
  120. )
  121. )
  122. }
  123. class LocationImportForm(NestedGroupModelImportForm):
  124. site = CSVModelChoiceField(
  125. label=_('Site'),
  126. queryset=Site.objects.all(),
  127. to_field_name='name',
  128. help_text=_('Assigned site')
  129. )
  130. parent = CSVModelChoiceField(
  131. label=_('Parent'),
  132. queryset=Location.objects.all(),
  133. required=False,
  134. to_field_name='name',
  135. help_text=_('Parent location'),
  136. error_messages={
  137. 'invalid_choice': _('Location not found.'),
  138. }
  139. )
  140. status = CSVChoiceField(
  141. label=_('Status'),
  142. choices=LocationStatusChoices,
  143. help_text=_('Operational status')
  144. )
  145. tenant = CSVModelChoiceField(
  146. label=_('Tenant'),
  147. queryset=Tenant.objects.all(),
  148. required=False,
  149. to_field_name='name',
  150. help_text=_('Assigned tenant')
  151. )
  152. class Meta:
  153. model = Location
  154. fields = (
  155. 'site', 'parent', 'name', 'slug', 'status', 'tenant', 'facility', 'description', 'owner', 'comments',
  156. 'tags',
  157. )
  158. def __init__(self, data=None, *args, **kwargs):
  159. super().__init__(data, *args, **kwargs)
  160. if data:
  161. # Limit location queryset by assigned site
  162. params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
  163. self.fields['parent'].queryset = self.fields['parent'].queryset.filter(**params)
  164. class RackRoleImportForm(OrganizationalModelImportForm):
  165. class Meta:
  166. model = RackRole
  167. fields = ('name', 'slug', 'color', 'description', 'owner', 'tags')
  168. class RackTypeImportForm(PrimaryModelImportForm):
  169. manufacturer = forms.ModelChoiceField(
  170. label=_('Manufacturer'),
  171. queryset=Manufacturer.objects.all(),
  172. to_field_name='name',
  173. help_text=_('The manufacturer of this rack type')
  174. )
  175. form_factor = CSVChoiceField(
  176. label=_('Type'),
  177. choices=RackFormFactorChoices,
  178. required=False,
  179. help_text=_('Form factor')
  180. )
  181. starting_unit = forms.IntegerField(
  182. required=False,
  183. min_value=1,
  184. help_text=_('The lowest-numbered position in the rack')
  185. )
  186. width = forms.ChoiceField(
  187. label=_('Width'),
  188. choices=RackWidthChoices,
  189. help_text=_('Rail-to-rail width (in inches)')
  190. )
  191. outer_unit = CSVChoiceField(
  192. label=_('Outer unit'),
  193. choices=RackDimensionUnitChoices,
  194. required=False,
  195. help_text=_('Unit for outer dimensions')
  196. )
  197. weight_unit = CSVChoiceField(
  198. label=_('Weight unit'),
  199. choices=WeightUnitChoices,
  200. required=False,
  201. help_text=_('Unit for rack weights')
  202. )
  203. class Meta:
  204. model = RackType
  205. fields = (
  206. 'manufacturer', 'model', 'slug', 'form_factor', 'width', 'u_height', 'starting_unit', 'desc_units',
  207. 'outer_width', 'outer_height', 'outer_depth', 'outer_unit', 'mounting_depth', 'weight', 'max_weight',
  208. 'weight_unit', 'description', 'owner', 'comments', 'tags',
  209. )
  210. def __init__(self, data=None, *args, **kwargs):
  211. super().__init__(data, *args, **kwargs)
  212. class RackImportForm(PrimaryModelImportForm):
  213. site = CSVModelChoiceField(
  214. label=_('Site'),
  215. queryset=Site.objects.all(),
  216. to_field_name='name'
  217. )
  218. location = CSVModelChoiceField(
  219. label=_('Location'),
  220. queryset=Location.objects.all(),
  221. required=False,
  222. to_field_name='name'
  223. )
  224. tenant = CSVModelChoiceField(
  225. label=_('Tenant'),
  226. queryset=Tenant.objects.all(),
  227. required=False,
  228. to_field_name='name',
  229. help_text=_('Name of assigned tenant')
  230. )
  231. status = CSVChoiceField(
  232. label=_('Status'),
  233. choices=RackStatusChoices,
  234. help_text=_('Operational status')
  235. )
  236. role = CSVModelChoiceField(
  237. label=_('Role'),
  238. queryset=RackRole.objects.all(),
  239. required=False,
  240. to_field_name='name',
  241. help_text=_('Name of assigned role')
  242. )
  243. rack_type = CSVModelChoiceField(
  244. label=_('Rack type'),
  245. queryset=RackType.objects.all(),
  246. to_field_name='model',
  247. required=False,
  248. help_text=_('Rack type model')
  249. )
  250. form_factor = CSVChoiceField(
  251. label=_('Type'),
  252. choices=RackFormFactorChoices,
  253. required=False,
  254. help_text=_('Form factor')
  255. )
  256. width = forms.ChoiceField(
  257. label=_('Width'),
  258. choices=RackWidthChoices,
  259. required=False,
  260. help_text=_('Rail-to-rail width (in inches)')
  261. )
  262. u_height = forms.IntegerField(
  263. required=False,
  264. label=_('Height (U)')
  265. )
  266. outer_unit = CSVChoiceField(
  267. label=_('Outer unit'),
  268. choices=RackDimensionUnitChoices,
  269. required=False,
  270. help_text=_('Unit for outer dimensions')
  271. )
  272. airflow = CSVChoiceField(
  273. label=_('Airflow'),
  274. choices=RackAirflowChoices,
  275. required=False,
  276. help_text=_('Airflow direction')
  277. )
  278. weight_unit = CSVChoiceField(
  279. label=_('Weight unit'),
  280. choices=WeightUnitChoices,
  281. required=False,
  282. help_text=_('Unit for rack weights')
  283. )
  284. class Meta:
  285. model = Rack
  286. fields = (
  287. 'site', 'location', 'name', 'facility_id', 'tenant', 'status', 'role', 'rack_type', 'form_factor', 'serial',
  288. 'asset_tag', 'width', 'u_height', 'desc_units', 'outer_width', 'outer_height', 'outer_depth', 'outer_unit',
  289. 'mounting_depth', 'airflow', 'weight', 'max_weight', 'weight_unit', 'description', 'owner', 'comments',
  290. 'tags',
  291. )
  292. def __init__(self, data=None, *args, **kwargs):
  293. super().__init__(data, *args, **kwargs)
  294. if data:
  295. # Limit location queryset by assigned site
  296. params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
  297. self.fields['location'].queryset = self.fields['location'].queryset.filter(**params)
  298. def clean(self):
  299. super().clean()
  300. # width & u_height must be set if not specifying a rack type on import
  301. if not self.instance.pk:
  302. if not self.cleaned_data.get('rack_type') and not self.cleaned_data.get('width'):
  303. raise forms.ValidationError(_("Width must be set if not specifying a rack type."))
  304. if not self.cleaned_data.get('rack_type') and not self.cleaned_data.get('u_height'):
  305. raise forms.ValidationError(_("U height must be set if not specifying a rack type."))
  306. class RackReservationImportForm(PrimaryModelImportForm):
  307. site = CSVModelChoiceField(
  308. label=_('Site'),
  309. queryset=Site.objects.all(),
  310. to_field_name='name',
  311. help_text=_('Parent site')
  312. )
  313. location = CSVModelChoiceField(
  314. label=_('Location'),
  315. queryset=Location.objects.all(),
  316. to_field_name='name',
  317. required=False,
  318. help_text=_("Rack's location (if any)")
  319. )
  320. rack = CSVModelChoiceField(
  321. label=_('Rack'),
  322. queryset=Rack.objects.all(),
  323. to_field_name='name',
  324. help_text=_('Rack')
  325. )
  326. units = SimpleArrayField(
  327. label=_('Units'),
  328. base_field=forms.IntegerField(),
  329. required=True,
  330. help_text=_('Comma-separated list of individual unit numbers')
  331. )
  332. status = CSVChoiceField(
  333. label=_('Status'),
  334. choices=RackReservationStatusChoices,
  335. help_text=_('Operational status')
  336. )
  337. tenant = CSVModelChoiceField(
  338. label=_('Tenant'),
  339. queryset=Tenant.objects.all(),
  340. required=False,
  341. to_field_name='name',
  342. help_text=_('Assigned tenant')
  343. )
  344. class Meta:
  345. model = RackReservation
  346. fields = ('site', 'location', 'rack', 'units', 'status', 'tenant', 'description', 'owner', 'comments', 'tags')
  347. def __init__(self, data=None, *args, **kwargs):
  348. super().__init__(data, *args, **kwargs)
  349. if data:
  350. # Limit location queryset by assigned site
  351. params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
  352. self.fields['location'].queryset = self.fields['location'].queryset.filter(**params)
  353. # Limit rack queryset by assigned site and group
  354. params = {
  355. f"site__{self.fields['site'].to_field_name}": data.get('site'),
  356. f"location__{self.fields['location'].to_field_name}": data.get('location'),
  357. }
  358. self.fields['rack'].queryset = self.fields['rack'].queryset.filter(**params)
  359. class ManufacturerImportForm(OrganizationalModelImportForm):
  360. class Meta:
  361. model = Manufacturer
  362. fields = ('name', 'slug', 'description', 'owner', 'tags')
  363. class DeviceTypeImportForm(PrimaryModelImportForm):
  364. manufacturer = CSVModelChoiceField(
  365. label=_('Manufacturer'),
  366. queryset=Manufacturer.objects.all(),
  367. to_field_name='name',
  368. help_text=_('The manufacturer which produces this device type')
  369. )
  370. default_platform = CSVModelChoiceField(
  371. label=_('Default platform'),
  372. queryset=Platform.objects.all(),
  373. to_field_name='name',
  374. required=False,
  375. help_text=_('The default platform for devices of this type (optional)')
  376. )
  377. weight = forms.DecimalField(
  378. label=_('Weight'),
  379. required=False,
  380. help_text=_('Device weight'),
  381. )
  382. weight_unit = CSVChoiceField(
  383. label=_('Weight unit'),
  384. choices=WeightUnitChoices,
  385. required=False,
  386. help_text=_('Unit for device weight')
  387. )
  388. class Meta:
  389. model = DeviceType
  390. fields = [
  391. 'manufacturer', 'default_platform', 'model', 'slug', 'part_number', 'u_height', 'exclude_from_utilization',
  392. 'is_full_depth', 'subdevice_role', 'airflow', 'description', 'weight', 'weight_unit', 'owner', 'comments',
  393. 'tags',
  394. ]
  395. class ModuleTypeProfileImportForm(PrimaryModelImportForm):
  396. class Meta:
  397. model = ModuleTypeProfile
  398. fields = [
  399. 'name', 'description', 'schema', 'owner', 'comments', 'tags',
  400. ]
  401. class ModuleTypeImportForm(PrimaryModelImportForm):
  402. profile = forms.ModelChoiceField(
  403. label=_('Profile'),
  404. queryset=ModuleTypeProfile.objects.all(),
  405. to_field_name='name',
  406. required=False
  407. )
  408. manufacturer = forms.ModelChoiceField(
  409. label=_('Manufacturer'),
  410. queryset=Manufacturer.objects.all(),
  411. to_field_name='name'
  412. )
  413. airflow = CSVChoiceField(
  414. label=_('Airflow'),
  415. choices=ModuleAirflowChoices,
  416. required=False,
  417. help_text=_('Airflow direction')
  418. )
  419. weight = forms.DecimalField(
  420. label=_('Weight'),
  421. required=False,
  422. help_text=_('Module weight'),
  423. )
  424. weight_unit = CSVChoiceField(
  425. label=_('Weight unit'),
  426. choices=WeightUnitChoices,
  427. required=False,
  428. help_text=_('Unit for module weight')
  429. )
  430. attribute_data = forms.JSONField(
  431. label=_('Attributes'),
  432. required=False,
  433. help_text=_('Attribute values for the assigned profile, passed as a dictionary')
  434. )
  435. class Meta:
  436. model = ModuleType
  437. fields = [
  438. 'manufacturer', 'model', 'part_number', 'description', 'airflow', 'weight', 'weight_unit', 'profile',
  439. 'attribute_data', 'owner', 'comments', 'tags',
  440. ]
  441. def clean(self):
  442. super().clean()
  443. # Attribute data may be included only if a profile is specified
  444. if self.cleaned_data.get('attribute_data') and not self.cleaned_data.get('profile'):
  445. raise forms.ValidationError(_("Profile must be specified if attribute data is provided."))
  446. # Default attribute_data to an empty dictionary if a profile is specified (to enforce schema validation)
  447. if self.cleaned_data.get('profile') and not self.cleaned_data.get('attribute_data'):
  448. self.cleaned_data['attribute_data'] = {}
  449. class DeviceRoleImportForm(NestedGroupModelImportForm):
  450. parent = CSVModelChoiceField(
  451. label=_('Parent'),
  452. queryset=DeviceRole.objects.all(),
  453. required=False,
  454. to_field_name='name',
  455. help_text=_('Parent Device Role'),
  456. error_messages={
  457. 'invalid_choice': _('Device role not found.'),
  458. }
  459. )
  460. config_template = CSVModelChoiceField(
  461. label=_('Config template'),
  462. queryset=ConfigTemplate.objects.all(),
  463. to_field_name='name',
  464. required=False,
  465. help_text=_('Config template')
  466. )
  467. class Meta:
  468. model = DeviceRole
  469. fields = (
  470. 'name', 'slug', 'parent', 'color', 'vm_role', 'config_template', 'description', 'owner', 'comments', 'tags'
  471. )
  472. class PlatformImportForm(NestedGroupModelImportForm):
  473. parent = CSVModelChoiceField(
  474. label=_('Parent'),
  475. queryset=Platform.objects.all(),
  476. required=False,
  477. to_field_name='name',
  478. help_text=_('Parent platform'),
  479. error_messages={
  480. 'invalid_choice': _('Platform not found.'),
  481. }
  482. )
  483. manufacturer = CSVModelChoiceField(
  484. label=_('Manufacturer'),
  485. queryset=Manufacturer.objects.all(),
  486. required=False,
  487. to_field_name='name',
  488. help_text=_('Limit platform assignments to this manufacturer')
  489. )
  490. config_template = CSVModelChoiceField(
  491. label=_('Config template'),
  492. queryset=ConfigTemplate.objects.all(),
  493. to_field_name='name',
  494. required=False,
  495. help_text=_('Config template')
  496. )
  497. class Meta:
  498. model = Platform
  499. fields = (
  500. 'name', 'slug', 'parent', 'manufacturer', 'config_template', 'description', 'owner', 'comments', 'tags',
  501. )
  502. class BaseDeviceImportForm(PrimaryModelImportForm):
  503. role = CSVModelChoiceField(
  504. label=_('Device role'),
  505. queryset=DeviceRole.objects.all(),
  506. to_field_name='name',
  507. help_text=_('Assigned role')
  508. )
  509. tenant = CSVModelChoiceField(
  510. label=_('Tenant'),
  511. queryset=Tenant.objects.all(),
  512. required=False,
  513. to_field_name='name',
  514. help_text=_('Assigned tenant')
  515. )
  516. manufacturer = CSVModelChoiceField(
  517. label=_('Manufacturer'),
  518. queryset=Manufacturer.objects.all(),
  519. to_field_name='name',
  520. help_text=_('Device type manufacturer')
  521. )
  522. device_type = CSVModelChoiceField(
  523. label=_('Device type'),
  524. queryset=DeviceType.objects.all(),
  525. to_field_name='model',
  526. help_text=_('Device type model')
  527. )
  528. platform = CSVModelChoiceField(
  529. label=_('Platform'),
  530. queryset=Platform.objects.all(),
  531. required=False,
  532. to_field_name='name',
  533. help_text=_('Assigned platform')
  534. )
  535. status = CSVChoiceField(
  536. label=_('Status'),
  537. choices=DeviceStatusChoices,
  538. help_text=_('Operational status')
  539. )
  540. virtual_chassis = CSVModelChoiceField(
  541. label=_('Virtual chassis'),
  542. queryset=VirtualChassis.objects.all(),
  543. to_field_name='name',
  544. required=False,
  545. help_text=_('Virtual chassis')
  546. )
  547. cluster = CSVModelChoiceField(
  548. label=_('Cluster'),
  549. queryset=Cluster.objects.all(),
  550. to_field_name='name',
  551. required=False,
  552. help_text=_('Virtualization cluster')
  553. )
  554. class Meta:
  555. fields = []
  556. model = Device
  557. def __init__(self, data=None, *args, **kwargs):
  558. super().__init__(data, *args, **kwargs)
  559. if data:
  560. # Limit device type queryset by manufacturer
  561. params = {f"manufacturer__{self.fields['manufacturer'].to_field_name}": data.get('manufacturer')}
  562. self.fields['device_type'].queryset = self.fields['device_type'].queryset.filter(**params)
  563. class DeviceImportForm(BaseDeviceImportForm):
  564. site = CSVModelChoiceField(
  565. label=_('Site'),
  566. queryset=Site.objects.all(),
  567. to_field_name='name',
  568. help_text=_('Assigned site')
  569. )
  570. location = CSVModelChoiceField(
  571. label=_('Location'),
  572. queryset=Location.objects.all(),
  573. to_field_name='name',
  574. required=False,
  575. help_text=_("Assigned location (if any)")
  576. )
  577. rack = CSVModelChoiceField(
  578. label=_('Rack'),
  579. queryset=Rack.objects.all(),
  580. to_field_name='name',
  581. required=False,
  582. help_text=_("Assigned rack (if any)")
  583. )
  584. face = CSVChoiceField(
  585. label=_('Face'),
  586. choices=DeviceFaceChoices,
  587. required=False,
  588. help_text=_('Mounted rack face')
  589. )
  590. parent = CSVModelChoiceField(
  591. label=_('Parent'),
  592. queryset=Device.objects.all(),
  593. to_field_name='name',
  594. required=False,
  595. help_text=_('Parent device (for child devices)')
  596. )
  597. device_bay = CSVModelChoiceField(
  598. label=_('Device bay'),
  599. queryset=DeviceBay.objects.all(),
  600. to_field_name='name',
  601. required=False,
  602. help_text=_('Device bay in which this device is installed (for child devices)')
  603. )
  604. airflow = CSVChoiceField(
  605. label=_('Airflow'),
  606. choices=DeviceAirflowChoices,
  607. required=False,
  608. help_text=_('Airflow direction')
  609. )
  610. config_template = CSVModelChoiceField(
  611. label=_('Config template'),
  612. queryset=ConfigTemplate.objects.all(),
  613. to_field_name='name',
  614. required=False,
  615. help_text=_('Config template')
  616. )
  617. class Meta(BaseDeviceImportForm.Meta):
  618. fields = [
  619. 'name', 'role', 'tenant', 'manufacturer', 'device_type', 'platform', 'serial', 'asset_tag', 'status',
  620. 'site', 'location', 'rack', 'position', 'face', 'latitude', 'longitude', 'parent', 'device_bay', 'airflow',
  621. 'virtual_chassis', 'vc_position', 'vc_priority', 'cluster', 'description', 'config_template', 'owner',
  622. 'comments', 'tags',
  623. ]
  624. def __init__(self, data=None, *args, **kwargs):
  625. super().__init__(data, *args, **kwargs)
  626. if data:
  627. # Limit location queryset by assigned site
  628. params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
  629. self.fields['location'].queryset = self.fields['location'].queryset.filter(**params)
  630. self.fields['parent'].queryset = self.fields['parent'].queryset.filter(**params)
  631. # Limit rack queryset by assigned site and location
  632. params = {
  633. f"site__{self.fields['site'].to_field_name}": data.get('site'),
  634. }
  635. if location := data.get('location'):
  636. params.update({
  637. f"location__{self.fields['location'].to_field_name}": location,
  638. })
  639. self.fields['rack'].queryset = self.fields['rack'].queryset.filter(**params)
  640. # Limit platform queryset by manufacturer
  641. params = {f"manufacturer__{self.fields['manufacturer'].to_field_name}": data.get('manufacturer')}
  642. self.fields['platform'].queryset = self.fields['platform'].queryset.filter(
  643. Q(**params) | Q(manufacturer=None)
  644. )
  645. # Limit device bay queryset by parent device
  646. if parent := data.get('parent'):
  647. params = {f"device__{self.fields['parent'].to_field_name}": parent}
  648. self.fields['device_bay'].queryset = self.fields['device_bay'].queryset.filter(**params)
  649. def clean(self):
  650. super().clean()
  651. # Inherit site and rack from parent device
  652. if parent := self.cleaned_data.get('parent'):
  653. self.instance.site = parent.site
  654. self.instance.rack = parent.rack
  655. # Set parent_bay reverse relationship
  656. if device_bay := self.cleaned_data.get('device_bay'):
  657. self.instance.parent_bay = device_bay
  658. class ModuleImportForm(ModuleCommonForm, PrimaryModelImportForm):
  659. device = CSVModelChoiceField(
  660. label=_('Device'),
  661. queryset=Device.objects.all(),
  662. to_field_name='name',
  663. help_text=_('The device in which this module is installed')
  664. )
  665. module_bay = CSVModelChoiceField(
  666. label=_('Module bay'),
  667. queryset=ModuleBay.objects.all(),
  668. to_field_name='name',
  669. help_text=_('The module bay in which this module is installed')
  670. )
  671. module_type = CSVModelChoiceField(
  672. label=_('Module type'),
  673. queryset=ModuleType.objects.all(),
  674. to_field_name='model',
  675. help_text=_('The type of module')
  676. )
  677. status = CSVChoiceField(
  678. label=_('Status'),
  679. choices=ModuleStatusChoices,
  680. help_text=_('Operational status')
  681. )
  682. replicate_components = forms.BooleanField(
  683. label=_('Replicate components'),
  684. required=False,
  685. help_text=_('Automatically populate components associated with this module type (enabled by default)')
  686. )
  687. adopt_components = forms.BooleanField(
  688. label=_('Adopt components'),
  689. required=False,
  690. help_text=_('Adopt already existing components')
  691. )
  692. class Meta:
  693. model = Module
  694. fields = (
  695. 'device', 'module_bay', 'module_type', 'serial', 'asset_tag', 'status', 'description', 'owner', 'comments',
  696. 'replicate_components', 'adopt_components', 'tags',
  697. )
  698. def __init__(self, data=None, *args, **kwargs):
  699. super().__init__(data, *args, **kwargs)
  700. if data:
  701. # Limit module_bay queryset by assigned device
  702. params = {f"device__{self.fields['device'].to_field_name}": data.get('device')}
  703. self.fields['module_bay'].queryset = self.fields['module_bay'].queryset.filter(**params)
  704. def clean_replicate_components(self):
  705. # Make sure replicate_components is True when it's not included in the uploaded data
  706. if 'replicate_components' not in self.data:
  707. return True
  708. else:
  709. return self.cleaned_data['replicate_components']
  710. #
  711. # Device components
  712. #
  713. class ConsolePortImportForm(OwnerCSVMixin, NetBoxModelImportForm):
  714. device = CSVModelChoiceField(
  715. label=_('Device'),
  716. queryset=Device.objects.all(),
  717. to_field_name='name'
  718. )
  719. type = CSVChoiceField(
  720. label=_('Type'),
  721. choices=ConsolePortTypeChoices,
  722. required=False,
  723. help_text=_('Port type')
  724. )
  725. speed = CSVTypedChoiceField(
  726. label=_('Speed'),
  727. choices=ConsolePortSpeedChoices,
  728. coerce=int,
  729. empty_value=None,
  730. required=False,
  731. help_text=_('Port speed in bps')
  732. )
  733. class Meta:
  734. model = ConsolePort
  735. fields = ('device', 'name', 'label', 'type', 'speed', 'mark_connected', 'description', 'owner', 'tags')
  736. class ConsoleServerPortImportForm(OwnerCSVMixin, NetBoxModelImportForm):
  737. device = CSVModelChoiceField(
  738. label=_('Device'),
  739. queryset=Device.objects.all(),
  740. to_field_name='name'
  741. )
  742. type = CSVChoiceField(
  743. label=_('Type'),
  744. choices=ConsolePortTypeChoices,
  745. required=False,
  746. help_text=_('Port type')
  747. )
  748. speed = CSVTypedChoiceField(
  749. label=_('Speed'),
  750. choices=ConsolePortSpeedChoices,
  751. coerce=int,
  752. empty_value=None,
  753. required=False,
  754. help_text=_('Port speed in bps')
  755. )
  756. class Meta:
  757. model = ConsoleServerPort
  758. fields = ('device', 'name', 'label', 'type', 'speed', 'mark_connected', 'description', 'owner', 'tags')
  759. class PowerPortImportForm(OwnerCSVMixin, NetBoxModelImportForm):
  760. device = CSVModelChoiceField(
  761. label=_('Device'),
  762. queryset=Device.objects.all(),
  763. to_field_name='name'
  764. )
  765. type = CSVChoiceField(
  766. label=_('Type'),
  767. choices=PowerPortTypeChoices,
  768. required=False,
  769. help_text=_('Port type')
  770. )
  771. class Meta:
  772. model = PowerPort
  773. fields = (
  774. 'device', 'name', 'label', 'type', 'mark_connected', 'maximum_draw', 'allocated_draw', 'description',
  775. 'owner', 'tags',
  776. )
  777. class PowerOutletImportForm(OwnerCSVMixin, NetBoxModelImportForm):
  778. device = CSVModelChoiceField(
  779. label=_('Device'),
  780. queryset=Device.objects.all(),
  781. to_field_name='name'
  782. )
  783. type = CSVChoiceField(
  784. label=_('Type'),
  785. choices=PowerOutletTypeChoices,
  786. required=False,
  787. help_text=_('Outlet type')
  788. )
  789. power_port = CSVModelChoiceField(
  790. label=_('Power port'),
  791. queryset=PowerPort.objects.all(),
  792. required=False,
  793. to_field_name='name',
  794. help_text=_('Local power port which feeds this outlet')
  795. )
  796. feed_leg = CSVChoiceField(
  797. label=_('Feed leg'),
  798. choices=PowerOutletFeedLegChoices,
  799. required=False,
  800. help_text=_('Electrical phase (for three-phase circuits)')
  801. )
  802. class Meta:
  803. model = PowerOutlet
  804. fields = (
  805. 'device', 'name', 'label', 'type', 'color', 'mark_connected', 'power_port', 'feed_leg', 'description',
  806. 'owner', 'tags',
  807. )
  808. def __init__(self, *args, **kwargs):
  809. super().__init__(*args, **kwargs)
  810. # Limit PowerPort choices to those belonging to this device (or VC master)
  811. if self.is_bound and 'device' in self.data:
  812. try:
  813. device = self.fields['device'].to_python(self.data['device'])
  814. except forms.ValidationError:
  815. device = None
  816. else:
  817. try:
  818. device = self.instance.device
  819. except Device.DoesNotExist:
  820. device = None
  821. if device:
  822. self.fields['power_port'].queryset = PowerPort.objects.filter(
  823. device__in=[device, device.get_vc_master()]
  824. )
  825. else:
  826. self.fields['power_port'].queryset = PowerPort.objects.none()
  827. class InterfaceImportForm(OwnerCSVMixin, NetBoxModelImportForm):
  828. device = CSVModelChoiceField(
  829. label=_('Device'),
  830. queryset=Device.objects.all(),
  831. to_field_name='name'
  832. )
  833. parent = CSVModelChoiceField(
  834. label=_('Parent'),
  835. queryset=Interface.objects.all(),
  836. required=False,
  837. to_field_name='name',
  838. help_text=_('Parent interface')
  839. )
  840. bridge = CSVModelChoiceField(
  841. label=_('Bridge'),
  842. queryset=Interface.objects.all(),
  843. required=False,
  844. to_field_name='name',
  845. help_text=_('Bridged interface')
  846. )
  847. lag = CSVModelChoiceField(
  848. label=_('Lag'),
  849. queryset=Interface.objects.all(),
  850. required=False,
  851. to_field_name='name',
  852. help_text=_('Parent LAG interface')
  853. )
  854. vdcs = CSVModelMultipleChoiceField(
  855. label=_('Vdcs'),
  856. queryset=VirtualDeviceContext.objects.all(),
  857. required=False,
  858. to_field_name='name',
  859. help_text=mark_safe(
  860. _('VDC names separated by commas, encased with double quotes. Example:') + ' <code>"vdc1,vdc2,vdc3"</code>'
  861. )
  862. )
  863. type = CSVChoiceField(
  864. label=_('Type'),
  865. choices=InterfaceTypeChoices,
  866. help_text=_('Physical medium')
  867. )
  868. duplex = CSVChoiceField(
  869. label=_('Duplex'),
  870. choices=InterfaceDuplexChoices,
  871. required=False
  872. )
  873. poe_mode = CSVChoiceField(
  874. label=_('Poe mode'),
  875. choices=InterfacePoEModeChoices,
  876. required=False,
  877. help_text=_('PoE mode')
  878. )
  879. poe_type = CSVChoiceField(
  880. label=_('Poe type'),
  881. choices=InterfacePoETypeChoices,
  882. required=False,
  883. help_text=_('PoE type')
  884. )
  885. mode = CSVChoiceField(
  886. label=_('Mode'),
  887. choices=InterfaceModeChoices,
  888. required=False,
  889. help_text=_('IEEE 802.1Q operational mode (for L2 interfaces)'),
  890. )
  891. vlan_group = CSVModelChoiceField(
  892. label=_('VLAN group'),
  893. queryset=VLANGroup.objects.all(),
  894. required=False,
  895. to_field_name='name',
  896. help_text=_('Filter VLANs available for assignment by group'),
  897. )
  898. untagged_vlan = CSVModelChoiceField(
  899. label=_('Untagged VLAN'),
  900. queryset=VLAN.objects.all(),
  901. required=False,
  902. to_field_name='vid',
  903. help_text=_('Assigned untagged VLAN ID (filtered by VLAN group)'),
  904. )
  905. tagged_vlans = CSVModelMultipleChoiceField(
  906. label=_('Tagged VLANs'),
  907. queryset=VLAN.objects.all(),
  908. required=False,
  909. to_field_name='vid',
  910. help_text=mark_safe(
  911. _(
  912. 'Assigned tagged VLAN IDs separated by commas, encased with double quotes '
  913. '(filtered by VLAN group). Example:'
  914. )
  915. + ' <code>"100,200,300"</code>'
  916. ),
  917. )
  918. qinq_svlan = CSVModelChoiceField(
  919. label=_('Q-in-Q Service VLAN'),
  920. queryset=VLAN.objects.filter(qinq_role=VLANQinQRoleChoices.ROLE_SERVICE),
  921. required=False,
  922. to_field_name='vid',
  923. help_text=_('Assigned Q-in-Q Service VLAN ID (filtered by VLAN group)'),
  924. )
  925. vrf = CSVModelChoiceField(
  926. label=_('VRF'),
  927. queryset=VRF.objects.all(),
  928. required=False,
  929. to_field_name='rd',
  930. help_text=_('Assigned VRF')
  931. )
  932. rf_role = CSVChoiceField(
  933. label=_('Rf role'),
  934. choices=WirelessRoleChoices,
  935. required=False,
  936. help_text=_('Wireless role (AP/station)')
  937. )
  938. class Meta:
  939. model = Interface
  940. fields = (
  941. 'device', 'name', 'label', 'parent', 'bridge', 'lag', 'type', 'speed', 'duplex', 'enabled',
  942. 'mark_connected', 'wwn', 'vdcs', 'mtu', 'mgmt_only', 'description', 'poe_mode', 'poe_type', 'mode',
  943. 'vlan_group', 'untagged_vlan', 'tagged_vlans', 'qinq_svlan', 'vrf', 'rf_role', 'rf_channel',
  944. 'rf_channel_frequency', 'rf_channel_width', 'tx_power', 'owner', 'tags'
  945. )
  946. def __init__(self, data=None, *args, **kwargs):
  947. super().__init__(data, *args, **kwargs)
  948. if data:
  949. # Limit choices for parent, bridge, and LAG interfaces to the assigned device
  950. if device := data.get('device'):
  951. params = {
  952. f"device__{self.fields['device'].to_field_name}": device
  953. }
  954. self.fields['parent'].queryset = self.fields['parent'].queryset.filter(**params)
  955. self.fields['bridge'].queryset = self.fields['bridge'].queryset.filter(**params)
  956. self.fields['lag'].queryset = self.fields['lag'].queryset.filter(**params)
  957. self.fields['vdcs'].queryset = self.fields['vdcs'].queryset.filter(**params)
  958. # Limit choices for VLANs to the assigned VLAN group
  959. if vlan_group := data.get('vlan_group'):
  960. params = {f"group__{self.fields['vlan_group'].to_field_name}": vlan_group}
  961. self.fields['untagged_vlan'].queryset = self.fields['untagged_vlan'].queryset.filter(**params)
  962. self.fields['tagged_vlans'].queryset = self.fields['tagged_vlans'].queryset.filter(**params)
  963. self.fields['qinq_svlan'].queryset = self.fields['qinq_svlan'].queryset.filter(**params)
  964. def clean_enabled(self):
  965. # Make sure enabled is True when it's not included in the uploaded data
  966. if 'enabled' not in self.data:
  967. return True
  968. else:
  969. return self.cleaned_data['enabled']
  970. def clean_vdcs(self):
  971. for vdc in self.cleaned_data['vdcs']:
  972. if vdc.device != self.cleaned_data['device']:
  973. raise forms.ValidationError(
  974. _("VDC {vdc} is not assigned to device {device}").format(
  975. vdc=vdc, device=self.cleaned_data['device']
  976. )
  977. )
  978. return self.cleaned_data['vdcs']
  979. class FrontPortImportForm(OwnerCSVMixin, NetBoxModelImportForm):
  980. device = CSVModelChoiceField(
  981. label=_('Device'),
  982. queryset=Device.objects.all(),
  983. to_field_name='name'
  984. )
  985. type = CSVChoiceField(
  986. label=_('Type'),
  987. choices=PortTypeChoices,
  988. help_text=_('Physical medium classification')
  989. )
  990. class Meta:
  991. model = FrontPort
  992. fields = (
  993. 'device', 'name', 'label', 'type', 'color', 'mark_connected', 'positions', 'description', 'owner', 'tags'
  994. )
  995. class RearPortImportForm(OwnerCSVMixin, NetBoxModelImportForm):
  996. device = CSVModelChoiceField(
  997. label=_('Device'),
  998. queryset=Device.objects.all(),
  999. to_field_name='name'
  1000. )
  1001. type = CSVChoiceField(
  1002. label=_('Type'),
  1003. help_text=_('Physical medium classification'),
  1004. choices=PortTypeChoices,
  1005. )
  1006. class Meta:
  1007. model = RearPort
  1008. fields = (
  1009. 'device', 'name', 'label', 'type', 'color', 'mark_connected', 'positions', 'description', 'owner', 'tags',
  1010. )
  1011. class ModuleBayImportForm(OwnerCSVMixin, NetBoxModelImportForm):
  1012. device = CSVModelChoiceField(
  1013. label=_('Device'),
  1014. queryset=Device.objects.all(),
  1015. to_field_name='name'
  1016. )
  1017. class Meta:
  1018. model = ModuleBay
  1019. fields = ('device', 'name', 'label', 'position', 'description', 'owner', 'tags')
  1020. class DeviceBayImportForm(OwnerCSVMixin, NetBoxModelImportForm):
  1021. device = CSVModelChoiceField(
  1022. label=_('Device'),
  1023. queryset=Device.objects.all(),
  1024. to_field_name='name'
  1025. )
  1026. installed_device = CSVModelChoiceField(
  1027. label=_('Installed device'),
  1028. queryset=Device.objects.all(),
  1029. required=False,
  1030. to_field_name='name',
  1031. help_text=_('Child device installed within this bay'),
  1032. error_messages={
  1033. 'invalid_choice': _('Child device not found.'),
  1034. }
  1035. )
  1036. class Meta:
  1037. model = DeviceBay
  1038. fields = ('device', 'name', 'label', 'installed_device', 'description', 'owner', 'tags')
  1039. def __init__(self, *args, **kwargs):
  1040. super().__init__(*args, **kwargs)
  1041. # Limit installed device choices to devices of the correct type and location
  1042. if self.is_bound and 'device' in self.data:
  1043. try:
  1044. device = self.fields['device'].to_python(self.data['device'])
  1045. except forms.ValidationError:
  1046. device = None
  1047. else:
  1048. try:
  1049. device = self.instance.device
  1050. except Device.DoesNotExist:
  1051. device = None
  1052. if device:
  1053. self.fields['installed_device'].queryset = Device.objects.filter(
  1054. site=device.site,
  1055. rack=device.rack,
  1056. parent_bay__isnull=True,
  1057. device_type__u_height=0,
  1058. device_type__subdevice_role=SubdeviceRoleChoices.ROLE_CHILD
  1059. ).exclude(pk=device.pk)
  1060. else:
  1061. self.fields['installed_device'].queryset = Device.objects.none()
  1062. class InventoryItemImportForm(OwnerCSVMixin, NetBoxModelImportForm):
  1063. device = CSVModelChoiceField(
  1064. label=_('Device'),
  1065. queryset=Device.objects.all(),
  1066. to_field_name='name'
  1067. )
  1068. role = CSVModelChoiceField(
  1069. label=_('Role'),
  1070. queryset=InventoryItemRole.objects.all(),
  1071. to_field_name='name',
  1072. required=False
  1073. )
  1074. manufacturer = CSVModelChoiceField(
  1075. label=_('Manufacturer'),
  1076. queryset=Manufacturer.objects.all(),
  1077. to_field_name='name',
  1078. required=False
  1079. )
  1080. parent = CSVModelChoiceField(
  1081. label=_('Parent'),
  1082. queryset=Device.objects.all(),
  1083. to_field_name='name',
  1084. required=False,
  1085. help_text=_('Parent inventory item')
  1086. )
  1087. component_type = CSVContentTypeField(
  1088. label=_('Component type'),
  1089. queryset=ContentType.objects.all(),
  1090. limit_choices_to=MODULAR_COMPONENT_MODELS,
  1091. required=False,
  1092. help_text=_('Component Type')
  1093. )
  1094. component_name = forms.CharField(
  1095. label=_('Component name'),
  1096. required=False,
  1097. help_text=_('Component Name')
  1098. )
  1099. status = CSVChoiceField(
  1100. label=_('Status'),
  1101. choices=InventoryItemStatusChoices,
  1102. help_text=_('Operational status')
  1103. )
  1104. class Meta:
  1105. model = InventoryItem
  1106. fields = (
  1107. 'device', 'name', 'label', 'status', 'role', 'manufacturer', 'parent', 'part_id', 'serial', 'asset_tag',
  1108. 'discovered', 'description', 'owner', 'tags', 'component_type', 'component_name',
  1109. )
  1110. def __init__(self, *args, **kwargs):
  1111. super().__init__(*args, **kwargs)
  1112. # Limit parent choices to inventory items belonging to this device
  1113. device = None
  1114. if self.is_bound and 'device' in self.data:
  1115. try:
  1116. device = self.fields['device'].to_python(self.data['device'])
  1117. except forms.ValidationError:
  1118. pass
  1119. if device:
  1120. self.fields['parent'].queryset = InventoryItem.objects.filter(device=device)
  1121. else:
  1122. self.fields['parent'].queryset = InventoryItem.objects.none()
  1123. def clean(self):
  1124. super().clean()
  1125. cleaned_data = self.cleaned_data
  1126. component_type = cleaned_data.get('component_type')
  1127. component_name = cleaned_data.get('component_name')
  1128. device = self.cleaned_data.get("device")
  1129. if component_type:
  1130. if device is None:
  1131. cleaned_data.pop('component_type', None)
  1132. if component_name is None:
  1133. cleaned_data.pop('component_type', None)
  1134. raise forms.ValidationError(
  1135. _("Component name must be specified when component type is specified")
  1136. )
  1137. if all([device, component_name]):
  1138. try:
  1139. model = component_type.model_class()
  1140. self.instance.component = model.objects.get(device=device, name=component_name)
  1141. except ObjectDoesNotExist:
  1142. cleaned_data.pop('component_type', None)
  1143. cleaned_data.pop('component_name', None)
  1144. raise forms.ValidationError(
  1145. _("Component not found: {device} - {component_name}").format(
  1146. device=device, component_name=component_name
  1147. )
  1148. )
  1149. else:
  1150. cleaned_data.pop('component_type', None)
  1151. if not component_name:
  1152. raise forms.ValidationError(
  1153. _("Component name must be specified when component type is specified")
  1154. )
  1155. else:
  1156. if component_name:
  1157. raise forms.ValidationError(
  1158. _("Component type must be specified when component name is specified")
  1159. )
  1160. return cleaned_data
  1161. #
  1162. # Device component roles
  1163. #
  1164. class InventoryItemRoleImportForm(OrganizationalModelImportForm):
  1165. slug = SlugField()
  1166. class Meta:
  1167. model = InventoryItemRole
  1168. fields = ('name', 'slug', 'color', 'description')
  1169. #
  1170. # Addressing
  1171. #
  1172. class MACAddressImportForm(PrimaryModelImportForm):
  1173. device = CSVModelChoiceField(
  1174. label=_('Device'),
  1175. queryset=Device.objects.all(),
  1176. required=False,
  1177. to_field_name='name',
  1178. help_text=_('Parent device of assigned interface (if any)')
  1179. )
  1180. virtual_machine = CSVModelChoiceField(
  1181. label=_('Virtual machine'),
  1182. queryset=VirtualMachine.objects.all(),
  1183. required=False,
  1184. to_field_name='name',
  1185. help_text=_('Parent VM of assigned interface (if any)')
  1186. )
  1187. interface = CSVModelChoiceField(
  1188. label=_('Interface'),
  1189. queryset=Interface.objects.none(), # Can also refer to VMInterface
  1190. required=False,
  1191. to_field_name='name',
  1192. help_text=_('Assigned interface')
  1193. )
  1194. is_primary = forms.BooleanField(
  1195. label=_('Is primary'),
  1196. help_text=_('Make this the primary MAC address for the assigned interface'),
  1197. required=False
  1198. )
  1199. class Meta:
  1200. model = MACAddress
  1201. fields = [
  1202. 'mac_address', 'device', 'virtual_machine', 'interface', 'is_primary', 'description', 'owner', 'comments',
  1203. 'tags',
  1204. ]
  1205. def __init__(self, data=None, *args, **kwargs):
  1206. super().__init__(data, *args, **kwargs)
  1207. if data:
  1208. # Limit interface queryset by assigned device
  1209. if data.get('device'):
  1210. self.fields['interface'].queryset = Interface.objects.filter(
  1211. **{f"device__{self.fields['device'].to_field_name}": data['device']}
  1212. )
  1213. # Limit interface queryset by assigned device
  1214. elif data.get('virtual_machine'):
  1215. self.fields['interface'].queryset = VMInterface.objects.filter(
  1216. **{f"virtual_machine__{self.fields['virtual_machine'].to_field_name}": data['virtual_machine']}
  1217. )
  1218. def clean(self):
  1219. super().clean()
  1220. device = self.cleaned_data.get('device')
  1221. virtual_machine = self.cleaned_data.get('virtual_machine')
  1222. interface = self.cleaned_data.get('interface')
  1223. # Validate interface assignment
  1224. if interface and not device and not virtual_machine:
  1225. raise forms.ValidationError({
  1226. "interface": _("Must specify the parent device or VM when assigning an interface")
  1227. })
  1228. def save(self, *args, **kwargs):
  1229. # Set interface assignment
  1230. if interface := self.cleaned_data.get('interface'):
  1231. self.instance.assigned_object = interface
  1232. instance = super().save(*args, **kwargs)
  1233. # Assign the MAC address as primary for its interface, if designated as such
  1234. if interface and self.cleaned_data['is_primary'] and self.instance.pk:
  1235. interface.primary_mac_address = self.instance
  1236. interface.save()
  1237. return instance
  1238. #
  1239. # Cables
  1240. #
  1241. class CableImportForm(PrimaryModelImportForm):
  1242. # Termination A
  1243. side_a_site = CSVModelChoiceField(
  1244. label=_('Side A site'),
  1245. queryset=Site.objects.all(),
  1246. required=False,
  1247. to_field_name='name',
  1248. help_text=_('Site of parent device A (if any)'),
  1249. )
  1250. side_a_device = CSVModelChoiceField(
  1251. label=_('Side A device'),
  1252. queryset=Device.objects.all(),
  1253. to_field_name='name',
  1254. help_text=_('Device name')
  1255. )
  1256. side_a_type = CSVContentTypeField(
  1257. label=_('Side A type'),
  1258. queryset=ContentType.objects.all(),
  1259. limit_choices_to=CABLE_TERMINATION_MODELS,
  1260. help_text=_('Termination type')
  1261. )
  1262. side_a_name = forms.CharField(
  1263. label=_('Side A name'),
  1264. help_text=_('Termination name')
  1265. )
  1266. # Termination B
  1267. side_b_site = CSVModelChoiceField(
  1268. label=_('Side B site'),
  1269. queryset=Site.objects.all(),
  1270. required=False,
  1271. to_field_name='name',
  1272. help_text=_('Site of parent device B (if any)'),
  1273. )
  1274. side_b_device = CSVModelChoiceField(
  1275. label=_('Side B device'),
  1276. queryset=Device.objects.all(),
  1277. to_field_name='name',
  1278. help_text=_('Device name')
  1279. )
  1280. side_b_type = CSVContentTypeField(
  1281. label=_('Side B type'),
  1282. queryset=ContentType.objects.all(),
  1283. limit_choices_to=CABLE_TERMINATION_MODELS,
  1284. help_text=_('Termination type')
  1285. )
  1286. side_b_name = forms.CharField(
  1287. label=_('Side B name'),
  1288. help_text=_('Termination name')
  1289. )
  1290. # Cable attributes
  1291. status = CSVChoiceField(
  1292. label=_('Status'),
  1293. choices=LinkStatusChoices,
  1294. required=False,
  1295. help_text=_('Connection status')
  1296. )
  1297. profile = CSVChoiceField(
  1298. label=_('Profile'),
  1299. choices=CableProfileChoices,
  1300. required=False,
  1301. help_text=_('Cable connection profile')
  1302. )
  1303. type = CSVChoiceField(
  1304. label=_('Type'),
  1305. choices=CableTypeChoices,
  1306. required=False,
  1307. help_text=_('Physical medium classification')
  1308. )
  1309. tenant = CSVModelChoiceField(
  1310. label=_('Tenant'),
  1311. queryset=Tenant.objects.all(),
  1312. required=False,
  1313. to_field_name='name',
  1314. help_text=_('Assigned tenant')
  1315. )
  1316. length_unit = CSVChoiceField(
  1317. label=_('Length unit'),
  1318. choices=CableLengthUnitChoices,
  1319. required=False,
  1320. help_text=_('Length unit')
  1321. )
  1322. color = forms.CharField(
  1323. label=_('Color'),
  1324. required=False,
  1325. max_length=16,
  1326. help_text=_('Color name (e.g. "Red") or hex code (e.g. "f44336")')
  1327. )
  1328. class Meta:
  1329. model = Cable
  1330. fields = [
  1331. 'side_a_site', 'side_a_device', 'side_a_type', 'side_a_name', 'side_b_site', 'side_b_device', 'side_b_type',
  1332. 'side_b_name', 'type', 'status', 'profile', 'tenant', 'label', 'color', 'length', 'length_unit',
  1333. 'description', 'owner', 'comments', 'tags',
  1334. ]
  1335. def __init__(self, data=None, *args, **kwargs):
  1336. super().__init__(data, *args, **kwargs)
  1337. if data:
  1338. # Limit choices for side_a_device to the assigned side_a_site
  1339. if side_a_site := data.get('side_a_site'):
  1340. side_a_device_params = {f'site__{self.fields["side_a_site"].to_field_name}': side_a_site}
  1341. self.fields['side_a_device'].queryset = self.fields['side_a_device'].queryset.filter(
  1342. **side_a_device_params
  1343. )
  1344. # Limit choices for side_b_device to the assigned side_b_site
  1345. if side_b_site := data.get('side_b_site'):
  1346. side_b_device_params = {f'site__{self.fields["side_b_site"].to_field_name}': side_b_site}
  1347. self.fields['side_b_device'].queryset = self.fields['side_b_device'].queryset.filter(
  1348. **side_b_device_params
  1349. )
  1350. def _clean_side(self, side):
  1351. """
  1352. Derive a Cable's A/B termination objects.
  1353. :param side: 'a' or 'b'
  1354. """
  1355. assert side in 'ab', f"Invalid side designation: {side}"
  1356. device = self.cleaned_data.get(f'side_{side}_device')
  1357. content_type = self.cleaned_data.get(f'side_{side}_type')
  1358. name = self.cleaned_data.get(f'side_{side}_name')
  1359. if not device or not content_type or not name:
  1360. return None
  1361. model = content_type.model_class()
  1362. try:
  1363. if device.virtual_chassis and device.virtual_chassis.master == device and \
  1364. model.objects.filter(device=device, name=name).count() == 0:
  1365. termination_object = model.objects.get(device__in=device.virtual_chassis.members.all(), name=name)
  1366. else:
  1367. termination_object = model.objects.get(device=device, name=name)
  1368. if termination_object.cable is not None and termination_object.cable != self.instance:
  1369. raise forms.ValidationError(
  1370. _("Side {side_upper}: {device} {termination_object} is already connected").format(
  1371. side_upper=side.upper(), device=device, termination_object=termination_object
  1372. )
  1373. )
  1374. except ObjectDoesNotExist:
  1375. raise forms.ValidationError(
  1376. _("{side_upper} side termination not found: {device} {name}").format(
  1377. side_upper=side.upper(), device=device, name=name
  1378. )
  1379. )
  1380. setattr(self.instance, f'{side}_terminations', [termination_object])
  1381. return termination_object
  1382. def _clean_color(self, color):
  1383. """
  1384. Derive a colors hex code
  1385. :param color: color as hex or color name
  1386. """
  1387. color_parsed = color.strip().lower()
  1388. for hex_code, label in ColorChoices.CHOICES:
  1389. if color.lower() == label.lower():
  1390. color_parsed = hex_code
  1391. if len(color_parsed) > 6:
  1392. raise forms.ValidationError(
  1393. _(f"{color} did not match any used color name and was longer than six characters: invalid hex.")
  1394. )
  1395. return color_parsed
  1396. def clean_side_a_name(self):
  1397. return self._clean_side('a')
  1398. def clean_side_b_name(self):
  1399. return self._clean_side('b')
  1400. def clean_length_unit(self):
  1401. # Avoid trying to save as NULL
  1402. length_unit = self.cleaned_data.get('length_unit', None)
  1403. return length_unit if length_unit is not None else ''
  1404. def clean_color(self):
  1405. color = self.cleaned_data.get('color', None)
  1406. return self._clean_color(color) if color is not None else ''
  1407. #
  1408. # Virtual chassis
  1409. #
  1410. class VirtualChassisImportForm(PrimaryModelImportForm):
  1411. master = CSVModelChoiceField(
  1412. label=_('Master'),
  1413. queryset=Device.objects.all(),
  1414. to_field_name='name',
  1415. required=False,
  1416. help_text=_('Master device')
  1417. )
  1418. class Meta:
  1419. model = VirtualChassis
  1420. fields = ('name', 'domain', 'master', 'description', 'owner', 'comments', 'tags')
  1421. #
  1422. # Power
  1423. #
  1424. class PowerPanelImportForm(PrimaryModelImportForm):
  1425. site = CSVModelChoiceField(
  1426. label=_('Site'),
  1427. queryset=Site.objects.all(),
  1428. to_field_name='name',
  1429. help_text=_('Name of parent site')
  1430. )
  1431. location = CSVModelChoiceField(
  1432. label=_('Location'),
  1433. queryset=Location.objects.all(),
  1434. required=False,
  1435. to_field_name='name'
  1436. )
  1437. class Meta:
  1438. model = PowerPanel
  1439. fields = ('site', 'location', 'name', 'description', 'owner', 'comments', 'tags')
  1440. def __init__(self, data=None, *args, **kwargs):
  1441. super().__init__(data, *args, **kwargs)
  1442. if data:
  1443. # Limit group queryset by assigned site
  1444. params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
  1445. self.fields['location'].queryset = self.fields['location'].queryset.filter(**params)
  1446. class PowerFeedImportForm(PrimaryModelImportForm):
  1447. site = CSVModelChoiceField(
  1448. label=_('Site'),
  1449. queryset=Site.objects.all(),
  1450. to_field_name='name',
  1451. help_text=_('Assigned site')
  1452. )
  1453. power_panel = CSVModelChoiceField(
  1454. label=_('Power panel'),
  1455. queryset=PowerPanel.objects.all(),
  1456. to_field_name='name',
  1457. help_text=_('Upstream power panel')
  1458. )
  1459. location = CSVModelChoiceField(
  1460. label=_('Location'),
  1461. queryset=Location.objects.all(),
  1462. to_field_name='name',
  1463. required=False,
  1464. help_text=_("Rack's location (if any)")
  1465. )
  1466. rack = CSVModelChoiceField(
  1467. label=_('Rack'),
  1468. queryset=Rack.objects.all(),
  1469. to_field_name='name',
  1470. required=False,
  1471. help_text=_('Rack')
  1472. )
  1473. tenant = CSVModelChoiceField(
  1474. queryset=Tenant.objects.all(),
  1475. to_field_name='name',
  1476. required=False,
  1477. help_text=_('Assigned tenant')
  1478. )
  1479. status = CSVChoiceField(
  1480. label=_('Status'),
  1481. choices=PowerFeedStatusChoices,
  1482. help_text=_('Operational status')
  1483. )
  1484. type = CSVChoiceField(
  1485. label=_('Type'),
  1486. choices=PowerFeedTypeChoices,
  1487. help_text=_('Primary or redundant')
  1488. )
  1489. supply = CSVChoiceField(
  1490. label=_('Supply'),
  1491. choices=PowerFeedSupplyChoices,
  1492. help_text=_('Supply type (AC/DC)')
  1493. )
  1494. phase = CSVChoiceField(
  1495. label=_('Phase'),
  1496. choices=PowerFeedPhaseChoices,
  1497. help_text=_('Single or three-phase')
  1498. )
  1499. class Meta:
  1500. model = PowerFeed
  1501. fields = (
  1502. 'site', 'power_panel', 'location', 'rack', 'name', 'status', 'type', 'mark_connected', 'supply', 'phase',
  1503. 'voltage', 'amperage', 'max_utilization', 'tenant', 'description', 'owner', 'comments', 'tags',
  1504. )
  1505. def __init__(self, data=None, *args, **kwargs):
  1506. super().__init__(data, *args, **kwargs)
  1507. if data:
  1508. # Limit power_panel queryset by site
  1509. params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
  1510. self.fields['power_panel'].queryset = self.fields['power_panel'].queryset.filter(**params)
  1511. # Limit location queryset by site
  1512. params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
  1513. self.fields['location'].queryset = self.fields['location'].queryset.filter(**params)
  1514. # Limit rack queryset by site and group
  1515. params = {
  1516. f"site__{self.fields['site'].to_field_name}": data.get('site'),
  1517. f"location__{self.fields['location'].to_field_name}": data.get('location'),
  1518. }
  1519. self.fields['rack'].queryset = self.fields['rack'].queryset.filter(**params)
  1520. class VirtualDeviceContextImportForm(PrimaryModelImportForm):
  1521. device = CSVModelChoiceField(
  1522. label=_('Device'),
  1523. queryset=Device.objects.all(),
  1524. to_field_name='name',
  1525. help_text=_('Assigned role')
  1526. )
  1527. tenant = CSVModelChoiceField(
  1528. label=_('Tenant'),
  1529. queryset=Tenant.objects.all(),
  1530. required=False,
  1531. to_field_name='name',
  1532. help_text=_('Assigned tenant')
  1533. )
  1534. status = CSVChoiceField(
  1535. label=_('Status'),
  1536. choices=VirtualDeviceContextStatusChoices,
  1537. )
  1538. primary_ip4 = CSVModelChoiceField(
  1539. label=_('Primary IPv4'),
  1540. queryset=IPAddress.objects.all(),
  1541. required=False,
  1542. to_field_name='address',
  1543. help_text=_('IPv4 address with mask, e.g. 1.2.3.4/24')
  1544. )
  1545. primary_ip6 = CSVModelChoiceField(
  1546. label=_('Primary IPv6'),
  1547. queryset=IPAddress.objects.all(),
  1548. required=False,
  1549. to_field_name='address',
  1550. help_text=_('IPv6 address with prefix length, e.g. 2001:db8::1/64')
  1551. )
  1552. class Meta:
  1553. fields = [
  1554. 'name', 'device', 'status', 'tenant', 'identifier', 'owner', 'comments', 'primary_ip4', 'primary_ip6',
  1555. ]
  1556. model = VirtualDeviceContext
  1557. def __init__(self, data=None, *args, **kwargs):
  1558. super().__init__(data, *args, **kwargs)
  1559. if data:
  1560. # Limit primary_ip4/ip6 querysets by assigned device
  1561. params = {f"interface__device__{self.fields['device'].to_field_name}": data.get('device')}
  1562. self.fields['primary_ip4'].queryset = self.fields['primary_ip4'].queryset.filter(**params)
  1563. self.fields['primary_ip6'].queryset = self.fields['primary_ip6'].queryset.filter(**params)