bulk_import.py 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526
  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 NON_FIELD_ERRORS, MultipleObjectsReturned, ObjectDoesNotExist
  5. from django.utils.functional import lazy
  6. from django.utils.html import format_html
  7. from django.utils.safestring import SafeString, mark_safe
  8. from django.utils.translation import gettext_lazy as _
  9. from dcim.choices import *
  10. from dcim.constants import *
  11. from dcim.models import *
  12. from dcim.utils import reconcile_port_mappings
  13. from extras.models import ConfigTemplate
  14. from ipam.choices import VLANQinQRoleChoices
  15. from ipam.models import VLAN, VRF, IPAddress, VLANGroup
  16. from netbox.choices import *
  17. from netbox.forms import (
  18. NestedGroupModelImportForm,
  19. NetBoxModelImportForm,
  20. OrganizationalModelImportForm,
  21. OwnerCSVMixin,
  22. PrimaryModelImportForm,
  23. )
  24. from tenancy.models import Tenant
  25. from utilities.forms.fields import (
  26. CSVChoiceField,
  27. CSVContentTypeField,
  28. CSVModelChoiceField,
  29. CSVModelMultipleChoiceField,
  30. CSVTypedChoiceField,
  31. SlugField,
  32. )
  33. from virtualization.models import Cluster, VirtualMachine, VMInterface
  34. from wireless.choices import WirelessRoleChoices
  35. from .common import ModuleCommonForm
  36. __all__ = (
  37. 'CableBundleImportForm',
  38. 'CableImportForm',
  39. 'ConsolePortImportForm',
  40. 'ConsoleServerPortImportForm',
  41. 'CoolingFeedImportForm',
  42. 'CoolingIntakeImportForm',
  43. 'CoolingOutflowImportForm',
  44. 'CoolingSourceImportForm',
  45. 'DeviceBayImportForm',
  46. 'DeviceImportForm',
  47. 'DeviceRoleImportForm',
  48. 'DeviceTypeImportForm',
  49. 'FrontPortImportForm',
  50. 'InterfaceImportForm',
  51. 'InventoryItemImportForm',
  52. 'InventoryItemRoleImportForm',
  53. 'LocationImportForm',
  54. 'MACAddressImportForm',
  55. 'MACBlockImportForm',
  56. 'ManufacturerImportForm',
  57. 'ModuleBayImportForm',
  58. 'ModuleBayTypeImportForm',
  59. 'ModuleImportForm',
  60. 'ModuleTypeImportForm',
  61. 'ModuleTypeProfileImportForm',
  62. 'PlatformImportForm',
  63. 'PowerFeedImportForm',
  64. 'PowerOutletImportForm',
  65. 'PowerPanelImportForm',
  66. 'PowerPortImportForm',
  67. 'RackGroupImportForm',
  68. 'RackImportForm',
  69. 'RackReservationImportForm',
  70. 'RackRoleImportForm',
  71. 'RackTypeImportForm',
  72. 'RearPortImportForm',
  73. 'RegionImportForm',
  74. 'SiteGroupImportForm',
  75. 'SiteImportForm',
  76. 'VirtualChassisImportForm',
  77. 'VirtualDeviceContextImportForm'
  78. )
  79. # A lazily evaluated format_html(), for help text which must not resolve its translated content until
  80. # the field is rendered. Unlike mark_safe(), this escapes the interpolated arguments.
  81. format_html_lazy = lazy(format_html, SafeString)
  82. class RegionImportForm(NestedGroupModelImportForm):
  83. parent = CSVModelChoiceField(
  84. label=_('Parent'),
  85. queryset=Region.objects.all(),
  86. required=False,
  87. to_field_name='name',
  88. help_text=_('Name of parent region')
  89. )
  90. class Meta:
  91. model = Region
  92. fields = ('name', 'slug', 'parent', 'description', 'owner', 'comments', 'tags')
  93. class SiteGroupImportForm(NestedGroupModelImportForm):
  94. parent = CSVModelChoiceField(
  95. label=_('Parent'),
  96. queryset=SiteGroup.objects.all(),
  97. required=False,
  98. to_field_name='name',
  99. help_text=_('Name of parent site group')
  100. )
  101. class Meta:
  102. model = SiteGroup
  103. fields = ('name', 'slug', 'parent', 'description', 'owner', 'comments', 'tags')
  104. class SiteImportForm(PrimaryModelImportForm):
  105. status = CSVChoiceField(
  106. label=_('Status'),
  107. choices=SiteStatusChoices,
  108. help_text=_('Operational status')
  109. )
  110. region = CSVModelChoiceField(
  111. label=_('Region'),
  112. queryset=Region.objects.all(),
  113. required=False,
  114. to_field_name='name',
  115. help_text=_('Assigned region')
  116. )
  117. group = CSVModelChoiceField(
  118. label=_('Group'),
  119. queryset=SiteGroup.objects.all(),
  120. required=False,
  121. to_field_name='name',
  122. help_text=_('Assigned group')
  123. )
  124. tenant = CSVModelChoiceField(
  125. label=_('Tenant'),
  126. queryset=Tenant.objects.all(),
  127. required=False,
  128. to_field_name='name',
  129. help_text=_('Assigned tenant')
  130. )
  131. class Meta:
  132. model = Site
  133. fields = (
  134. 'name', 'slug', 'status', 'region', 'group', 'tenant', 'facility', 'time_zone', 'description',
  135. 'physical_address', 'shipping_address', 'latitude', 'longitude', 'owner', 'comments', 'tags'
  136. )
  137. help_texts = {
  138. 'time_zone': mark_safe(
  139. '{} (<a href="https://en.wikipedia.org/wiki/List_of_tz_database_time_zones">{}</a>)'.format(
  140. _('Time zone'), _('available options')
  141. )
  142. )
  143. }
  144. class LocationImportForm(NestedGroupModelImportForm):
  145. site = CSVModelChoiceField(
  146. label=_('Site'),
  147. queryset=Site.objects.all(),
  148. to_field_name='name',
  149. help_text=_('Assigned site')
  150. )
  151. parent = CSVModelChoiceField(
  152. label=_('Parent'),
  153. queryset=Location.objects.all(),
  154. required=False,
  155. to_field_name='name',
  156. help_text=_('Parent location'),
  157. error_messages={
  158. 'invalid_choice': _('Location not found.'),
  159. }
  160. )
  161. status = CSVChoiceField(
  162. label=_('Status'),
  163. choices=LocationStatusChoices,
  164. help_text=_('Operational status')
  165. )
  166. tenant = CSVModelChoiceField(
  167. label=_('Tenant'),
  168. queryset=Tenant.objects.all(),
  169. required=False,
  170. to_field_name='name',
  171. help_text=_('Assigned tenant')
  172. )
  173. class Meta:
  174. model = Location
  175. fields = (
  176. 'site', 'parent', 'name', 'slug', 'status', 'tenant', 'facility', 'description', 'owner', 'comments',
  177. 'tags',
  178. )
  179. def __init__(self, data=None, *args, **kwargs):
  180. super().__init__(data, *args, **kwargs)
  181. if data:
  182. # Limit location queryset by assigned site
  183. params = self.get_related_filter('site', 'site', data.get('site'))
  184. self.fields['parent'].queryset = self.fields['parent'].queryset.filter(**params)
  185. class RackGroupImportForm(OrganizationalModelImportForm):
  186. class Meta:
  187. model = RackGroup
  188. fields = ('name', 'slug', 'description', 'owner', 'comments', 'tags')
  189. class RackRoleImportForm(OrganizationalModelImportForm):
  190. class Meta:
  191. model = RackRole
  192. fields = ('name', 'slug', 'color', 'description', 'owner', 'comments', 'tags')
  193. class RackTypeImportForm(PrimaryModelImportForm):
  194. manufacturer = forms.ModelChoiceField(
  195. label=_('Manufacturer'),
  196. queryset=Manufacturer.objects.all(),
  197. to_field_name='name',
  198. help_text=_('The manufacturer of this rack type')
  199. )
  200. form_factor = CSVChoiceField(
  201. label=_('Type'),
  202. choices=RackFormFactorChoices,
  203. help_text=_('Form factor')
  204. )
  205. starting_unit = forms.IntegerField(
  206. required=False,
  207. min_value=1,
  208. help_text=_('The lowest-numbered position in the rack')
  209. )
  210. width = forms.ChoiceField(
  211. label=_('Width'),
  212. choices=RackWidthChoices,
  213. help_text=_('Rail-to-rail width (in inches)')
  214. )
  215. outer_unit = CSVChoiceField(
  216. label=_('Outer unit'),
  217. choices=RackDimensionUnitChoices,
  218. required=False,
  219. help_text=_('Unit for outer dimensions')
  220. )
  221. weight_unit = CSVChoiceField(
  222. label=_('Weight unit'),
  223. choices=WeightUnitChoices,
  224. required=False,
  225. help_text=_('Unit for rack weights')
  226. )
  227. cooling_capability = CSVChoiceField(
  228. label=_('Cooling capability'),
  229. choices=RackCoolingCapabilityChoices,
  230. required=False,
  231. help_text=_('Cooling capability')
  232. )
  233. class Meta:
  234. model = RackType
  235. fields = (
  236. 'manufacturer', 'model', 'slug', 'form_factor', 'width', 'u_height', 'starting_unit', 'desc_units',
  237. 'outer_width', 'outer_height', 'outer_depth', 'outer_unit', 'mounting_depth', 'weight', 'max_weight',
  238. 'weight_unit', 'cooling_capability', 'cooling_capacity', 'description', 'owner', 'comments', 'tags',
  239. )
  240. def __init__(self, data=None, *args, **kwargs):
  241. super().__init__(data, *args, **kwargs)
  242. class RackImportForm(PrimaryModelImportForm):
  243. site = CSVModelChoiceField(
  244. label=_('Site'),
  245. queryset=Site.objects.all(),
  246. to_field_name='name'
  247. )
  248. location = CSVModelChoiceField(
  249. label=_('Location'),
  250. queryset=Location.objects.all(),
  251. required=False,
  252. to_field_name='name'
  253. )
  254. tenant = CSVModelChoiceField(
  255. label=_('Tenant'),
  256. queryset=Tenant.objects.all(),
  257. required=False,
  258. to_field_name='name',
  259. help_text=_('Name of assigned tenant')
  260. )
  261. group = CSVModelChoiceField(
  262. label=_('Rack group'),
  263. queryset=RackGroup.objects.all(),
  264. required=False,
  265. to_field_name='name',
  266. help_text=_('Name of assigned group')
  267. )
  268. status = CSVChoiceField(
  269. label=_('Status'),
  270. choices=RackStatusChoices,
  271. help_text=_('Operational status')
  272. )
  273. role = CSVModelChoiceField(
  274. label=_('Role'),
  275. queryset=RackRole.objects.all(),
  276. required=False,
  277. to_field_name='name',
  278. help_text=_('Name of assigned role')
  279. )
  280. rack_type = CSVModelChoiceField(
  281. label=_('Rack type'),
  282. queryset=RackType.objects.all(),
  283. to_field_name='model',
  284. required=False,
  285. help_text=_('Rack type model')
  286. )
  287. form_factor = CSVChoiceField(
  288. label=_('Type'),
  289. choices=RackFormFactorChoices,
  290. required=False,
  291. help_text=_('Form factor')
  292. )
  293. width = forms.ChoiceField(
  294. label=_('Width'),
  295. choices=RackWidthChoices,
  296. required=False,
  297. help_text=_('Rail-to-rail width (in inches)')
  298. )
  299. u_height = forms.IntegerField(
  300. required=False,
  301. label=_('Height (U)')
  302. )
  303. outer_unit = CSVChoiceField(
  304. label=_('Outer unit'),
  305. choices=RackDimensionUnitChoices,
  306. required=False,
  307. help_text=_('Unit for outer dimensions')
  308. )
  309. airflow = CSVChoiceField(
  310. label=_('Airflow'),
  311. choices=RackAirflowChoices,
  312. required=False,
  313. help_text=_('Airflow direction')
  314. )
  315. cooling_capability = CSVChoiceField(
  316. label=_('Cooling capability'),
  317. choices=RackCoolingCapabilityChoices,
  318. required=False,
  319. help_text=_('Cooling capability')
  320. )
  321. weight_unit = CSVChoiceField(
  322. label=_('Weight unit'),
  323. choices=WeightUnitChoices,
  324. required=False,
  325. help_text=_('Unit for rack weights')
  326. )
  327. class Meta:
  328. model = Rack
  329. fields = (
  330. 'site', 'location', 'group', 'name', 'facility_id', 'tenant', 'status', 'role', 'rack_type', 'form_factor',
  331. 'serial', 'asset_tag', 'width', 'u_height', 'desc_units', 'outer_width', 'outer_height', 'outer_depth',
  332. 'outer_unit', 'mounting_depth', 'airflow', 'cooling_capability', 'cooling_capacity', 'weight',
  333. 'max_weight', 'weight_unit', 'description', 'owner', 'comments', 'tags',
  334. )
  335. def __init__(self, data=None, *args, **kwargs):
  336. super().__init__(data, *args, **kwargs)
  337. if data:
  338. # Limit location queryset by assigned site
  339. params = self.get_related_filter('site', 'site', data.get('site'))
  340. self.fields['location'].queryset = self.fields['location'].queryset.filter(**params)
  341. def clean(self):
  342. super().clean()
  343. # width & u_height must be set if not specifying a rack type on import
  344. if not self.instance.pk:
  345. if not self.cleaned_data.get('rack_type') and not self.cleaned_data.get('width'):
  346. raise forms.ValidationError(_("Width must be set if not specifying a rack type."))
  347. if not self.cleaned_data.get('rack_type') and not self.cleaned_data.get('u_height'):
  348. raise forms.ValidationError(_("U height must be set if not specifying a rack type."))
  349. class RackReservationImportForm(PrimaryModelImportForm):
  350. site = CSVModelChoiceField(
  351. label=_('Site'),
  352. queryset=Site.objects.all(),
  353. to_field_name='name',
  354. help_text=_('Parent site')
  355. )
  356. location = CSVModelChoiceField(
  357. label=_('Location'),
  358. queryset=Location.objects.all(),
  359. to_field_name='name',
  360. required=False,
  361. help_text=_("Rack's location (if any)")
  362. )
  363. rack = CSVModelChoiceField(
  364. label=_('Rack'),
  365. queryset=Rack.objects.all(),
  366. to_field_name='name',
  367. help_text=_('Rack')
  368. )
  369. units = SimpleArrayField(
  370. label=_('Units'),
  371. base_field=forms.IntegerField(),
  372. required=True,
  373. help_text=_('Comma-separated list of individual unit numbers')
  374. )
  375. status = CSVChoiceField(
  376. label=_('Status'),
  377. choices=RackReservationStatusChoices,
  378. help_text=_('Operational status')
  379. )
  380. tenant = CSVModelChoiceField(
  381. label=_('Tenant'),
  382. queryset=Tenant.objects.all(),
  383. required=False,
  384. to_field_name='name',
  385. help_text=_('Assigned tenant')
  386. )
  387. class Meta:
  388. model = RackReservation
  389. fields = ('site', 'location', 'rack', 'units', 'status', 'tenant', 'description', 'owner', 'comments', 'tags')
  390. def __init__(self, data=None, *args, **kwargs):
  391. super().__init__(data, *args, **kwargs)
  392. if data:
  393. # Limit location queryset by assigned site
  394. params = self.get_related_filter('site', 'site', data.get('site'))
  395. self.fields['location'].queryset = self.fields['location'].queryset.filter(**params)
  396. # Limit rack queryset by assigned site and group
  397. params = {
  398. **self.get_related_filter('site', 'site', data.get('site')),
  399. **self.get_related_filter('location', 'location', data.get('location')),
  400. }
  401. self.fields['rack'].queryset = self.fields['rack'].queryset.filter(**params)
  402. class ManufacturerImportForm(OrganizationalModelImportForm):
  403. class Meta:
  404. model = Manufacturer
  405. fields = ('name', 'slug', 'description', 'owner', 'comments', 'tags')
  406. class DeviceTypeImportForm(PrimaryModelImportForm):
  407. manufacturer = CSVModelChoiceField(
  408. label=_('Manufacturer'),
  409. queryset=Manufacturer.objects.all(),
  410. to_field_name='name',
  411. help_text=_('The manufacturer which produces this device type')
  412. )
  413. default_platform = CSVModelChoiceField(
  414. label=_('Default platform'),
  415. queryset=Platform.objects.all(),
  416. to_field_name='name',
  417. required=False,
  418. help_text=_('The default platform for devices of this type (optional)')
  419. )
  420. weight = forms.DecimalField(
  421. label=_('Weight'),
  422. required=False,
  423. help_text=_('Device weight'),
  424. )
  425. weight_unit = CSVChoiceField(
  426. label=_('Weight unit'),
  427. choices=WeightUnitChoices,
  428. required=False,
  429. help_text=_('Unit for device weight')
  430. )
  431. class Meta:
  432. model = DeviceType
  433. fields = [
  434. 'manufacturer', 'default_platform', 'model', 'slug', 'part_number', 'u_height', 'exclude_from_utilization',
  435. 'is_full_depth', 'subdevice_role', 'airflow', 'cooling_method', 'description', 'weight', 'weight_unit',
  436. 'end_of_life', 'owner', 'comments', 'tags',
  437. ]
  438. class ModuleBayTypeImportForm(PrimaryModelImportForm):
  439. manufacturer = CSVModelChoiceField(
  440. label=_('Manufacturer'),
  441. queryset=Manufacturer.objects.all(),
  442. to_field_name='name',
  443. required=False,
  444. )
  445. class Meta:
  446. model = ModuleBayType
  447. fields = [
  448. 'name', 'slug', 'manufacturer', 'color', 'description', 'owner', 'comments', 'tags',
  449. ]
  450. class ModuleTypeProfileImportForm(PrimaryModelImportForm):
  451. class Meta:
  452. model = ModuleTypeProfile
  453. fields = [
  454. 'name', 'description', 'schema', 'owner', 'comments', 'tags',
  455. ]
  456. class ModuleTypeImportForm(PrimaryModelImportForm):
  457. module_bay_types = CSVModelMultipleChoiceField(
  458. label=_('Module bay types'),
  459. queryset=ModuleBayType.objects.all(),
  460. to_field_name='name',
  461. required=False,
  462. )
  463. profile = forms.ModelChoiceField(
  464. label=_('Profile'),
  465. queryset=ModuleTypeProfile.objects.all(),
  466. to_field_name='name',
  467. required=False
  468. )
  469. manufacturer = forms.ModelChoiceField(
  470. label=_('Manufacturer'),
  471. queryset=Manufacturer.objects.all(),
  472. to_field_name='name'
  473. )
  474. airflow = CSVChoiceField(
  475. label=_('Airflow'),
  476. choices=ModuleAirflowChoices,
  477. required=False,
  478. help_text=_('Airflow direction')
  479. )
  480. cooling_method = CSVChoiceField(
  481. label=_('Cooling method'),
  482. choices=CoolingMethodChoices,
  483. required=False,
  484. help_text=_('Cooling method')
  485. )
  486. weight = forms.DecimalField(
  487. label=_('Weight'),
  488. required=False,
  489. help_text=_('Module weight'),
  490. )
  491. weight_unit = CSVChoiceField(
  492. label=_('Weight unit'),
  493. choices=WeightUnitChoices,
  494. required=False,
  495. help_text=_('Unit for module weight')
  496. )
  497. attribute_data = forms.JSONField(
  498. label=_('Attributes'),
  499. required=False,
  500. help_text=_('Attribute values for the assigned profile, passed as a dictionary')
  501. )
  502. class Meta:
  503. model = ModuleType
  504. fields = [
  505. 'manufacturer', 'model', 'part_number', 'description', 'cooling_method', 'airflow', 'weight', 'weight_unit',
  506. 'end_of_life', 'profile', 'attribute_data', 'module_bay_types', 'owner', 'comments', 'tags',
  507. ]
  508. def clean(self):
  509. super().clean()
  510. # Attribute data may be included only if a profile is specified
  511. if self.cleaned_data.get('attribute_data') and not self.cleaned_data.get('profile'):
  512. raise forms.ValidationError(_("Profile must be specified if attribute data is provided."))
  513. # Default attribute_data to an empty dictionary if a profile is specified (to enforce schema validation)
  514. if self.cleaned_data.get('profile') and not self.cleaned_data.get('attribute_data'):
  515. self.cleaned_data['attribute_data'] = {}
  516. module_bay_types = self.cleaned_data.get('module_bay_types')
  517. manufacturer = self.cleaned_data.get('manufacturer')
  518. # If importing an update to an existing module type and the manufacturer is not in
  519. # the import data, use the existing manufacturer.
  520. if manufacturer is None and self.instance.pk:
  521. manufacturer = self.instance.manufacturer
  522. if not module_bay_types or manufacturer is None:
  523. return
  524. # Match the module's manufacturer or a global bay type, preferring the former
  525. # when a name is shared, as with module bay template imports.
  526. by_name = {}
  527. for module_bay_type in module_bay_types:
  528. if module_bay_type.manufacturer_id not in (None, manufacturer.pk):
  529. continue
  530. existing = by_name.get(module_bay_type.name)
  531. if existing is None or module_bay_type.manufacturer_id is not None:
  532. by_name[module_bay_type.name] = module_bay_type
  533. # A name matching only some other manufacturer's bay type is rejected rather than
  534. # resolved to it.
  535. for module_bay_type in module_bay_types:
  536. if module_bay_type.name not in by_name:
  537. raise forms.ValidationError({
  538. 'module_bay_types': forms.ValidationError(
  539. self.fields['module_bay_types'].error_messages['invalid_choice'],
  540. code='invalid_choice',
  541. params={'value': module_bay_type.name},
  542. )
  543. })
  544. self.cleaned_data['module_bay_types'] = list(by_name.values())
  545. class DeviceRoleImportForm(NestedGroupModelImportForm):
  546. parent = CSVModelChoiceField(
  547. label=_('Parent'),
  548. queryset=DeviceRole.objects.all(),
  549. required=False,
  550. to_field_name='name',
  551. help_text=_('Parent Device Role'),
  552. error_messages={
  553. 'invalid_choice': _('Device role not found.'),
  554. }
  555. )
  556. config_template = CSVModelChoiceField(
  557. label=_('Config template'),
  558. queryset=ConfigTemplate.objects.all(),
  559. to_field_name='name',
  560. required=False,
  561. help_text=_('Config template')
  562. )
  563. class Meta:
  564. model = DeviceRole
  565. fields = (
  566. 'name', 'slug', 'parent', 'color', 'vm_role', 'config_template', 'description', 'owner', 'comments', 'tags'
  567. )
  568. class PlatformImportForm(NestedGroupModelImportForm):
  569. parent = CSVModelChoiceField(
  570. label=_('Parent'),
  571. queryset=Platform.objects.all(),
  572. required=False,
  573. to_field_name='name',
  574. help_text=_('Parent platform'),
  575. error_messages={
  576. 'invalid_choice': _('Platform not found.'),
  577. }
  578. )
  579. manufacturer = CSVModelChoiceField(
  580. label=_('Manufacturer'),
  581. queryset=Manufacturer.objects.all(),
  582. required=False,
  583. to_field_name='name',
  584. help_text=_('Limit platform assignments to this manufacturer')
  585. )
  586. config_template = CSVModelChoiceField(
  587. label=_('Config template'),
  588. queryset=ConfigTemplate.objects.all(),
  589. to_field_name='name',
  590. required=False,
  591. help_text=_('Config template')
  592. )
  593. class Meta:
  594. model = Platform
  595. fields = (
  596. 'name', 'slug', 'parent', 'manufacturer', 'config_template', 'description', 'owner', 'comments', 'tags',
  597. )
  598. class BaseDeviceImportForm(PrimaryModelImportForm):
  599. role = CSVModelChoiceField(
  600. label=_('Device role'),
  601. queryset=DeviceRole.objects.all(),
  602. to_field_name='name',
  603. help_text=_('Assigned role')
  604. )
  605. tenant = CSVModelChoiceField(
  606. label=_('Tenant'),
  607. queryset=Tenant.objects.all(),
  608. required=False,
  609. to_field_name='name',
  610. help_text=_('Assigned tenant')
  611. )
  612. manufacturer = CSVModelChoiceField(
  613. label=_('Manufacturer'),
  614. queryset=Manufacturer.objects.all(),
  615. to_field_name='name',
  616. help_text=_('Device type manufacturer')
  617. )
  618. device_type = CSVModelChoiceField(
  619. label=_('Device type'),
  620. queryset=DeviceType.objects.all(),
  621. to_field_name='model',
  622. help_text=_('Device type model')
  623. )
  624. platform = CSVModelChoiceField(
  625. label=_('Platform'),
  626. queryset=Platform.objects.all(),
  627. required=False,
  628. to_field_name='name',
  629. help_text=_('Assigned platform')
  630. )
  631. status = CSVChoiceField(
  632. label=_('Status'),
  633. choices=DeviceStatusChoices,
  634. help_text=_('Operational status')
  635. )
  636. virtual_chassis = CSVModelChoiceField(
  637. label=_('Virtual chassis'),
  638. queryset=VirtualChassis.objects.all(),
  639. to_field_name='name',
  640. required=False,
  641. help_text=_('Virtual chassis')
  642. )
  643. cluster = CSVModelChoiceField(
  644. label=_('Cluster'),
  645. queryset=Cluster.objects.all(),
  646. to_field_name='name',
  647. required=False,
  648. help_text=_('Virtualization cluster')
  649. )
  650. class Meta:
  651. fields = []
  652. model = Device
  653. def __init__(self, data=None, *args, **kwargs):
  654. super().__init__(data, *args, **kwargs)
  655. if data:
  656. # Limit device type queryset by manufacturer
  657. params = self.get_related_filter('manufacturer', 'manufacturer', data.get('manufacturer'))
  658. self.fields['device_type'].queryset = self.fields['device_type'].queryset.filter(**params)
  659. class DeviceImportForm(BaseDeviceImportForm):
  660. site = CSVModelChoiceField(
  661. label=_('Site'),
  662. queryset=Site.objects.all(),
  663. to_field_name='name',
  664. help_text=_('Assigned site')
  665. )
  666. location = CSVModelChoiceField(
  667. label=_('Location'),
  668. queryset=Location.objects.all(),
  669. to_field_name='name',
  670. required=False,
  671. help_text=_("Assigned location (if any)")
  672. )
  673. rack = CSVModelChoiceField(
  674. label=_('Rack'),
  675. queryset=Rack.objects.all(),
  676. to_field_name='name',
  677. required=False,
  678. help_text=_("Assigned rack (if any)")
  679. )
  680. face = CSVChoiceField(
  681. label=_('Face'),
  682. choices=DeviceFaceChoices,
  683. required=False,
  684. help_text=_('Mounted rack face')
  685. )
  686. parent = CSVModelChoiceField(
  687. label=_('Parent'),
  688. queryset=Device.objects.all(),
  689. to_field_name='name',
  690. required=False,
  691. help_text=_('Parent device (for child devices)')
  692. )
  693. device_bay = CSVModelChoiceField(
  694. label=_('Device bay'),
  695. queryset=DeviceBay.objects.all(),
  696. to_field_name='name',
  697. required=False,
  698. help_text=_('Device bay in which this device is installed (for child devices)')
  699. )
  700. airflow = CSVChoiceField(
  701. label=_('Airflow'),
  702. choices=DeviceAirflowChoices,
  703. required=False,
  704. help_text=_('Airflow direction')
  705. )
  706. cooling_method = CSVChoiceField(
  707. label=_('Cooling method'),
  708. choices=CoolingMethodChoices,
  709. required=False,
  710. help_text=_('Cooling method')
  711. )
  712. config_template = CSVModelChoiceField(
  713. label=_('Config template'),
  714. queryset=ConfigTemplate.objects.all(),
  715. to_field_name='name',
  716. required=False,
  717. help_text=_('Config template')
  718. )
  719. replicate_components = forms.BooleanField(
  720. label=_('Replicate components'),
  721. required=False,
  722. help_text=_('Automatically populate components associated with this device type (enabled by default)')
  723. )
  724. class Meta(BaseDeviceImportForm.Meta):
  725. fields = [
  726. 'name', 'role', 'tenant', 'manufacturer', 'device_type', 'platform', 'serial', 'asset_tag', 'status',
  727. 'site', 'location', 'rack', 'position', 'face', 'latitude', 'longitude', 'parent', 'device_bay', 'airflow',
  728. 'cooling_method', 'virtual_chassis', 'vc_position', 'vc_priority', 'cluster', 'description',
  729. 'config_template', 'owner', 'comments', 'replicate_components', 'tags',
  730. ]
  731. def __init__(self, data=None, *args, **kwargs):
  732. super().__init__(data, *args, **kwargs)
  733. if data:
  734. # Limit location queryset by assigned site
  735. params = self.get_related_filter('site', 'site', data.get('site'))
  736. self.fields['location'].queryset = self.fields['location'].queryset.filter(**params)
  737. self.fields['parent'].queryset = self.fields['parent'].queryset.filter(**params)
  738. # Limit rack queryset by assigned site and location
  739. params = self.get_related_filter('site', 'site', data.get('site'))
  740. if location := data.get('location'):
  741. params.update(self.get_related_filter('location', 'location', location))
  742. self.fields['rack'].queryset = self.fields['rack'].queryset.filter(**params)
  743. # Limit platform queryset by manufacturer
  744. params = self.get_related_filter('manufacturer', 'manufacturer', data.get('manufacturer'))
  745. self.fields['platform'].queryset = self.fields['platform'].queryset.filter(
  746. Q(**params) | Q(manufacturer=None)
  747. )
  748. # Limit device bay queryset by parent device
  749. if parent := data.get('parent'):
  750. params = self.get_related_filter('device', 'parent', parent)
  751. self.fields['device_bay'].queryset = self.fields['device_bay'].queryset.filter(**params)
  752. def clean(self):
  753. super().clean()
  754. # Inherit site and rack from parent device
  755. if parent := self.cleaned_data.get('parent'):
  756. self.instance.site = parent.site
  757. self.instance.rack = parent.rack
  758. # Set parent_bay reverse relationship
  759. if device_bay := self.cleaned_data.get('device_bay'):
  760. self.instance.parent_bay = device_bay
  761. # Disable component replication for a new device if requested
  762. if not self.instance.pk and not self.cleaned_data.get('replicate_components'):
  763. self.instance._disable_replication = True
  764. def clean_replicate_components(self):
  765. # Default to True when replicate_components is omitted or left blank in the uploaded data
  766. if self.data.get('replicate_components') in (None, ''):
  767. return True
  768. return self.cleaned_data['replicate_components']
  769. class ModuleImportForm(ModuleCommonForm, PrimaryModelImportForm):
  770. device = CSVModelChoiceField(
  771. label=_('Device'),
  772. queryset=Device.objects.all(),
  773. to_field_name='name',
  774. help_text=_('The device in which this module is installed')
  775. )
  776. module_bay = CSVModelChoiceField(
  777. label=_('Module bay'),
  778. queryset=ModuleBay.objects.all(),
  779. to_field_name='name',
  780. help_text=_('The module bay in which this module is installed')
  781. )
  782. module_type = CSVModelChoiceField(
  783. label=_('Module type'),
  784. queryset=ModuleType.objects.all(),
  785. to_field_name='model',
  786. help_text=_('The type of module')
  787. )
  788. status = CSVChoiceField(
  789. label=_('Status'),
  790. choices=ModuleStatusChoices,
  791. help_text=_('Operational status')
  792. )
  793. replicate_components = forms.BooleanField(
  794. label=_('Replicate components'),
  795. required=False,
  796. help_text=_('Automatically populate components associated with this module type (enabled by default)')
  797. )
  798. adopt_components = forms.BooleanField(
  799. label=_('Adopt components'),
  800. required=False,
  801. help_text=_('Adopt already existing components')
  802. )
  803. class Meta:
  804. model = Module
  805. fields = (
  806. 'device', 'module_bay', 'module_type', 'serial', 'asset_tag', 'status', 'description', 'owner', 'comments',
  807. 'replicate_components', 'adopt_components', 'tags',
  808. )
  809. def __init__(self, data=None, *args, **kwargs):
  810. super().__init__(data, *args, **kwargs)
  811. if data:
  812. # Limit module_bay queryset by assigned device
  813. params = self.get_related_filter('device', 'device', data.get('device'))
  814. self.fields['module_bay'].queryset = self.fields['module_bay'].queryset.filter(**params)
  815. def clean_replicate_components(self):
  816. # Make sure replicate_components is True when it's not included in the uploaded data
  817. if 'replicate_components' not in self.data:
  818. return True
  819. return self.cleaned_data['replicate_components']
  820. #
  821. # Device components
  822. #
  823. class ConsolePortImportForm(OwnerCSVMixin, NetBoxModelImportForm):
  824. device = CSVModelChoiceField(
  825. label=_('Device'),
  826. queryset=Device.objects.all(),
  827. to_field_name='name'
  828. )
  829. type = CSVChoiceField(
  830. label=_('Type'),
  831. choices=ConsolePortTypeChoices,
  832. required=False,
  833. help_text=_('Port type')
  834. )
  835. speed = CSVTypedChoiceField(
  836. label=_('Speed'),
  837. choices=ConsolePortSpeedChoices,
  838. coerce=int,
  839. empty_value=None,
  840. required=False,
  841. help_text=_('Port speed in bps')
  842. )
  843. class Meta:
  844. model = ConsolePort
  845. fields = ('device', 'name', 'label', 'type', 'speed', 'mark_connected', 'description', 'owner', 'tags')
  846. class ConsoleServerPortImportForm(OwnerCSVMixin, NetBoxModelImportForm):
  847. device = CSVModelChoiceField(
  848. label=_('Device'),
  849. queryset=Device.objects.all(),
  850. to_field_name='name'
  851. )
  852. type = CSVChoiceField(
  853. label=_('Type'),
  854. choices=ConsolePortTypeChoices,
  855. required=False,
  856. help_text=_('Port type')
  857. )
  858. speed = CSVTypedChoiceField(
  859. label=_('Speed'),
  860. choices=ConsolePortSpeedChoices,
  861. coerce=int,
  862. empty_value=None,
  863. required=False,
  864. help_text=_('Port speed in bps')
  865. )
  866. class Meta:
  867. model = ConsoleServerPort
  868. fields = ('device', 'name', 'label', 'type', 'speed', 'mark_connected', 'description', 'owner', 'tags')
  869. class PowerPortImportForm(OwnerCSVMixin, NetBoxModelImportForm):
  870. device = CSVModelChoiceField(
  871. label=_('Device'),
  872. queryset=Device.objects.all(),
  873. to_field_name='name'
  874. )
  875. type = CSVChoiceField(
  876. label=_('Type'),
  877. choices=PowerPortTypeChoices,
  878. required=False,
  879. help_text=_('Port type')
  880. )
  881. class Meta:
  882. model = PowerPort
  883. fields = (
  884. 'device', 'name', 'label', 'type', 'mark_connected', 'maximum_draw', 'allocated_draw', 'description',
  885. 'owner', 'tags',
  886. )
  887. class PowerOutletImportForm(OwnerCSVMixin, NetBoxModelImportForm):
  888. device = CSVModelChoiceField(
  889. label=_('Device'),
  890. queryset=Device.objects.all(),
  891. to_field_name='name'
  892. )
  893. type = CSVChoiceField(
  894. label=_('Type'),
  895. choices=PowerOutletTypeChoices,
  896. required=False,
  897. help_text=_('Outlet type')
  898. )
  899. power_port = CSVModelChoiceField(
  900. label=_('Power port'),
  901. queryset=PowerPort.objects.all(),
  902. required=False,
  903. to_field_name='name',
  904. help_text=_('Local power port which feeds this outlet')
  905. )
  906. feed_leg = CSVChoiceField(
  907. label=_('Feed leg'),
  908. choices=PowerOutletFeedLegChoices,
  909. required=False,
  910. help_text=_('Electrical phase (for three-phase circuits)')
  911. )
  912. class Meta:
  913. model = PowerOutlet
  914. fields = (
  915. 'device', 'name', 'label', 'type', 'color', 'mark_connected', 'power_port', 'feed_leg', 'description',
  916. 'owner', 'tags',
  917. )
  918. def __init__(self, *args, **kwargs):
  919. super().__init__(*args, **kwargs)
  920. # Limit PowerPort choices to those belonging to this device (or VC master)
  921. if self.is_bound and 'device' in self.data:
  922. try:
  923. device = self.fields['device'].to_python(self.data['device'])
  924. except forms.ValidationError:
  925. device = None
  926. else:
  927. try:
  928. device = self.instance.device
  929. except Device.DoesNotExist:
  930. device = None
  931. if device:
  932. self.fields['power_port'].queryset = PowerPort.objects.filter(
  933. device__in=[device, device.get_vc_master()]
  934. )
  935. else:
  936. self.fields['power_port'].queryset = PowerPort.objects.none()
  937. class CoolingIntakeImportForm(OwnerCSVMixin, NetBoxModelImportForm):
  938. device = CSVModelChoiceField(
  939. label=_('Device'),
  940. queryset=Device.objects.all(),
  941. to_field_name='name'
  942. )
  943. type = CSVChoiceField(
  944. label=_('Type'),
  945. choices=CoolingConnectorTypeChoices,
  946. required=False,
  947. help_text=_('Physical connector type')
  948. )
  949. diameter_unit = CSVChoiceField(
  950. label=_('Diameter unit'),
  951. choices=DiameterUnitChoices,
  952. required=False,
  953. help_text=_('Diameter unit')
  954. )
  955. max_flow_unit = CSVChoiceField(
  956. label=_('Max flow unit'),
  957. choices=FlowRateUnitChoices,
  958. required=False,
  959. help_text=_('Unit for maximum flow')
  960. )
  961. cooling_outflow_device = CSVModelChoiceField(
  962. label=_('Cooling outflow device'),
  963. queryset=Device.objects.all(),
  964. required=False,
  965. to_field_name='name',
  966. help_text=_('Device bearing the upstream cooling outflow (defaults to this intake\'s device)')
  967. )
  968. cooling_outflow = CSVModelChoiceField(
  969. label=_('Cooling outflow'),
  970. queryset=CoolingOutflow.objects.all(),
  971. required=False,
  972. to_field_name='name',
  973. help_text=_('Upstream cooling outflow which feeds this intake')
  974. )
  975. class Meta:
  976. model = CoolingIntake
  977. fields = (
  978. 'device', 'name', 'label', 'type', 'diameter', 'diameter_unit', 'max_flow',
  979. 'max_flow_unit', 'cooling_outflow_device', 'cooling_outflow', 'description', 'owner', 'tags',
  980. )
  981. def __init__(self, *args, **kwargs):
  982. super().__init__(*args, **kwargs)
  983. # The supplying outflow typically belongs to an upstream device (e.g. a CDU or manifold), so scope the
  984. # CoolingOutflow choices to cooling_outflow_device where given, falling back to this intake's own device.
  985. if self.is_bound and 'device' in self.data:
  986. try:
  987. device = self.fields['device'].to_python(self.data['device'])
  988. except forms.ValidationError:
  989. device = None
  990. else:
  991. try:
  992. device = self.instance.device
  993. except Device.DoesNotExist:
  994. device = None
  995. outflow_device = None
  996. if self.is_bound and self.data.get('cooling_outflow_device'):
  997. try:
  998. outflow_device = self.fields['cooling_outflow_device'].to_python(
  999. self.data['cooling_outflow_device']
  1000. )
  1001. except forms.ValidationError:
  1002. outflow_device = None
  1003. if outflow_device:
  1004. self.fields['cooling_outflow'].queryset = CoolingOutflow.objects.filter(device=outflow_device)
  1005. elif device:
  1006. self.fields['cooling_outflow'].queryset = CoolingOutflow.objects.filter(
  1007. device__in=[device, device.get_vc_master()]
  1008. )
  1009. else:
  1010. self.fields['cooling_outflow'].queryset = CoolingOutflow.objects.none()
  1011. class CoolingOutflowImportForm(OwnerCSVMixin, NetBoxModelImportForm):
  1012. device = CSVModelChoiceField(
  1013. label=_('Device'),
  1014. queryset=Device.objects.all(),
  1015. to_field_name='name'
  1016. )
  1017. type = CSVChoiceField(
  1018. label=_('Type'),
  1019. choices=CoolingConnectorTypeChoices,
  1020. required=False,
  1021. help_text=_('Physical connector type')
  1022. )
  1023. diameter_unit = CSVChoiceField(
  1024. label=_('Diameter unit'),
  1025. choices=DiameterUnitChoices,
  1026. required=False,
  1027. help_text=_('Diameter unit')
  1028. )
  1029. cooling_intake = CSVModelChoiceField(
  1030. label=_('Cooling intake'),
  1031. queryset=CoolingIntake.objects.all(),
  1032. required=False,
  1033. to_field_name='name',
  1034. help_text=_('Local cooling intake which feeds this outflow')
  1035. )
  1036. class Meta:
  1037. model = CoolingOutflow
  1038. fields = (
  1039. 'device', 'name', 'label', 'type', 'diameter', 'diameter_unit',
  1040. 'cooling_intake', 'description', 'owner', 'tags',
  1041. )
  1042. def __init__(self, *args, **kwargs):
  1043. super().__init__(*args, **kwargs)
  1044. # Limit CoolingIntake choices to those belonging to this device (or VC master)
  1045. if self.is_bound and 'device' in self.data:
  1046. try:
  1047. device = self.fields['device'].to_python(self.data['device'])
  1048. except forms.ValidationError:
  1049. device = None
  1050. else:
  1051. try:
  1052. device = self.instance.device
  1053. except Device.DoesNotExist:
  1054. device = None
  1055. if device:
  1056. self.fields['cooling_intake'].queryset = CoolingIntake.objects.filter(
  1057. device__in=[device, device.get_vc_master()]
  1058. )
  1059. else:
  1060. self.fields['cooling_intake'].queryset = CoolingIntake.objects.none()
  1061. class InterfaceImportForm(OwnerCSVMixin, NetBoxModelImportForm):
  1062. device = CSVModelChoiceField(
  1063. label=_('Device'),
  1064. queryset=Device.objects.all(),
  1065. to_field_name='name'
  1066. )
  1067. parent = CSVModelChoiceField(
  1068. label=_('Parent'),
  1069. queryset=Interface.objects.all(),
  1070. required=False,
  1071. to_field_name='name',
  1072. help_text=_('Parent interface')
  1073. )
  1074. bridge = CSVModelChoiceField(
  1075. label=_('Bridge'),
  1076. queryset=Interface.objects.all(),
  1077. required=False,
  1078. to_field_name='name',
  1079. help_text=_('Bridged interface')
  1080. )
  1081. lag = CSVModelChoiceField(
  1082. label=_('Lag'),
  1083. queryset=Interface.objects.all(),
  1084. required=False,
  1085. to_field_name='name',
  1086. help_text=_('Parent LAG interface')
  1087. )
  1088. vdcs = CSVModelMultipleChoiceField(
  1089. label=_('Vdcs'),
  1090. queryset=VirtualDeviceContext.objects.all(),
  1091. required=False,
  1092. to_field_name='name',
  1093. help_text=mark_safe(
  1094. _('VDC names separated by commas, encased with double quotes. Example:') + ' <code>"vdc1,vdc2,vdc3"</code>'
  1095. )
  1096. )
  1097. type = CSVChoiceField(
  1098. label=_('Type'),
  1099. choices=InterfaceTypeChoices,
  1100. help_text=_('Physical medium')
  1101. )
  1102. duplex = CSVChoiceField(
  1103. label=_('Duplex'),
  1104. choices=InterfaceDuplexChoices,
  1105. required=False
  1106. )
  1107. poe_mode = CSVChoiceField(
  1108. label=_('Poe mode'),
  1109. choices=InterfacePoEModeChoices,
  1110. required=False,
  1111. help_text=_('PoE mode')
  1112. )
  1113. poe_type = CSVChoiceField(
  1114. label=_('Poe type'),
  1115. choices=InterfacePoETypeChoices,
  1116. required=False,
  1117. help_text=_('PoE type')
  1118. )
  1119. lag_mode = CSVChoiceField(
  1120. label=_('LAG mode'),
  1121. choices=InterfaceLAGModeChoices,
  1122. required=False,
  1123. help_text=_('LAG mode')
  1124. )
  1125. lag_hash_policy = CSVChoiceField(
  1126. label=_('LAG hash policy'),
  1127. choices=InterfaceLAGHashPolicyChoices,
  1128. required=False,
  1129. help_text=_('LAG hash policy')
  1130. )
  1131. mode = CSVChoiceField(
  1132. label=_('Mode'),
  1133. choices=InterfaceModeChoices,
  1134. required=False,
  1135. help_text=_('IEEE 802.1Q operational mode (for L2 interfaces)'),
  1136. )
  1137. vlan_group = CSVModelChoiceField(
  1138. label=_('VLAN group'),
  1139. queryset=VLANGroup.objects.all(),
  1140. required=False,
  1141. to_field_name='name',
  1142. help_text=_('Filter VLANs available for assignment by group'),
  1143. )
  1144. untagged_vlan = CSVModelChoiceField(
  1145. label=_('Untagged VLAN'),
  1146. queryset=VLAN.objects.all(),
  1147. required=False,
  1148. to_field_name='vid',
  1149. help_text=_('Assigned untagged VLAN ID (filtered by VLAN group)'),
  1150. )
  1151. tagged_vlans = CSVModelMultipleChoiceField(
  1152. label=_('Tagged VLANs'),
  1153. queryset=VLAN.objects.all(),
  1154. required=False,
  1155. to_field_name='vid',
  1156. help_text=mark_safe(
  1157. _(
  1158. 'Assigned tagged VLAN IDs separated by commas, encased with double quotes '
  1159. '(filtered by VLAN group). Example:'
  1160. )
  1161. + ' <code>"100,200,300"</code>'
  1162. ),
  1163. )
  1164. qinq_svlan = CSVModelChoiceField(
  1165. label=_('Q-in-Q Service VLAN'),
  1166. queryset=VLAN.objects.filter(qinq_role=VLANQinQRoleChoices.ROLE_SERVICE),
  1167. required=False,
  1168. to_field_name='vid',
  1169. help_text=_('Assigned Q-in-Q Service VLAN ID (filtered by VLAN group)'),
  1170. )
  1171. vrf = CSVModelChoiceField(
  1172. label=_('VRF'),
  1173. queryset=VRF.objects.all(),
  1174. required=False,
  1175. to_field_name='rd',
  1176. help_text=_('Assigned VRF')
  1177. )
  1178. rf_role = CSVChoiceField(
  1179. label=_('Rf role'),
  1180. choices=WirelessRoleChoices,
  1181. required=False,
  1182. help_text=_('Wireless role (AP/station)')
  1183. )
  1184. class Meta:
  1185. model = Interface
  1186. fields = (
  1187. 'device', 'name', 'label', 'parent', 'bridge', 'lag', 'type', 'channels', 'channel_id', 'speed', 'duplex',
  1188. 'enabled', 'mark_connected', 'wwn', 'vdcs', 'mtu', 'mgmt_only', 'description', 'poe_mode', 'poe_type',
  1189. 'lag_mode', 'lag_hash_policy', 'mode', 'vlan_group', 'untagged_vlan', 'tagged_vlans', 'qinq_svlan', 'vrf',
  1190. 'rf_role', 'rf_channel', 'rf_channel_frequency', 'rf_channel_width', 'tx_power', 'owner', 'tags'
  1191. )
  1192. def __init__(self, data=None, *args, **kwargs):
  1193. super().__init__(data, *args, **kwargs)
  1194. if data:
  1195. # Limit choices for parent, bridge, and LAG interfaces to the assigned device
  1196. if device := data.get('device'):
  1197. params = self.get_related_filter('device', 'device', device)
  1198. self.fields['parent'].queryset = self.fields['parent'].queryset.filter(**params)
  1199. self.fields['bridge'].queryset = self.fields['bridge'].queryset.filter(**params)
  1200. self.fields['lag'].queryset = self.fields['lag'].queryset.filter(**params)
  1201. self.fields['vdcs'].queryset = self.fields['vdcs'].queryset.filter(**params)
  1202. # Limit choices for VLANs to the assigned VLAN group
  1203. if vlan_group := data.get('vlan_group'):
  1204. params = self.get_related_filter('group', 'vlan_group', vlan_group)
  1205. self.fields['untagged_vlan'].queryset = self.fields['untagged_vlan'].queryset.filter(**params)
  1206. self.fields['tagged_vlans'].queryset = self.fields['tagged_vlans'].queryset.filter(**params)
  1207. self.fields['qinq_svlan'].queryset = self.fields['qinq_svlan'].queryset.filter(**params)
  1208. def clean_enabled(self):
  1209. # Make sure enabled is True when it's not included in the uploaded data
  1210. if 'enabled' not in self.data:
  1211. return True
  1212. return self.cleaned_data['enabled']
  1213. def clean_vdcs(self):
  1214. for vdc in self.cleaned_data['vdcs']:
  1215. if vdc.device != self.cleaned_data['device']:
  1216. raise forms.ValidationError(
  1217. _("VDC {vdc} is not assigned to device {device}").format(
  1218. vdc=vdc, device=self.cleaned_data['device']
  1219. )
  1220. )
  1221. return self.cleaned_data['vdcs']
  1222. class FrontPortImportForm(OwnerCSVMixin, NetBoxModelImportForm):
  1223. device = CSVModelChoiceField(
  1224. label=_('Device'),
  1225. queryset=Device.objects.all(),
  1226. to_field_name='name'
  1227. )
  1228. type = CSVChoiceField(
  1229. label=_('Type'),
  1230. choices=PortTypeChoices,
  1231. help_text=_('Physical medium classification')
  1232. )
  1233. rear_port = CSVModelChoiceField(
  1234. label=_('Rear port'),
  1235. queryset=RearPort.objects.all(),
  1236. to_field_name='name',
  1237. help_text=_('Corresponding rear port (mapped to the front port\'s first position)')
  1238. )
  1239. rear_port_position = forms.IntegerField(
  1240. label=_('Rear port position'),
  1241. required=False,
  1242. help_text=_('Mapped position on the corresponding rear port (defaults to 1)')
  1243. )
  1244. class Meta:
  1245. model = FrontPort
  1246. fields = (
  1247. 'device', 'name', 'label', 'type', 'color', 'mark_connected', 'positions', 'rear_port',
  1248. 'rear_port_position', 'description', 'owner', 'tags'
  1249. )
  1250. def __init__(self, *args, **kwargs):
  1251. super().__init__(*args, **kwargs)
  1252. # Limit RearPort choices to those belonging to this device (or VC master)
  1253. if self.is_bound and 'device' in self.data:
  1254. try:
  1255. device = self.fields['device'].to_python(self.data['device'])
  1256. except forms.ValidationError:
  1257. device = None
  1258. else:
  1259. try:
  1260. device = self.instance.device
  1261. except Device.DoesNotExist:
  1262. device = None
  1263. if device:
  1264. self.fields['rear_port'].queryset = RearPort.objects.filter(
  1265. device__in=[device, device.get_vc_master()]
  1266. )
  1267. else:
  1268. self.fields['rear_port'].queryset = RearPort.objects.none()
  1269. def clean(self):
  1270. super().clean()
  1271. rear_port = self.cleaned_data.get('rear_port')
  1272. rear_port_position = self.cleaned_data.get('rear_port_position') or 1
  1273. if not rear_port:
  1274. return
  1275. # Validate the rear port position against the selected rear port
  1276. if rear_port_position > rear_port.positions:
  1277. raise forms.ValidationError({
  1278. 'rear_port_position': _(
  1279. "Invalid rear port position ({rear_port_position}): Rear port {name} has only {positions} "
  1280. "positions."
  1281. ).format(
  1282. rear_port_position=rear_port_position,
  1283. name=rear_port.name,
  1284. positions=rear_port.positions
  1285. )
  1286. })
  1287. # Ensure the target rear port position isn't already occupied. reconcile_port_mappings() creates the
  1288. # mapping via create() (bypassing validate_unique()), so without this check a collision would surface
  1289. # as an uncaught IntegrityError (HTTP 500) rather than a row-level validation error.
  1290. occupied = PortMapping.objects.filter(
  1291. rear_port=rear_port, rear_port_position=rear_port_position
  1292. ).exclude(front_port=self.instance.pk)
  1293. if occupied.exists():
  1294. raise forms.ValidationError({
  1295. 'rear_port_position': _(
  1296. "Rear port {name} position {rear_port_position} is already occupied."
  1297. ).format(
  1298. name=rear_port.name,
  1299. rear_port_position=rear_port_position
  1300. )
  1301. })
  1302. def _save_m2m(self):
  1303. super()._save_m2m()
  1304. # Map the front port's first position to the specified rear port & position
  1305. if rear_port := self.cleaned_data.get('rear_port'):
  1306. reconcile_port_mappings(
  1307. PortMapping,
  1308. parent_field='front_port',
  1309. parent=self.instance,
  1310. desired=[{
  1311. 'front_port_position': 1,
  1312. 'rear_port_id': rear_port.pk,
  1313. 'rear_port_position': self.cleaned_data.get('rear_port_position') or 1,
  1314. }],
  1315. )
  1316. class RearPortImportForm(OwnerCSVMixin, NetBoxModelImportForm):
  1317. device = CSVModelChoiceField(
  1318. label=_('Device'),
  1319. queryset=Device.objects.all(),
  1320. to_field_name='name'
  1321. )
  1322. type = CSVChoiceField(
  1323. label=_('Type'),
  1324. help_text=_('Physical medium classification'),
  1325. choices=PortTypeChoices,
  1326. )
  1327. class Meta:
  1328. model = RearPort
  1329. fields = (
  1330. 'device', 'name', 'label', 'type', 'color', 'mark_connected', 'positions', 'description', 'owner', 'tags',
  1331. )
  1332. class ModuleBayImportForm(OwnerCSVMixin, NetBoxModelImportForm):
  1333. device = CSVModelChoiceField(
  1334. label=_('Device'),
  1335. queryset=Device.objects.all(),
  1336. to_field_name='name'
  1337. )
  1338. class Meta:
  1339. model = ModuleBay
  1340. fields = ('device', 'name', 'label', 'position', 'enabled', 'description', 'owner', 'tags')
  1341. def clean_enabled(self):
  1342. # Make sure enabled is True when it's not included in the uploaded data
  1343. if 'enabled' not in self.data:
  1344. return True
  1345. return self.cleaned_data['enabled']
  1346. class DeviceBayImportForm(OwnerCSVMixin, NetBoxModelImportForm):
  1347. device = CSVModelChoiceField(
  1348. label=_('Device'),
  1349. queryset=Device.objects.all(),
  1350. to_field_name='name'
  1351. )
  1352. installed_device = CSVModelChoiceField(
  1353. label=_('Installed device'),
  1354. queryset=Device.objects.all(),
  1355. required=False,
  1356. to_field_name='name',
  1357. help_text=_('Child device installed within this bay'),
  1358. error_messages={
  1359. 'invalid_choice': _('Child device not found.'),
  1360. }
  1361. )
  1362. class Meta:
  1363. model = DeviceBay
  1364. fields = ('device', 'name', 'label', 'enabled', 'installed_device', 'description', 'owner', 'tags')
  1365. def __init__(self, *args, **kwargs):
  1366. super().__init__(*args, **kwargs)
  1367. # Limit installed device choices to devices of the correct type and location
  1368. if self.is_bound and 'device' in self.data:
  1369. try:
  1370. device = self.fields['device'].to_python(self.data['device'])
  1371. except forms.ValidationError:
  1372. device = None
  1373. else:
  1374. try:
  1375. device = self.instance.device
  1376. except Device.DoesNotExist:
  1377. device = None
  1378. if device:
  1379. self.fields['installed_device'].queryset = Device.objects.filter(
  1380. site=device.site,
  1381. rack=device.rack,
  1382. parent_bay__isnull=True,
  1383. device_type__u_height=0,
  1384. device_type__subdevice_role=SubdeviceRoleChoices.ROLE_CHILD
  1385. ).exclude(pk=device.pk)
  1386. else:
  1387. self.fields['installed_device'].queryset = Device.objects.none()
  1388. def clean_enabled(self):
  1389. # Make sure enabled is True when it's not included in the uploaded data
  1390. if 'enabled' not in self.data:
  1391. return True
  1392. return self.cleaned_data['enabled']
  1393. class InventoryItemImportForm(OwnerCSVMixin, NetBoxModelImportForm):
  1394. device = CSVModelChoiceField(
  1395. label=_('Device'),
  1396. queryset=Device.objects.all(),
  1397. to_field_name='name'
  1398. )
  1399. role = CSVModelChoiceField(
  1400. label=_('Role'),
  1401. queryset=InventoryItemRole.objects.all(),
  1402. to_field_name='name',
  1403. required=False
  1404. )
  1405. manufacturer = CSVModelChoiceField(
  1406. label=_('Manufacturer'),
  1407. queryset=Manufacturer.objects.all(),
  1408. to_field_name='name',
  1409. required=False
  1410. )
  1411. parent = CSVModelChoiceField(
  1412. label=_('Parent'),
  1413. queryset=Device.objects.all(),
  1414. to_field_name='name',
  1415. required=False,
  1416. help_text=_('Parent inventory item')
  1417. )
  1418. component_type = CSVContentTypeField(
  1419. label=_('Component type'),
  1420. queryset=ContentType.objects.all(),
  1421. limit_choices_to=MODULAR_COMPONENT_MODELS,
  1422. required=False,
  1423. help_text=_('Component Type')
  1424. )
  1425. component_name = forms.CharField(
  1426. label=_('Component name'),
  1427. required=False,
  1428. help_text=_('Component Name')
  1429. )
  1430. status = CSVChoiceField(
  1431. label=_('Status'),
  1432. choices=InventoryItemStatusChoices,
  1433. help_text=_('Operational status')
  1434. )
  1435. class Meta:
  1436. model = InventoryItem
  1437. fields = (
  1438. 'device', 'name', 'label', 'status', 'role', 'manufacturer', 'parent', 'part_id', 'serial', 'asset_tag',
  1439. 'discovered', 'description', 'owner', 'tags', 'component_type', 'component_name',
  1440. )
  1441. def __init__(self, *args, **kwargs):
  1442. super().__init__(*args, **kwargs)
  1443. # Limit parent choices to inventory items belonging to this device
  1444. device = None
  1445. if self.is_bound and 'device' in self.data:
  1446. try:
  1447. device = self.fields['device'].to_python(self.data['device'])
  1448. except forms.ValidationError:
  1449. pass
  1450. if device:
  1451. self.fields['parent'].queryset = InventoryItem.objects.filter(device=device)
  1452. else:
  1453. self.fields['parent'].queryset = InventoryItem.objects.none()
  1454. def clean(self):
  1455. super().clean()
  1456. cleaned_data = self.cleaned_data
  1457. component_type = cleaned_data.get('component_type')
  1458. component_name = cleaned_data.get('component_name')
  1459. device = self.cleaned_data.get("device")
  1460. if component_type:
  1461. if device is None:
  1462. cleaned_data.pop('component_type', None)
  1463. if component_name is None:
  1464. cleaned_data.pop('component_type', None)
  1465. raise forms.ValidationError(
  1466. _("Component name must be specified when component type is specified")
  1467. )
  1468. if all([device, component_name]):
  1469. try:
  1470. model = component_type.model_class()
  1471. self.instance.component = model.objects.get(device=device, name=component_name)
  1472. except ObjectDoesNotExist:
  1473. cleaned_data.pop('component_type', None)
  1474. cleaned_data.pop('component_name', None)
  1475. raise forms.ValidationError(
  1476. _("Component not found: {device} - {component_name}").format(
  1477. device=device, component_name=component_name
  1478. )
  1479. )
  1480. else:
  1481. cleaned_data.pop('component_type', None)
  1482. if not component_name:
  1483. raise forms.ValidationError(
  1484. _("Component name must be specified when component type is specified")
  1485. )
  1486. else:
  1487. if component_name:
  1488. raise forms.ValidationError(
  1489. _("Component type must be specified when component name is specified")
  1490. )
  1491. return cleaned_data
  1492. #
  1493. # Device component roles
  1494. #
  1495. class InventoryItemRoleImportForm(OrganizationalModelImportForm):
  1496. slug = SlugField()
  1497. class Meta:
  1498. model = InventoryItemRole
  1499. fields = ('name', 'slug', 'color', 'description', 'owner', 'comments')
  1500. #
  1501. # Addressing
  1502. #
  1503. class MACAddressImportForm(PrimaryModelImportForm):
  1504. device = CSVModelChoiceField(
  1505. label=_('Device'),
  1506. queryset=Device.objects.all(),
  1507. required=False,
  1508. to_field_name='name',
  1509. help_text=_('Parent device of assigned interface (if any)')
  1510. )
  1511. virtual_machine = CSVModelChoiceField(
  1512. label=_('Virtual machine'),
  1513. queryset=VirtualMachine.objects.all(),
  1514. required=False,
  1515. to_field_name='name',
  1516. help_text=_('Parent VM of assigned interface (if any)')
  1517. )
  1518. interface = CSVModelChoiceField(
  1519. label=_('Interface'),
  1520. queryset=Interface.objects.none(), # Can also refer to VMInterface
  1521. required=False,
  1522. to_field_name='name',
  1523. help_text=_('Assigned interface')
  1524. )
  1525. is_primary = forms.BooleanField(
  1526. label=_('Is primary'),
  1527. help_text=_('Make this the primary MAC address for the assigned interface'),
  1528. required=False
  1529. )
  1530. class Meta:
  1531. model = MACAddress
  1532. fields = [
  1533. 'mac_address', 'device', 'virtual_machine', 'interface', 'is_primary', 'description', 'owner', 'comments',
  1534. 'tags',
  1535. ]
  1536. def __init__(self, data=None, *args, **kwargs):
  1537. super().__init__(data, *args, **kwargs)
  1538. if data:
  1539. # Limit interface queryset by assigned device
  1540. if data.get('device'):
  1541. self.fields['interface'].queryset = Interface.objects.filter(
  1542. **self.get_related_filter('device', 'device', data['device'])
  1543. )
  1544. # Limit interface queryset by assigned device
  1545. elif data.get('virtual_machine'):
  1546. self.fields['interface'].queryset = VMInterface.objects.filter(
  1547. **self.get_related_filter('virtual_machine', 'virtual_machine', data['virtual_machine'])
  1548. )
  1549. def clean(self):
  1550. super().clean()
  1551. device = self.cleaned_data.get('device')
  1552. virtual_machine = self.cleaned_data.get('virtual_machine')
  1553. interface = self.cleaned_data.get('interface')
  1554. # Validate interface assignment
  1555. if interface and not device and not virtual_machine:
  1556. raise forms.ValidationError({
  1557. "interface": _("Must specify the parent device or VM when assigning an interface")
  1558. })
  1559. def save(self, *args, **kwargs):
  1560. # Set interface assignment
  1561. if interface := self.cleaned_data.get('interface'):
  1562. self.instance.assigned_object = interface
  1563. instance = super().save(*args, **kwargs)
  1564. # Assign the MAC address as primary for its interface, if designated as such
  1565. if interface and self.cleaned_data['is_primary'] and self.instance.pk:
  1566. interface.snapshot()
  1567. interface.primary_mac_address = self.instance
  1568. interface.save()
  1569. return instance
  1570. class MACBlockImportForm(PrimaryModelImportForm):
  1571. class Meta:
  1572. model = MACBlock
  1573. fields = [
  1574. 'prefix', 'prefix_length', 'name', 'enforce_unique', 'description', 'owner', 'comments', 'tags',
  1575. ]
  1576. #
  1577. # Cables
  1578. #
  1579. class CableBundleImportForm(PrimaryModelImportForm):
  1580. class Meta:
  1581. model = CableBundle
  1582. fields = ('name', 'description', 'owner', 'comments', 'tags')
  1583. class CableImportForm(PrimaryModelImportForm):
  1584. # Cable.clean() reports termination errors (e.g. cable profile violations) against the model's
  1585. # a_terminations/b_terminations attributes, which have no corresponding fields on this form.
  1586. # Map them onto the columns which define each side's terminations.
  1587. TERMINATION_ERROR_FIELDS = {
  1588. 'a_terminations': 'side_a_name',
  1589. 'b_terminations': 'side_b_name',
  1590. }
  1591. # Columns which take effect only by resolving a side's terminations, and are therefore
  1592. # meaningless without that side's name column.
  1593. TERMINATION_DEPENDENT_COLUMNS = ('site', 'device', 'power_panel', 'type')
  1594. # Termination A
  1595. side_a_site = CSVModelChoiceField(
  1596. label=_('Side A site'),
  1597. queryset=Site.objects.all(),
  1598. required=False,
  1599. to_field_name='name',
  1600. help_text=_('Site of parent device A (if any). Restricts the devices & power panels which may be matched.'),
  1601. )
  1602. side_a_device = CSVModelMultipleChoiceField(
  1603. label=_('Side A device'),
  1604. queryset=Device.objects.all(),
  1605. required=False,
  1606. to_field_name='name',
  1607. help_text=format_html_lazy(
  1608. '{} <code>{}</code>',
  1609. _('Device name(s) for device component terminations. Separate multiple values with commas, '
  1610. 'encased with double quotes. Example:'),
  1611. '"device1,device2"'
  1612. )
  1613. )
  1614. side_a_power_panel = CSVModelMultipleChoiceField(
  1615. label=_('Side A power panel'),
  1616. queryset=PowerPanel.objects.all(),
  1617. required=False,
  1618. to_field_name='name',
  1619. help_text=format_html_lazy(
  1620. '{} <code>{}</code>',
  1621. _('Power panel name(s) for power feed terminations. Separate multiple values with commas, '
  1622. 'encased with double quotes. Example:'),
  1623. '"panel1,panel2"'
  1624. )
  1625. )
  1626. side_a_type = CSVContentTypeField(
  1627. label=_('Side A type'),
  1628. queryset=ContentType.objects.all(),
  1629. limit_choices_to=CABLE_TERMINATION_MODELS,
  1630. help_text=_('Termination type')
  1631. )
  1632. side_a_name = forms.CharField(
  1633. label=_('Side A name'),
  1634. help_text=format_html_lazy(
  1635. '{} <code>{}</code>',
  1636. _('Termination name(s). Separate multiple values with commas, encased with double quotes. '
  1637. 'Example:'),
  1638. '"eth0,eth1"'
  1639. )
  1640. )
  1641. # Termination B
  1642. side_b_site = CSVModelChoiceField(
  1643. label=_('Side B site'),
  1644. queryset=Site.objects.all(),
  1645. required=False,
  1646. to_field_name='name',
  1647. help_text=_('Site of parent device B (if any). Restricts the devices & power panels which may be matched.'),
  1648. )
  1649. side_b_device = CSVModelMultipleChoiceField(
  1650. label=_('Side B device'),
  1651. queryset=Device.objects.all(),
  1652. required=False,
  1653. to_field_name='name',
  1654. help_text=format_html_lazy(
  1655. '{} <code>{}</code>',
  1656. _('Device name(s) for device component terminations. Separate multiple values with commas, '
  1657. 'encased with double quotes. Example:'),
  1658. '"device1,device2"'
  1659. )
  1660. )
  1661. side_b_power_panel = CSVModelMultipleChoiceField(
  1662. label=_('Side B power panel'),
  1663. queryset=PowerPanel.objects.all(),
  1664. required=False,
  1665. to_field_name='name',
  1666. help_text=format_html_lazy(
  1667. '{} <code>{}</code>',
  1668. _('Power panel name(s) for power feed terminations. Separate multiple values with commas, '
  1669. 'encased with double quotes. Example:'),
  1670. '"panel1,panel2"'
  1671. )
  1672. )
  1673. side_b_type = CSVContentTypeField(
  1674. label=_('Side B type'),
  1675. queryset=ContentType.objects.all(),
  1676. limit_choices_to=CABLE_TERMINATION_MODELS,
  1677. help_text=_('Termination type')
  1678. )
  1679. side_b_name = forms.CharField(
  1680. label=_('Side B name'),
  1681. help_text=format_html_lazy(
  1682. '{} <code>{}</code>',
  1683. _('Termination name(s). Separate multiple values with commas, encased with double quotes. '
  1684. 'Example:'),
  1685. '"eth0,eth1"'
  1686. )
  1687. )
  1688. # Cable attributes
  1689. status = CSVChoiceField(
  1690. label=_('Status'),
  1691. choices=LinkStatusChoices,
  1692. required=False,
  1693. help_text=_('Connection status')
  1694. )
  1695. profile = CSVChoiceField(
  1696. label=_('Profile'),
  1697. choices=CableProfileChoices,
  1698. required=False,
  1699. help_text=_('Cable connection profile')
  1700. )
  1701. type = CSVChoiceField(
  1702. label=_('Type'),
  1703. choices=CableTypeChoices,
  1704. required=False,
  1705. help_text=_('Physical medium classification')
  1706. )
  1707. tenant = CSVModelChoiceField(
  1708. label=_('Tenant'),
  1709. queryset=Tenant.objects.all(),
  1710. required=False,
  1711. to_field_name='name',
  1712. help_text=_('Assigned tenant')
  1713. )
  1714. bundle = CSVModelChoiceField(
  1715. label=_('Bundle'),
  1716. queryset=CableBundle.objects.all(),
  1717. required=False,
  1718. to_field_name='name',
  1719. help_text=_('Cable bundle name'),
  1720. )
  1721. length_unit = CSVChoiceField(
  1722. label=_('Length unit'),
  1723. choices=CableLengthUnitChoices,
  1724. required=False,
  1725. help_text=_('Length unit')
  1726. )
  1727. color = forms.CharField(
  1728. label=_('Color'),
  1729. required=False,
  1730. max_length=16,
  1731. help_text=_('Color name (e.g. "Red") or hex code (e.g. "f44336")')
  1732. )
  1733. class Meta:
  1734. model = Cable
  1735. fields = [
  1736. 'side_a_site', 'side_a_device', 'side_a_power_panel', 'side_a_type', 'side_a_name',
  1737. 'side_b_site', 'side_b_device', 'side_b_power_panel', 'side_b_type', 'side_b_name',
  1738. 'type', 'status', 'profile', 'tenant', 'bundle', 'label', 'color', 'length', 'length_unit',
  1739. 'description', 'owner', 'comments', 'tags',
  1740. ]
  1741. def __init__(self, data=None, *args, **kwargs):
  1742. super().__init__(data, *args, **kwargs)
  1743. if data:
  1744. # Limit choices for side_a_device to the assigned side_a_site
  1745. if side_a_site := data.get('side_a_site'):
  1746. side_a_parent_params = self.get_related_filter('site', 'side_a_site', side_a_site)
  1747. self.fields['side_a_device'].queryset = self.fields['side_a_device'].queryset.filter(
  1748. **side_a_parent_params
  1749. )
  1750. self.fields['side_a_power_panel'].queryset = self.fields['side_a_power_panel'].queryset.filter(
  1751. **side_a_parent_params
  1752. )
  1753. # Limit choices for side_b_device to the assigned side_b_site
  1754. if side_b_site := data.get('side_b_site'):
  1755. side_b_parent_params = self.get_related_filter('site', 'side_b_site', side_b_site)
  1756. self.fields['side_b_device'].queryset = self.fields['side_b_device'].queryset.filter(
  1757. **side_b_parent_params
  1758. )
  1759. self.fields['side_b_power_panel'].queryset = self.fields['side_b_power_panel'].queryset.filter(
  1760. **side_b_parent_params
  1761. )
  1762. def _update_errors(self, errors):
  1763. # Remap any termination errors raised by Cable.clean() onto the relevant import column.
  1764. # Without this, the base form reports them as prefixed non-field errors, as neither
  1765. # a_terminations nor b_terminations exists as a field on this form. Errors are dispatched
  1766. # per key so that both sides can fall back to a non-field error without colliding.
  1767. if hasattr(errors, 'error_dict'):
  1768. remapped = {}
  1769. for name, error_list in errors.error_dict.items():
  1770. mapped_name = self._map_termination_field(name) or NON_FIELD_ERRORS
  1771. remapped.setdefault(mapped_name, []).extend(error_list)
  1772. errors = forms.ValidationError(remapped)
  1773. super()._update_errors(errors)
  1774. def _map_termination_field(self, field):
  1775. """
  1776. Return the import column against which a model-level termination error should be reported,
  1777. or None (i.e. a non-field error) if that column is not present on the form. Columns absent
  1778. from an update record are removed from the form by BulkImportView, so a cable profile
  1779. violation can be reported against a side whose terminations were not being modified.
  1780. """
  1781. if field not in self.TERMINATION_ERROR_FIELDS:
  1782. return field
  1783. mapped_field = self.TERMINATION_ERROR_FIELDS[field]
  1784. return mapped_field if mapped_field in self.fields else None
  1785. @staticmethod
  1786. def _split_side_values(value):
  1787. """
  1788. Split a side_* cell into an ordered list of values, preserving duplicates and empty
  1789. entries. Accepts a comma-separated string (CSV) or a native list (JSON/YAML).
  1790. """
  1791. if value in (None, ''):
  1792. return []
  1793. if not isinstance(value, (list, tuple)):
  1794. value = str(value).split(',')
  1795. return ['' if item is None else str(item).strip() for item in value]
  1796. def _check_companion_column(self, side, field_name):
  1797. """
  1798. Verify that a column needed to resolve a side's terminations is present on the form.
  1799. When updating an existing object, BulkImportView removes every field which does not appear
  1800. in the record. A record which redefines a side's termination names must therefore also
  1801. include the columns identifying their type and parent, otherwise the names cannot be
  1802. resolved and the update would appear to succeed while changing nothing.
  1803. """
  1804. if field_name not in self.fields:
  1805. raise forms.ValidationError(
  1806. _(
  1807. "Side {side_upper}: The {column} column must be included when modifying terminations"
  1808. ).format(side_upper=side.upper(), column=field_name)
  1809. )
  1810. def _resolve_side_parent_objects(self, field_name):
  1811. """
  1812. Resolve a side's parent objects from the raw submitted values, preserving their order.
  1813. CSVModelMultipleChoiceField cleans to an unordered queryset, which cannot be used to pair
  1814. each parent with its corresponding termination name by position. Resolution errors are
  1815. reported on the parent field itself.
  1816. """
  1817. if field_name not in self.cleaned_data:
  1818. # The parent field has already raised its own validation error
  1819. return None
  1820. field = self.fields[field_name]
  1821. parents = []
  1822. for value in self._split_side_values(self.data.get(field_name)):
  1823. try:
  1824. parents.append(field.filter_by_value(value).get())
  1825. except ObjectDoesNotExist:
  1826. self.add_error(field_name, _("Object not found: {value}").format(value=value))
  1827. return None
  1828. except MultipleObjectsReturned:
  1829. self.add_error(
  1830. field_name,
  1831. _('"{value}" is not a unique value for this field; multiple objects were found').format(
  1832. value=value
  1833. )
  1834. )
  1835. return None
  1836. return parents
  1837. @staticmethod
  1838. def _get_device_component_termination(model, device, name):
  1839. """
  1840. Resolve a device component by its device and name. If the device is a virtual chassis
  1841. master and the component is not found on it, search all virtual chassis members.
  1842. """
  1843. queryset = model.objects.filter(device=device, name=name)
  1844. if (
  1845. device.virtual_chassis and
  1846. device.virtual_chassis.master == device and
  1847. not queryset.exists()
  1848. ):
  1849. queryset = model.objects.filter(device__in=device.virtual_chassis.members.all(), name=name)
  1850. return queryset.get()
  1851. def _clean_side(self, side):
  1852. """
  1853. Derive a Cable's A/B termination objects.
  1854. :param side: 'a' or 'b'
  1855. """
  1856. if side not in ('a', 'b'):
  1857. raise ValueError(_("Invalid side designation: {side}").format(side=side))
  1858. content_type = self.cleaned_data.get(f'side_{side}_type')
  1859. # Native list values (JSON/YAML) bypass the CharField; strings use its cleaned value
  1860. names = self.data.get(f'side_{side}_name')
  1861. if not isinstance(names, (list, tuple)):
  1862. names = self.cleaned_data.get(f'side_{side}_name')
  1863. names = self._split_side_values(names)
  1864. if not names:
  1865. return None
  1866. if not content_type:
  1867. # BulkImportView removes any field absent from an update record, so a missing termination
  1868. # type here means the column was omitted rather than left blank. Reject it: silently
  1869. # ignoring the submitted names would report a successful update which changed nothing.
  1870. self._check_companion_column(side, f'side_{side}_type')
  1871. return None
  1872. if '' in names:
  1873. raise forms.ValidationError(
  1874. _("Side {side_upper}: Empty termination names are not permitted").format(side_upper=side.upper())
  1875. )
  1876. model = content_type.model_class()
  1877. # Identify the parent field for the termination type. PowerFeed terminations reference a
  1878. # PowerPanel; all other supported types reference a Device.
  1879. if content_type.model == 'powerfeed':
  1880. parent_field_name = f'side_{side}_power_panel'
  1881. parent_label = _('power panel')
  1882. elif any(field.name == 'device' for field in model._meta.fields):
  1883. parent_field_name = f'side_{side}_device'
  1884. parent_label = _('device')
  1885. else:
  1886. raise forms.ValidationError(
  1887. _("Bulk import does not support {type} terminations").format(type=content_type)
  1888. )
  1889. self._check_companion_column(side, parent_field_name)
  1890. parents = self._resolve_side_parent_objects(parent_field_name)
  1891. if parents is None:
  1892. # The parent field has already raised its own validation error
  1893. return None
  1894. if not parents:
  1895. raise forms.ValidationError(
  1896. _("Side {side_upper}: Must specify a {parent} for the selected termination type").format(
  1897. side_upper=side.upper(), parent=parent_label
  1898. )
  1899. )
  1900. if len(parents) == 1:
  1901. parents = parents * len(names)
  1902. elif len(parents) != len(names):
  1903. raise forms.ValidationError(
  1904. _(
  1905. "Side {side_upper}: Must specify either one {parent} for all terminations or one {parent} "
  1906. "per termination name"
  1907. ).format(side_upper=side.upper(), parent=parent_label)
  1908. )
  1909. terminations = []
  1910. for parent, name in zip(parents, names):
  1911. try:
  1912. if content_type.model == 'powerfeed':
  1913. termination_object = model.objects.get(power_panel=parent, name=name)
  1914. else:
  1915. termination_object = self._get_device_component_termination(model, parent, name)
  1916. except ObjectDoesNotExist:
  1917. raise forms.ValidationError(
  1918. _("{side_upper} side termination not found: {parent} {name}").format(
  1919. side_upper=side.upper(), parent=parent, name=name
  1920. )
  1921. )
  1922. except MultipleObjectsReturned:
  1923. raise forms.ValidationError(
  1924. _("{side_upper} side termination not unique: {parent} {name}").format(
  1925. side_upper=side.upper(), parent=parent, name=name
  1926. )
  1927. )
  1928. if termination_object.cable is not None and termination_object.cable != self.instance:
  1929. raise forms.ValidationError(
  1930. _("Side {side_upper}: {parent} {termination_object} is already connected").format(
  1931. side_upper=side.upper(), parent=parent, termination_object=termination_object
  1932. )
  1933. )
  1934. terminations.append(termination_object)
  1935. if len({termination.pk for termination in terminations}) != len(terminations):
  1936. raise forms.ValidationError(
  1937. _("Side {side_upper}: Duplicate termination specified").format(side_upper=side.upper())
  1938. )
  1939. setattr(self.instance, f'{side}_terminations', terminations)
  1940. return terminations
  1941. def _clean_color(self, color):
  1942. """
  1943. Derive a colors hex code
  1944. :param color: color as hex or color name
  1945. """
  1946. color_parsed = color.strip().lower()
  1947. for hex_code, label in ColorChoices.CHOICES:
  1948. if color.lower() == label.lower():
  1949. color_parsed = hex_code
  1950. if len(color_parsed) > 6:
  1951. raise forms.ValidationError(
  1952. _(f"{color} did not match any used color name and was longer than six characters: invalid hex.")
  1953. )
  1954. return color_parsed
  1955. def clean(self):
  1956. cleaned_data = super().clean()
  1957. # Termination resolution is driven by clean_side_<x>_name(), which Django never calls for a
  1958. # field BulkImportView has removed. An update record which supplies a side's supporting
  1959. # columns but omits its name column would therefore have those columns silently discarded
  1960. # and report an update which changed nothing; reject it instead. This cannot trigger on
  1961. # creation, where the name columns are always present (and required).
  1962. for side in ('a', 'b'):
  1963. if f'side_{side}_name' in self.fields:
  1964. continue
  1965. if supplied := [
  1966. column for column in self.TERMINATION_DEPENDENT_COLUMNS
  1967. if f'side_{side}_{column}' in self.fields
  1968. ]:
  1969. self.add_error(None, _(
  1970. "Side {side_upper}: The side_{side}_name column must be included when modifying "
  1971. "terminations (found {columns})"
  1972. ).format(
  1973. side_upper=side.upper(),
  1974. side=side,
  1975. columns=', '.join(f'side_{side}_{column}' for column in supplied),
  1976. ))
  1977. return cleaned_data
  1978. def clean_side_a_name(self):
  1979. return self._clean_side('a')
  1980. def clean_side_b_name(self):
  1981. return self._clean_side('b')
  1982. def clean_length_unit(self):
  1983. # Avoid trying to save as NULL
  1984. length_unit = self.cleaned_data.get('length_unit', None)
  1985. return length_unit if length_unit is not None else ''
  1986. def clean_color(self):
  1987. color = self.cleaned_data.get('color', None)
  1988. return self._clean_color(color) if color is not None else ''
  1989. #
  1990. # Virtual chassis
  1991. #
  1992. class VirtualChassisImportForm(PrimaryModelImportForm):
  1993. master = CSVModelChoiceField(
  1994. label=_('Master'),
  1995. queryset=Device.objects.all(),
  1996. to_field_name='name',
  1997. required=False,
  1998. help_text=_('Master device')
  1999. )
  2000. class Meta:
  2001. model = VirtualChassis
  2002. fields = ('name', 'domain', 'master', 'description', 'owner', 'comments', 'tags')
  2003. #
  2004. # Power
  2005. #
  2006. class PowerPanelImportForm(PrimaryModelImportForm):
  2007. site = CSVModelChoiceField(
  2008. label=_('Site'),
  2009. queryset=Site.objects.all(),
  2010. to_field_name='name',
  2011. help_text=_('Name of parent site')
  2012. )
  2013. location = CSVModelChoiceField(
  2014. label=_('Location'),
  2015. queryset=Location.objects.all(),
  2016. required=False,
  2017. to_field_name='name'
  2018. )
  2019. class Meta:
  2020. model = PowerPanel
  2021. fields = ('site', 'location', 'name', 'description', 'owner', 'comments', 'tags')
  2022. def __init__(self, data=None, *args, **kwargs):
  2023. super().__init__(data, *args, **kwargs)
  2024. if data:
  2025. # Limit group queryset by assigned site
  2026. params = self.get_related_filter('site', 'site', data.get('site'))
  2027. self.fields['location'].queryset = self.fields['location'].queryset.filter(**params)
  2028. class PowerFeedImportForm(PrimaryModelImportForm):
  2029. site = CSVModelChoiceField(
  2030. label=_('Site'),
  2031. queryset=Site.objects.all(),
  2032. to_field_name='name',
  2033. help_text=_('Assigned site')
  2034. )
  2035. power_panel = CSVModelChoiceField(
  2036. label=_('Power panel'),
  2037. queryset=PowerPanel.objects.all(),
  2038. to_field_name='name',
  2039. help_text=_('Upstream power panel')
  2040. )
  2041. location = CSVModelChoiceField(
  2042. label=_('Location'),
  2043. queryset=Location.objects.all(),
  2044. to_field_name='name',
  2045. required=False,
  2046. help_text=_("Rack's location (if any)")
  2047. )
  2048. rack = CSVModelChoiceField(
  2049. label=_('Rack'),
  2050. queryset=Rack.objects.all(),
  2051. to_field_name='name',
  2052. required=False,
  2053. help_text=_('Rack')
  2054. )
  2055. tenant = CSVModelChoiceField(
  2056. queryset=Tenant.objects.all(),
  2057. to_field_name='name',
  2058. required=False,
  2059. help_text=_('Assigned tenant')
  2060. )
  2061. status = CSVChoiceField(
  2062. label=_('Status'),
  2063. choices=PowerFeedStatusChoices,
  2064. help_text=_('Operational status')
  2065. )
  2066. type = CSVChoiceField(
  2067. label=_('Type'),
  2068. choices=PowerFeedTypeChoices,
  2069. help_text=_('Primary or redundant')
  2070. )
  2071. supply = CSVChoiceField(
  2072. label=_('Supply'),
  2073. choices=PowerFeedSupplyChoices,
  2074. help_text=_('Supply type (AC/DC)')
  2075. )
  2076. phase = CSVChoiceField(
  2077. label=_('Phase'),
  2078. choices=PowerFeedPhaseChoices,
  2079. help_text=_('Single or three-phase')
  2080. )
  2081. class Meta:
  2082. model = PowerFeed
  2083. fields = (
  2084. 'site', 'power_panel', 'location', 'rack', 'name', 'status', 'type', 'mark_connected', 'supply', 'phase',
  2085. 'voltage', 'amperage', 'max_utilization', 'tenant', 'description', 'owner', 'comments', 'tags',
  2086. )
  2087. def __init__(self, data=None, *args, **kwargs):
  2088. super().__init__(data, *args, **kwargs)
  2089. if data:
  2090. # Limit power_panel queryset by site
  2091. params = self.get_related_filter('site', 'site', data.get('site'))
  2092. self.fields['power_panel'].queryset = self.fields['power_panel'].queryset.filter(**params)
  2093. # Limit location queryset by site
  2094. params = self.get_related_filter('site', 'site', data.get('site'))
  2095. self.fields['location'].queryset = self.fields['location'].queryset.filter(**params)
  2096. # Limit rack queryset by site and group
  2097. params = {
  2098. **self.get_related_filter('site', 'site', data.get('site')),
  2099. **self.get_related_filter('location', 'location', data.get('location')),
  2100. }
  2101. self.fields['rack'].queryset = self.fields['rack'].queryset.filter(**params)
  2102. class CoolingSourceImportForm(PrimaryModelImportForm):
  2103. site = CSVModelChoiceField(
  2104. label=_('Site'),
  2105. queryset=Site.objects.all(),
  2106. to_field_name='name',
  2107. help_text=_('Name of parent site')
  2108. )
  2109. location = CSVModelChoiceField(
  2110. label=_('Location'),
  2111. queryset=Location.objects.all(),
  2112. required=False,
  2113. to_field_name='name'
  2114. )
  2115. type = CSVChoiceField(
  2116. label=_('Type'),
  2117. choices=CoolingSourceTypeChoices,
  2118. help_text=_('Cooling source type')
  2119. )
  2120. status = CSVChoiceField(
  2121. label=_('Status'),
  2122. choices=CoolingSourceStatusChoices,
  2123. help_text=_('Operational status')
  2124. )
  2125. fluid_type = CSVChoiceField(
  2126. label=_('Fluid type'),
  2127. choices=FluidTypeChoices,
  2128. required=False,
  2129. help_text=_('Coolant fluid type')
  2130. )
  2131. class Meta:
  2132. model = CoolingSource
  2133. fields = (
  2134. 'site', 'location', 'name', 'type', 'status', 'fluid_type', 'cooling_capacity', 'description', 'owner',
  2135. 'comments', 'tags',
  2136. )
  2137. def __init__(self, data=None, *args, **kwargs):
  2138. super().__init__(data, *args, **kwargs)
  2139. if data:
  2140. # Limit location queryset by assigned site
  2141. params = self.get_related_filter('site', 'site', data.get('site'))
  2142. self.fields['location'].queryset = self.fields['location'].queryset.filter(**params)
  2143. class CoolingFeedImportForm(PrimaryModelImportForm):
  2144. site = CSVModelChoiceField(
  2145. label=_('Site'),
  2146. queryset=Site.objects.all(),
  2147. to_field_name='name',
  2148. help_text=_('Assigned site')
  2149. )
  2150. cooling_source = CSVModelChoiceField(
  2151. label=_('Cooling source'),
  2152. queryset=CoolingSource.objects.all(),
  2153. to_field_name='name',
  2154. help_text=_('Upstream cooling source')
  2155. )
  2156. location = CSVModelChoiceField(
  2157. label=_('Location'),
  2158. queryset=Location.objects.all(),
  2159. to_field_name='name',
  2160. required=False,
  2161. help_text=_("Rack's location (if any)")
  2162. )
  2163. rack = CSVModelChoiceField(
  2164. label=_('Rack'),
  2165. queryset=Rack.objects.all(),
  2166. to_field_name='name',
  2167. required=False,
  2168. help_text=_('Rack')
  2169. )
  2170. tenant = CSVModelChoiceField(
  2171. queryset=Tenant.objects.all(),
  2172. to_field_name='name',
  2173. required=False,
  2174. help_text=_('Assigned tenant')
  2175. )
  2176. status = CSVChoiceField(
  2177. label=_('Status'),
  2178. choices=CoolingFeedStatusChoices,
  2179. help_text=_('Operational status')
  2180. )
  2181. max_flow_unit = CSVChoiceField(
  2182. label=_('Max flow unit'),
  2183. choices=FlowRateUnitChoices,
  2184. required=False,
  2185. help_text=_('Unit for maximum flow')
  2186. )
  2187. class Meta:
  2188. model = CoolingFeed
  2189. fields = (
  2190. 'site', 'cooling_source', 'location', 'rack', 'name', 'status',
  2191. 'cooling_capacity', 'max_flow', 'max_flow_unit', 'tenant', 'description', 'owner',
  2192. 'comments', 'tags',
  2193. )
  2194. def __init__(self, data=None, *args, **kwargs):
  2195. super().__init__(data, *args, **kwargs)
  2196. if data:
  2197. # Limit cooling_source queryset by site
  2198. params = self.get_related_filter('site', 'site', data.get('site'))
  2199. self.fields['cooling_source'].queryset = self.fields['cooling_source'].queryset.filter(**params)
  2200. # Limit location queryset by site
  2201. params = self.get_related_filter('site', 'site', data.get('site'))
  2202. self.fields['location'].queryset = self.fields['location'].queryset.filter(**params)
  2203. # Limit rack queryset by site and group
  2204. params = {
  2205. **self.get_related_filter('site', 'site', data.get('site')),
  2206. **self.get_related_filter('location', 'location', data.get('location')),
  2207. }
  2208. self.fields['rack'].queryset = self.fields['rack'].queryset.filter(**params)
  2209. class VirtualDeviceContextImportForm(PrimaryModelImportForm):
  2210. device = CSVModelChoiceField(
  2211. label=_('Device'),
  2212. queryset=Device.objects.all(),
  2213. to_field_name='name',
  2214. help_text=_('Assigned role')
  2215. )
  2216. tenant = CSVModelChoiceField(
  2217. label=_('Tenant'),
  2218. queryset=Tenant.objects.all(),
  2219. required=False,
  2220. to_field_name='name',
  2221. help_text=_('Assigned tenant')
  2222. )
  2223. status = CSVChoiceField(
  2224. label=_('Status'),
  2225. choices=VirtualDeviceContextStatusChoices,
  2226. )
  2227. primary_ip4 = CSVModelChoiceField(
  2228. label=_('Primary IPv4'),
  2229. queryset=IPAddress.objects.all(),
  2230. required=False,
  2231. to_field_name='address',
  2232. help_text=_('IPv4 address with mask, e.g. 1.2.3.4/24')
  2233. )
  2234. primary_ip6 = CSVModelChoiceField(
  2235. label=_('Primary IPv6'),
  2236. queryset=IPAddress.objects.all(),
  2237. required=False,
  2238. to_field_name='address',
  2239. help_text=_('IPv6 address with prefix length, e.g. 2001:db8::1/64')
  2240. )
  2241. class Meta:
  2242. fields = [
  2243. 'name', 'device', 'status', 'tenant', 'identifier', 'owner', 'comments', 'primary_ip4', 'primary_ip6',
  2244. ]
  2245. model = VirtualDeviceContext
  2246. def __init__(self, data=None, *args, **kwargs):
  2247. super().__init__(data, *args, **kwargs)
  2248. if data:
  2249. # Limit primary_ip4/ip6 querysets by assigned device
  2250. params = self.get_related_filter('interface__device', 'device', data.get('device'))
  2251. self.fields['primary_ip4'].queryset = self.fields['primary_ip4'].queryset.filter(**params)
  2252. self.fields['primary_ip6'].queryset = self.fields['primary_ip6'].queryset.filter(**params)