forms.py 122 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381
  1. import re
  2. from django import forms
  3. from django.contrib.auth.models import User
  4. from django.contrib.contenttypes.models import ContentType
  5. from django.contrib.postgres.forms.array import SimpleArrayField
  6. from django.core.exceptions import ObjectDoesNotExist
  7. from django.db.models import Q
  8. from mptt.forms import TreeNodeChoiceField
  9. from netaddr import EUI
  10. from netaddr.core import AddrFormatError
  11. from taggit.forms import TagField
  12. from timezone_field import TimeZoneFormField
  13. from circuits.models import Circuit, Provider
  14. from extras.forms import (
  15. AddRemoveTagsForm, CustomFieldForm, CustomFieldBulkEditForm, CustomFieldFilterForm, LocalConfigContextFilterForm
  16. )
  17. from ipam.models import IPAddress, VLAN, VLANGroup
  18. from tenancy.forms import TenancyFilterForm, TenancyForm
  19. from tenancy.models import Tenant, TenantGroup
  20. from utilities.forms import (
  21. APISelect, APISelectMultiple, add_blank_choice, ArrayFieldSelectMultiple, BootstrapMixin, BulkEditForm,
  22. BulkEditNullBooleanSelect, ChainedFieldsMixin, ChainedModelChoiceField, ColorSelect, CommentField, ComponentForm,
  23. ConfirmationForm, CSVChoiceField, ExpandableNameField, FilterChoiceField, FlexibleModelChoiceField, JSONField,
  24. SelectWithPK, SmallTextarea, SlugField, StaticSelect2, StaticSelect2Multiple, BOOLEAN_WITH_BLANK_CHOICES,
  25. )
  26. from virtualization.models import Cluster, ClusterGroup, VirtualMachine
  27. from .choices import *
  28. from .constants import *
  29. from .models import (
  30. Cable, DeviceBay, DeviceBayTemplate, ConsolePort, ConsolePortTemplate, ConsoleServerPort, ConsoleServerPortTemplate,
  31. Device, DeviceRole, DeviceType, FrontPort, FrontPortTemplate, Interface, InterfaceTemplate, Manufacturer,
  32. InventoryItem, Platform, PowerFeed, PowerOutlet, PowerOutletTemplate, PowerPanel, PowerPort, PowerPortTemplate,
  33. Rack, RackGroup, RackReservation, RackRole, RearPort, RearPortTemplate, Region, Site, VirtualChassis,
  34. )
  35. DEVICE_BY_PK_RE = r'{\d+\}'
  36. INTERFACE_MODE_HELP_TEXT = """
  37. Access: One untagged VLAN<br />
  38. Tagged: One untagged VLAN and/or one or more tagged VLANs<br />
  39. Tagged All: Implies all VLANs are available (w/optional untagged VLAN)
  40. """
  41. def get_device_by_name_or_pk(name):
  42. """
  43. Attempt to retrieve a device by either its name or primary key ('{pk}').
  44. """
  45. if re.match(DEVICE_BY_PK_RE, name):
  46. pk = name.strip('{}')
  47. device = Device.objects.get(pk=pk)
  48. else:
  49. device = Device.objects.get(name=name)
  50. return device
  51. class DeviceComponentFilterForm(BootstrapMixin, forms.Form):
  52. field_order = [
  53. 'q', 'region', 'site'
  54. ]
  55. q = forms.CharField(
  56. required=False,
  57. label='Search'
  58. )
  59. region = TreeNodeChoiceField(
  60. queryset=Region.objects.all(),
  61. required=False,
  62. widget=APISelect(
  63. api_url="/api/dcim/regions/"
  64. )
  65. )
  66. site = forms.ModelChoiceField(
  67. queryset=Site.objects.all(),
  68. to_field_name='slug',
  69. required=False,
  70. help_text='Name of parent site',
  71. error_messages={
  72. 'invalid_choice': 'Site not found.',
  73. }
  74. )
  75. class InterfaceCommonForm:
  76. def clean(self):
  77. super().clean()
  78. # Validate VLAN assignments
  79. tagged_vlans = self.cleaned_data['tagged_vlans']
  80. # Untagged interfaces cannot be assigned tagged VLANs
  81. if self.cleaned_data['mode'] == InterfaceModeChoices.MODE_ACCESS and tagged_vlans:
  82. raise forms.ValidationError({
  83. 'mode': "An access interface cannot have tagged VLANs assigned."
  84. })
  85. # Remove all tagged VLAN assignments from "tagged all" interfaces
  86. elif self.cleaned_data['mode'] == InterfaceModeChoices.MODE_TAGGED_ALL:
  87. self.cleaned_data['tagged_vlans'] = []
  88. class BulkRenameForm(forms.Form):
  89. """
  90. An extendable form to be used for renaming device components in bulk.
  91. """
  92. find = forms.CharField()
  93. replace = forms.CharField()
  94. use_regex = forms.BooleanField(
  95. required=False,
  96. initial=True,
  97. label='Use regular expressions'
  98. )
  99. def clean(self):
  100. # Validate regular expression in "find" field
  101. if self.cleaned_data['use_regex']:
  102. try:
  103. re.compile(self.cleaned_data['find'])
  104. except re.error:
  105. raise forms.ValidationError({
  106. 'find': "Invalid regular expression"
  107. })
  108. #
  109. # Fields
  110. #
  111. class MACAddressField(forms.Field):
  112. widget = forms.CharField
  113. default_error_messages = {
  114. 'invalid': 'MAC address must be in EUI-48 format',
  115. }
  116. def to_python(self, value):
  117. value = super().to_python(value)
  118. # Validate MAC address format
  119. try:
  120. value = EUI(value.strip())
  121. except AddrFormatError:
  122. raise forms.ValidationError(self.error_messages['invalid'], code='invalid')
  123. return value
  124. #
  125. # Regions
  126. #
  127. class RegionForm(BootstrapMixin, forms.ModelForm):
  128. slug = SlugField()
  129. class Meta:
  130. model = Region
  131. fields = [
  132. 'parent', 'name', 'slug',
  133. ]
  134. widgets = {
  135. 'parent': APISelect(
  136. api_url="/api/dcim/regions/"
  137. )
  138. }
  139. class RegionCSVForm(forms.ModelForm):
  140. parent = forms.ModelChoiceField(
  141. queryset=Region.objects.all(),
  142. required=False,
  143. to_field_name='name',
  144. help_text='Name of parent region',
  145. error_messages={
  146. 'invalid_choice': 'Region not found.',
  147. }
  148. )
  149. class Meta:
  150. model = Region
  151. fields = Region.csv_headers
  152. help_texts = {
  153. 'name': 'Region name',
  154. 'slug': 'URL-friendly slug',
  155. }
  156. class RegionFilterForm(BootstrapMixin, forms.Form):
  157. model = Site
  158. q = forms.CharField(
  159. required=False,
  160. label='Search'
  161. )
  162. #
  163. # Sites
  164. #
  165. class SiteForm(BootstrapMixin, TenancyForm, CustomFieldForm):
  166. region = TreeNodeChoiceField(
  167. queryset=Region.objects.all(),
  168. required=False,
  169. widget=APISelect(
  170. api_url="/api/dcim/regions/"
  171. )
  172. )
  173. slug = SlugField()
  174. comments = CommentField()
  175. tags = TagField(
  176. required=False
  177. )
  178. class Meta:
  179. model = Site
  180. fields = [
  181. 'name', 'slug', 'status', 'region', 'tenant_group', 'tenant', 'facility', 'asn', 'time_zone', 'description',
  182. 'physical_address', 'shipping_address', 'latitude', 'longitude', 'contact_name', 'contact_phone',
  183. 'contact_email', 'comments', 'tags',
  184. ]
  185. widgets = {
  186. 'physical_address': SmallTextarea(
  187. attrs={
  188. 'rows': 3,
  189. }
  190. ),
  191. 'shipping_address': SmallTextarea(
  192. attrs={
  193. 'rows': 3,
  194. }
  195. ),
  196. 'status': StaticSelect2(),
  197. 'time_zone': StaticSelect2(),
  198. }
  199. help_texts = {
  200. 'name': "Full name of the site",
  201. 'facility': "Data center provider and facility (e.g. Equinix NY7)",
  202. 'asn': "BGP autonomous system number",
  203. 'time_zone': "Local time zone",
  204. 'description': "Short description (will appear in sites list)",
  205. 'physical_address': "Physical location of the building (e.g. for GPS)",
  206. 'shipping_address': "If different from the physical address",
  207. 'latitude': "Latitude in decimal format (xx.yyyyyy)",
  208. 'longitude': "Longitude in decimal format (xx.yyyyyy)"
  209. }
  210. class SiteCSVForm(forms.ModelForm):
  211. status = CSVChoiceField(
  212. choices=SiteStatusChoices,
  213. required=False,
  214. help_text='Operational status'
  215. )
  216. region = forms.ModelChoiceField(
  217. queryset=Region.objects.all(),
  218. required=False,
  219. to_field_name='name',
  220. help_text='Name of assigned region',
  221. error_messages={
  222. 'invalid_choice': 'Region not found.',
  223. }
  224. )
  225. tenant = forms.ModelChoiceField(
  226. queryset=Tenant.objects.all(),
  227. required=False,
  228. to_field_name='name',
  229. help_text='Name of assigned tenant',
  230. error_messages={
  231. 'invalid_choice': 'Tenant not found.',
  232. }
  233. )
  234. class Meta:
  235. model = Site
  236. fields = Site.csv_headers
  237. help_texts = {
  238. 'name': 'Site name',
  239. 'slug': 'URL-friendly slug',
  240. 'asn': '32-bit autonomous system number',
  241. }
  242. class SiteBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldBulkEditForm):
  243. pk = forms.ModelMultipleChoiceField(
  244. queryset=Site.objects.all(),
  245. widget=forms.MultipleHiddenInput
  246. )
  247. status = forms.ChoiceField(
  248. choices=add_blank_choice(SiteStatusChoices),
  249. required=False,
  250. initial='',
  251. widget=StaticSelect2()
  252. )
  253. region = TreeNodeChoiceField(
  254. queryset=Region.objects.all(),
  255. required=False,
  256. widget=APISelect(
  257. api_url="/api/dcim/regions/"
  258. )
  259. )
  260. tenant = forms.ModelChoiceField(
  261. queryset=Tenant.objects.all(),
  262. required=False,
  263. widget=APISelect(
  264. api_url="/api/tenancy/tenants",
  265. )
  266. )
  267. asn = forms.IntegerField(
  268. min_value=1,
  269. max_value=4294967295,
  270. required=False,
  271. label='ASN'
  272. )
  273. description = forms.CharField(
  274. max_length=100,
  275. required=False
  276. )
  277. time_zone = TimeZoneFormField(
  278. choices=add_blank_choice(TimeZoneFormField().choices),
  279. required=False,
  280. widget=StaticSelect2()
  281. )
  282. class Meta:
  283. nullable_fields = [
  284. 'region', 'tenant', 'asn', 'description', 'time_zone',
  285. ]
  286. class SiteFilterForm(BootstrapMixin, TenancyFilterForm, CustomFieldFilterForm):
  287. model = Site
  288. field_order = ['q', 'status', 'region', 'tenant_group', 'tenant']
  289. q = forms.CharField(
  290. required=False,
  291. label='Search'
  292. )
  293. status = forms.MultipleChoiceField(
  294. choices=SiteStatusChoices,
  295. required=False,
  296. widget=StaticSelect2Multiple()
  297. )
  298. region = forms.ModelMultipleChoiceField(
  299. queryset=Region.objects.all(),
  300. to_field_name='slug',
  301. required=False,
  302. widget=APISelectMultiple(
  303. api_url="/api/dcim/regions/",
  304. value_field="slug",
  305. )
  306. )
  307. #
  308. # Rack groups
  309. #
  310. class RackGroupForm(BootstrapMixin, forms.ModelForm):
  311. slug = SlugField()
  312. class Meta:
  313. model = RackGroup
  314. fields = [
  315. 'site', 'name', 'slug',
  316. ]
  317. widgets = {
  318. 'site': APISelect(
  319. api_url="/api/dcim/sites/"
  320. )
  321. }
  322. class RackGroupCSVForm(forms.ModelForm):
  323. site = forms.ModelChoiceField(
  324. queryset=Site.objects.all(),
  325. to_field_name='name',
  326. help_text='Name of parent site',
  327. error_messages={
  328. 'invalid_choice': 'Site not found.',
  329. }
  330. )
  331. class Meta:
  332. model = RackGroup
  333. fields = RackGroup.csv_headers
  334. help_texts = {
  335. 'name': 'Name of rack group',
  336. 'slug': 'URL-friendly slug',
  337. }
  338. class RackGroupFilterForm(BootstrapMixin, forms.Form):
  339. site = FilterChoiceField(
  340. queryset=Site.objects.all(),
  341. to_field_name='slug',
  342. widget=APISelectMultiple(
  343. api_url="/api/dcim/sites/",
  344. value_field="slug",
  345. )
  346. )
  347. #
  348. # Rack roles
  349. #
  350. class RackRoleForm(BootstrapMixin, forms.ModelForm):
  351. slug = SlugField()
  352. class Meta:
  353. model = RackRole
  354. fields = [
  355. 'name', 'slug', 'color', 'description',
  356. ]
  357. class RackRoleCSVForm(forms.ModelForm):
  358. slug = SlugField()
  359. class Meta:
  360. model = RackRole
  361. fields = RackRole.csv_headers
  362. help_texts = {
  363. 'name': 'Name of rack role',
  364. 'color': 'RGB color in hexadecimal (e.g. 00ff00)'
  365. }
  366. #
  367. # Racks
  368. #
  369. class RackForm(BootstrapMixin, TenancyForm, CustomFieldForm):
  370. group = ChainedModelChoiceField(
  371. queryset=RackGroup.objects.all(),
  372. chains=(
  373. ('site', 'site'),
  374. ),
  375. required=False,
  376. widget=APISelect(
  377. api_url='/api/dcim/rack-groups/',
  378. )
  379. )
  380. comments = CommentField()
  381. tags = TagField(
  382. required=False
  383. )
  384. class Meta:
  385. model = Rack
  386. fields = [
  387. 'site', 'group', 'name', 'facility_id', 'tenant_group', 'tenant', 'status', 'role', 'serial', 'asset_tag',
  388. 'type', 'width', 'u_height', 'desc_units', 'outer_width', 'outer_depth', 'outer_unit', 'comments', 'tags',
  389. ]
  390. help_texts = {
  391. 'site': "The site at which the rack exists",
  392. 'name': "Organizational rack name",
  393. 'facility_id': "The unique rack ID assigned by the facility",
  394. 'u_height': "Height in rack units",
  395. }
  396. widgets = {
  397. 'site': APISelect(
  398. api_url="/api/dcim/sites/",
  399. filter_for={
  400. 'group': 'site_id',
  401. }
  402. ),
  403. 'status': StaticSelect2(),
  404. 'role': APISelect(
  405. api_url="/api/dcim/rack-roles/"
  406. ),
  407. 'type': StaticSelect2(),
  408. 'width': StaticSelect2(),
  409. 'outer_unit': StaticSelect2(),
  410. }
  411. class RackCSVForm(forms.ModelForm):
  412. site = forms.ModelChoiceField(
  413. queryset=Site.objects.all(),
  414. to_field_name='name',
  415. help_text='Name of parent site',
  416. error_messages={
  417. 'invalid_choice': 'Site not found.',
  418. }
  419. )
  420. group_name = forms.CharField(
  421. help_text='Name of rack group',
  422. required=False
  423. )
  424. tenant = forms.ModelChoiceField(
  425. queryset=Tenant.objects.all(),
  426. required=False,
  427. to_field_name='name',
  428. help_text='Name of assigned tenant',
  429. error_messages={
  430. 'invalid_choice': 'Tenant not found.',
  431. }
  432. )
  433. status = CSVChoiceField(
  434. choices=RackStatusChoices,
  435. required=False,
  436. help_text='Operational status'
  437. )
  438. role = forms.ModelChoiceField(
  439. queryset=RackRole.objects.all(),
  440. required=False,
  441. to_field_name='name',
  442. help_text='Name of assigned role',
  443. error_messages={
  444. 'invalid_choice': 'Role not found.',
  445. }
  446. )
  447. type = CSVChoiceField(
  448. choices=RackTypeChoices,
  449. required=False,
  450. help_text='Rack type'
  451. )
  452. width = forms.ChoiceField(
  453. choices=RackWidthChoices,
  454. help_text='Rail-to-rail width (in inches)'
  455. )
  456. outer_unit = CSVChoiceField(
  457. choices=RackDimensionUnitChoices,
  458. required=False,
  459. help_text='Unit for outer dimensions'
  460. )
  461. class Meta:
  462. model = Rack
  463. fields = Rack.csv_headers
  464. help_texts = {
  465. 'name': 'Rack name',
  466. 'u_height': 'Height in rack units',
  467. }
  468. def clean(self):
  469. super().clean()
  470. site = self.cleaned_data.get('site')
  471. group_name = self.cleaned_data.get('group_name')
  472. name = self.cleaned_data.get('name')
  473. facility_id = self.cleaned_data.get('facility_id')
  474. # Validate rack group
  475. if group_name:
  476. try:
  477. self.instance.group = RackGroup.objects.get(site=site, name=group_name)
  478. except RackGroup.DoesNotExist:
  479. raise forms.ValidationError("Rack group {} not found for site {}".format(group_name, site))
  480. # Validate uniqueness of rack name within group
  481. if Rack.objects.filter(group=self.instance.group, name=name).exists():
  482. raise forms.ValidationError(
  483. "A rack named {} already exists within group {}".format(name, group_name)
  484. )
  485. # Validate uniqueness of facility ID within group
  486. if facility_id and Rack.objects.filter(group=self.instance.group, facility_id=facility_id).exists():
  487. raise forms.ValidationError(
  488. "A rack with the facility ID {} already exists within group {}".format(facility_id, group_name)
  489. )
  490. class RackBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldBulkEditForm):
  491. pk = forms.ModelMultipleChoiceField(
  492. queryset=Rack.objects.all(),
  493. widget=forms.MultipleHiddenInput
  494. )
  495. site = forms.ModelChoiceField(
  496. queryset=Site.objects.all(),
  497. required=False,
  498. widget=APISelect(
  499. api_url="/api/dcim/sites",
  500. filter_for={
  501. 'group': 'site_id',
  502. }
  503. )
  504. )
  505. group = forms.ModelChoiceField(
  506. queryset=RackGroup.objects.all(),
  507. required=False,
  508. widget=APISelect(
  509. api_url="/api/dcim/rack-groups",
  510. )
  511. )
  512. tenant = forms.ModelChoiceField(
  513. queryset=Tenant.objects.all(),
  514. required=False,
  515. widget=APISelect(
  516. api_url="/api/tenancy/tenants",
  517. )
  518. )
  519. status = forms.ChoiceField(
  520. choices=add_blank_choice(RackStatusChoices),
  521. required=False,
  522. initial='',
  523. widget=StaticSelect2()
  524. )
  525. role = forms.ModelChoiceField(
  526. queryset=RackRole.objects.all(),
  527. required=False,
  528. widget=APISelect(
  529. api_url="/api/dcim/rack-roles",
  530. )
  531. )
  532. serial = forms.CharField(
  533. max_length=50,
  534. required=False,
  535. label='Serial Number'
  536. )
  537. asset_tag = forms.CharField(
  538. max_length=50,
  539. required=False
  540. )
  541. type = forms.ChoiceField(
  542. choices=add_blank_choice(RackTypeChoices),
  543. required=False,
  544. widget=StaticSelect2()
  545. )
  546. width = forms.ChoiceField(
  547. choices=add_blank_choice(RackWidthChoices),
  548. required=False,
  549. widget=StaticSelect2()
  550. )
  551. u_height = forms.IntegerField(
  552. required=False,
  553. label='Height (U)'
  554. )
  555. desc_units = forms.NullBooleanField(
  556. required=False,
  557. widget=BulkEditNullBooleanSelect,
  558. label='Descending units'
  559. )
  560. outer_width = forms.IntegerField(
  561. required=False,
  562. min_value=1
  563. )
  564. outer_depth = forms.IntegerField(
  565. required=False,
  566. min_value=1
  567. )
  568. outer_unit = forms.ChoiceField(
  569. choices=add_blank_choice(RackDimensionUnitChoices),
  570. required=False,
  571. widget=StaticSelect2()
  572. )
  573. comments = CommentField(
  574. widget=SmallTextarea
  575. )
  576. class Meta:
  577. nullable_fields = [
  578. 'group', 'tenant', 'role', 'serial', 'asset_tag', 'outer_width', 'outer_depth', 'outer_unit', 'comments',
  579. ]
  580. class RackFilterForm(BootstrapMixin, TenancyFilterForm, CustomFieldFilterForm):
  581. model = Rack
  582. field_order = ['q', 'site', 'group_id', 'status', 'role', 'tenant_group', 'tenant']
  583. q = forms.CharField(
  584. required=False,
  585. label='Search'
  586. )
  587. site = FilterChoiceField(
  588. queryset=Site.objects.all(),
  589. to_field_name='slug',
  590. widget=APISelectMultiple(
  591. api_url="/api/dcim/sites/",
  592. value_field="slug",
  593. filter_for={
  594. 'group_id': 'site'
  595. }
  596. )
  597. )
  598. group_id = ChainedModelChoiceField(
  599. label='Rack group',
  600. queryset=RackGroup.objects.prefetch_related('site'),
  601. chains=(
  602. ('site', 'site'),
  603. ),
  604. required=False,
  605. widget=APISelectMultiple(
  606. api_url="/api/dcim/rack-groups/",
  607. null_option=True,
  608. )
  609. )
  610. status = forms.MultipleChoiceField(
  611. choices=RackStatusChoices,
  612. required=False,
  613. widget=StaticSelect2Multiple()
  614. )
  615. role = FilterChoiceField(
  616. queryset=RackRole.objects.all(),
  617. to_field_name='slug',
  618. null_label='-- None --',
  619. widget=APISelectMultiple(
  620. api_url="/api/dcim/rack-roles/",
  621. value_field="slug",
  622. null_option=True,
  623. )
  624. )
  625. #
  626. # Rack reservations
  627. #
  628. class RackReservationForm(BootstrapMixin, TenancyForm, forms.ModelForm):
  629. units = SimpleArrayField(
  630. base_field=forms.IntegerField(),
  631. widget=ArrayFieldSelectMultiple(
  632. attrs={
  633. 'size': 10,
  634. }
  635. )
  636. )
  637. user = forms.ModelChoiceField(
  638. queryset=User.objects.order_by(
  639. 'username'
  640. ),
  641. widget=StaticSelect2()
  642. )
  643. class Meta:
  644. model = RackReservation
  645. fields = [
  646. 'units', 'user', 'tenant_group', 'tenant', 'description',
  647. ]
  648. def __init__(self, *args, **kwargs):
  649. super().__init__(*args, **kwargs)
  650. # Populate rack unit choices
  651. self.fields['units'].widget.choices = self._get_unit_choices()
  652. def _get_unit_choices(self):
  653. rack = self.instance.rack
  654. reserved_units = []
  655. for resv in rack.reservations.exclude(pk=self.instance.pk):
  656. for u in resv.units:
  657. reserved_units.append(u)
  658. unit_choices = [(u, {'label': str(u), 'disabled': u in reserved_units}) for u in rack.units]
  659. return unit_choices
  660. class RackReservationBulkEditForm(BootstrapMixin, BulkEditForm):
  661. pk = forms.ModelMultipleChoiceField(
  662. queryset=RackReservation.objects.all(),
  663. widget=forms.MultipleHiddenInput()
  664. )
  665. user = forms.ModelChoiceField(
  666. queryset=User.objects.order_by(
  667. 'username'
  668. ),
  669. required=False,
  670. widget=StaticSelect2()
  671. )
  672. tenant = forms.ModelChoiceField(
  673. queryset=Tenant.objects.all(),
  674. required=False,
  675. widget=APISelect(
  676. api_url="/api/tenancy/tenant",
  677. )
  678. )
  679. description = forms.CharField(
  680. max_length=100,
  681. required=False
  682. )
  683. class Meta:
  684. nullable_fields = []
  685. class RackReservationFilterForm(BootstrapMixin, TenancyFilterForm):
  686. field_order = ['q', 'site', 'group_id', 'tenant_group', 'tenant']
  687. q = forms.CharField(
  688. required=False,
  689. label='Search'
  690. )
  691. site = FilterChoiceField(
  692. queryset=Site.objects.all(),
  693. to_field_name='slug',
  694. widget=APISelectMultiple(
  695. api_url="/api/dcim/sites/",
  696. value_field="slug",
  697. )
  698. )
  699. group_id = FilterChoiceField(
  700. queryset=RackGroup.objects.prefetch_related('site'),
  701. label='Rack group',
  702. null_label='-- None --',
  703. widget=APISelectMultiple(
  704. api_url="/api/dcim/rack-groups/",
  705. null_option=True,
  706. )
  707. )
  708. #
  709. # Manufacturers
  710. #
  711. class ManufacturerForm(BootstrapMixin, forms.ModelForm):
  712. slug = SlugField()
  713. class Meta:
  714. model = Manufacturer
  715. fields = [
  716. 'name', 'slug',
  717. ]
  718. class ManufacturerCSVForm(forms.ModelForm):
  719. class Meta:
  720. model = Manufacturer
  721. fields = Manufacturer.csv_headers
  722. help_texts = {
  723. 'name': 'Manufacturer name',
  724. 'slug': 'URL-friendly slug',
  725. }
  726. #
  727. # Device types
  728. #
  729. class DeviceTypeForm(BootstrapMixin, CustomFieldForm):
  730. slug = SlugField(
  731. slug_source='model'
  732. )
  733. comments = CommentField()
  734. tags = TagField(
  735. required=False
  736. )
  737. class Meta:
  738. model = DeviceType
  739. fields = [
  740. 'manufacturer', 'model', 'slug', 'part_number', 'u_height', 'is_full_depth', 'subdevice_role', 'comments',
  741. 'tags',
  742. ]
  743. widgets = {
  744. 'manufacturer': APISelect(
  745. api_url="/api/dcim/manufacturers/"
  746. ),
  747. 'subdevice_role': StaticSelect2()
  748. }
  749. class DeviceTypeImportForm(BootstrapMixin, forms.ModelForm):
  750. manufacturer = forms.ModelChoiceField(
  751. queryset=Manufacturer.objects.all(),
  752. to_field_name='name'
  753. )
  754. class Meta:
  755. model = DeviceType
  756. fields = [
  757. 'manufacturer', 'model', 'slug', 'part_number', 'u_height', 'is_full_depth', 'subdevice_role',
  758. ]
  759. class DeviceTypeBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldBulkEditForm):
  760. pk = forms.ModelMultipleChoiceField(
  761. queryset=DeviceType.objects.all(),
  762. widget=forms.MultipleHiddenInput()
  763. )
  764. manufacturer = forms.ModelChoiceField(
  765. queryset=Manufacturer.objects.all(),
  766. required=False,
  767. widget=APISelect(
  768. api_url="/api/dcim/manufactureres"
  769. )
  770. )
  771. u_height = forms.IntegerField(
  772. min_value=1,
  773. required=False
  774. )
  775. is_full_depth = forms.NullBooleanField(
  776. required=False,
  777. widget=BulkEditNullBooleanSelect(),
  778. label='Is full depth'
  779. )
  780. class Meta:
  781. nullable_fields = []
  782. class DeviceTypeFilterForm(BootstrapMixin, CustomFieldFilterForm):
  783. model = DeviceType
  784. q = forms.CharField(
  785. required=False,
  786. label='Search'
  787. )
  788. manufacturer = FilterChoiceField(
  789. queryset=Manufacturer.objects.all(),
  790. to_field_name='slug',
  791. widget=APISelectMultiple(
  792. api_url="/api/dcim/manufacturers/",
  793. value_field="slug",
  794. )
  795. )
  796. subdevice_role = forms.MultipleChoiceField(
  797. choices=add_blank_choice(SubdeviceRoleChoices),
  798. required=False,
  799. widget=StaticSelect2Multiple()
  800. )
  801. console_ports = forms.NullBooleanField(
  802. required=False,
  803. label='Has console ports',
  804. widget=StaticSelect2(
  805. choices=BOOLEAN_WITH_BLANK_CHOICES
  806. )
  807. )
  808. console_server_ports = forms.NullBooleanField(
  809. required=False,
  810. label='Has console server ports',
  811. widget=StaticSelect2(
  812. choices=BOOLEAN_WITH_BLANK_CHOICES
  813. )
  814. )
  815. power_ports = forms.NullBooleanField(
  816. required=False,
  817. label='Has power ports',
  818. widget=StaticSelect2(
  819. choices=BOOLEAN_WITH_BLANK_CHOICES
  820. )
  821. )
  822. power_outlets = forms.NullBooleanField(
  823. required=False,
  824. label='Has power outlets',
  825. widget=StaticSelect2(
  826. choices=BOOLEAN_WITH_BLANK_CHOICES
  827. )
  828. )
  829. interfaces = forms.NullBooleanField(
  830. required=False,
  831. label='Has interfaces',
  832. widget=StaticSelect2(
  833. choices=BOOLEAN_WITH_BLANK_CHOICES
  834. )
  835. )
  836. pass_through_ports = forms.NullBooleanField(
  837. required=False,
  838. label='Has pass-through ports',
  839. widget=StaticSelect2(
  840. choices=BOOLEAN_WITH_BLANK_CHOICES
  841. )
  842. )
  843. #
  844. # Device component templates
  845. #
  846. class ConsolePortTemplateForm(BootstrapMixin, forms.ModelForm):
  847. class Meta:
  848. model = ConsolePortTemplate
  849. fields = [
  850. 'device_type', 'name', 'type',
  851. ]
  852. widgets = {
  853. 'device_type': forms.HiddenInput(),
  854. }
  855. class ConsolePortTemplateCreateForm(ComponentForm):
  856. name_pattern = ExpandableNameField(
  857. label='Name'
  858. )
  859. type = forms.ChoiceField(
  860. choices=ConsolePortTypeChoices,
  861. widget=StaticSelect2()
  862. )
  863. class ConsoleServerPortTemplateForm(BootstrapMixin, forms.ModelForm):
  864. class Meta:
  865. model = ConsoleServerPortTemplate
  866. fields = [
  867. 'device_type', 'name', 'type',
  868. ]
  869. widgets = {
  870. 'device_type': forms.HiddenInput(),
  871. }
  872. class ConsoleServerPortTemplateCreateForm(ComponentForm):
  873. name_pattern = ExpandableNameField(
  874. label='Name'
  875. )
  876. type = forms.ChoiceField(
  877. choices=add_blank_choice(ConsolePortTypeChoices),
  878. widget=StaticSelect2()
  879. )
  880. class PowerPortTemplateForm(BootstrapMixin, forms.ModelForm):
  881. class Meta:
  882. model = PowerPortTemplate
  883. fields = [
  884. 'device_type', 'name', 'type', 'maximum_draw', 'allocated_draw',
  885. ]
  886. widgets = {
  887. 'device_type': forms.HiddenInput(),
  888. }
  889. class PowerPortTemplateCreateForm(ComponentForm):
  890. name_pattern = ExpandableNameField(
  891. label='Name'
  892. )
  893. type = forms.ChoiceField(
  894. choices=add_blank_choice(PowerPortTypeChoices),
  895. required=False
  896. )
  897. maximum_draw = forms.IntegerField(
  898. min_value=1,
  899. required=False,
  900. help_text="Maximum current draw (watts)"
  901. )
  902. allocated_draw = forms.IntegerField(
  903. min_value=1,
  904. required=False,
  905. help_text="Allocated current draw (watts)"
  906. )
  907. class PowerOutletTemplateForm(BootstrapMixin, forms.ModelForm):
  908. class Meta:
  909. model = PowerOutletTemplate
  910. fields = [
  911. 'device_type', 'name', 'type', 'power_port', 'feed_leg',
  912. ]
  913. widgets = {
  914. 'device_type': forms.HiddenInput(),
  915. }
  916. def __init__(self, *args, **kwargs):
  917. super().__init__(*args, **kwargs)
  918. # Limit power_port choices to current DeviceType
  919. if hasattr(self.instance, 'device_type'):
  920. self.fields['power_port'].queryset = PowerPortTemplate.objects.filter(
  921. device_type=self.instance.device_type
  922. )
  923. class PowerOutletTemplateCreateForm(ComponentForm):
  924. name_pattern = ExpandableNameField(
  925. label='Name'
  926. )
  927. type = forms.ChoiceField(
  928. choices=add_blank_choice(PowerOutletTypeChoices),
  929. required=False
  930. )
  931. power_port = forms.ModelChoiceField(
  932. queryset=PowerPortTemplate.objects.all(),
  933. required=False
  934. )
  935. feed_leg = forms.ChoiceField(
  936. choices=add_blank_choice(PowerOutletFeedLegChoices),
  937. required=False,
  938. widget=StaticSelect2()
  939. )
  940. def __init__(self, *args, **kwargs):
  941. super().__init__(*args, **kwargs)
  942. # Limit power_port choices to current DeviceType
  943. self.fields['power_port'].queryset = PowerPortTemplate.objects.filter(
  944. device_type=self.parent
  945. )
  946. class InterfaceTemplateForm(BootstrapMixin, forms.ModelForm):
  947. class Meta:
  948. model = InterfaceTemplate
  949. fields = [
  950. 'device_type', 'name', 'type', 'mgmt_only',
  951. ]
  952. widgets = {
  953. 'device_type': forms.HiddenInput(),
  954. 'type': StaticSelect2(),
  955. }
  956. class InterfaceTemplateCreateForm(ComponentForm):
  957. name_pattern = ExpandableNameField(
  958. label='Name'
  959. )
  960. type = forms.ChoiceField(
  961. choices=InterfaceTypeChoices,
  962. widget=StaticSelect2()
  963. )
  964. mgmt_only = forms.BooleanField(
  965. required=False,
  966. label='Management only'
  967. )
  968. class InterfaceTemplateBulkEditForm(BootstrapMixin, BulkEditForm):
  969. pk = forms.ModelMultipleChoiceField(
  970. queryset=InterfaceTemplate.objects.all(),
  971. widget=forms.MultipleHiddenInput()
  972. )
  973. type = forms.ChoiceField(
  974. choices=add_blank_choice(InterfaceTypeChoices),
  975. required=False,
  976. widget=StaticSelect2()
  977. )
  978. mgmt_only = forms.NullBooleanField(
  979. required=False,
  980. widget=BulkEditNullBooleanSelect,
  981. label='Management only'
  982. )
  983. class Meta:
  984. nullable_fields = []
  985. class FrontPortTemplateForm(BootstrapMixin, forms.ModelForm):
  986. class Meta:
  987. model = FrontPortTemplate
  988. fields = [
  989. 'device_type', 'name', 'type', 'rear_port', 'rear_port_position',
  990. ]
  991. widgets = {
  992. 'device_type': forms.HiddenInput(),
  993. 'rear_port': StaticSelect2(),
  994. }
  995. def __init__(self, *args, **kwargs):
  996. super().__init__(*args, **kwargs)
  997. # Limit rear_port choices to current DeviceType
  998. if hasattr(self.instance, 'device_type'):
  999. self.fields['rear_port'].queryset = RearPortTemplate.objects.filter(
  1000. device_type=self.instance.device_type
  1001. )
  1002. class FrontPortTemplateCreateForm(ComponentForm):
  1003. name_pattern = ExpandableNameField(
  1004. label='Name'
  1005. )
  1006. type = forms.ChoiceField(
  1007. choices=PortTypeChoices,
  1008. widget=StaticSelect2()
  1009. )
  1010. rear_port_set = forms.MultipleChoiceField(
  1011. choices=[],
  1012. label='Rear ports',
  1013. help_text='Select one rear port assignment for each front port being created.',
  1014. )
  1015. def __init__(self, *args, **kwargs):
  1016. super().__init__(*args, **kwargs)
  1017. # Determine which rear port positions are occupied. These will be excluded from the list of available mappings.
  1018. occupied_port_positions = [
  1019. (front_port.rear_port_id, front_port.rear_port_position)
  1020. for front_port in self.parent.frontport_templates.all()
  1021. ]
  1022. # Populate rear port choices
  1023. choices = []
  1024. rear_ports = RearPortTemplate.objects.filter(device_type=self.parent)
  1025. for rear_port in rear_ports:
  1026. for i in range(1, rear_port.positions + 1):
  1027. if (rear_port.pk, i) not in occupied_port_positions:
  1028. choices.append(
  1029. ('{}:{}'.format(rear_port.pk, i), '{}:{}'.format(rear_port.name, i))
  1030. )
  1031. self.fields['rear_port_set'].choices = choices
  1032. def clean(self):
  1033. # Validate that the number of ports being created equals the number of selected (rear port, position) tuples
  1034. front_port_count = len(self.cleaned_data['name_pattern'])
  1035. rear_port_count = len(self.cleaned_data['rear_port_set'])
  1036. if front_port_count != rear_port_count:
  1037. raise forms.ValidationError({
  1038. 'rear_port_set': 'The provided name pattern will create {} ports, however {} rear port assignments '
  1039. 'were selected. These counts must match.'.format(front_port_count, rear_port_count)
  1040. })
  1041. def get_iterative_data(self, iteration):
  1042. # Assign rear port and position from selected set
  1043. rear_port, position = self.cleaned_data['rear_port_set'][iteration].split(':')
  1044. return {
  1045. 'rear_port': int(rear_port),
  1046. 'rear_port_position': int(position),
  1047. }
  1048. class RearPortTemplateForm(BootstrapMixin, forms.ModelForm):
  1049. class Meta:
  1050. model = RearPortTemplate
  1051. fields = [
  1052. 'device_type', 'name', 'type', 'positions',
  1053. ]
  1054. widgets = {
  1055. 'device_type': forms.HiddenInput(),
  1056. 'type': StaticSelect2(),
  1057. }
  1058. class RearPortTemplateCreateForm(ComponentForm):
  1059. name_pattern = ExpandableNameField(
  1060. label='Name'
  1061. )
  1062. type = forms.ChoiceField(
  1063. choices=PortTypeChoices,
  1064. widget=StaticSelect2(),
  1065. )
  1066. positions = forms.IntegerField(
  1067. min_value=1,
  1068. max_value=64,
  1069. initial=1,
  1070. help_text='The number of front ports which may be mapped to each rear port'
  1071. )
  1072. class DeviceBayTemplateForm(BootstrapMixin, forms.ModelForm):
  1073. class Meta:
  1074. model = DeviceBayTemplate
  1075. fields = [
  1076. 'device_type', 'name',
  1077. ]
  1078. widgets = {
  1079. 'device_type': forms.HiddenInput(),
  1080. }
  1081. class DeviceBayTemplateCreateForm(ComponentForm):
  1082. name_pattern = ExpandableNameField(
  1083. label='Name'
  1084. )
  1085. #
  1086. # Component template import forms
  1087. #
  1088. class ComponentTemplateImportForm(BootstrapMixin, forms.ModelForm):
  1089. def __init__(self, device_type, data=None, *args, **kwargs):
  1090. # Must pass the parent DeviceType on form initialization
  1091. data.update({
  1092. 'device_type': device_type.pk,
  1093. })
  1094. super().__init__(data, *args, **kwargs)
  1095. def clean_device_type(self):
  1096. data = self.cleaned_data['device_type']
  1097. # Limit fields referencing other components to the parent DeviceType
  1098. for field_name, field in self.fields.items():
  1099. if isinstance(field, forms.ModelChoiceField) and field_name != 'device_type':
  1100. field.queryset = field.queryset.filter(device_type=data)
  1101. return data
  1102. class ConsolePortTemplateImportForm(ComponentTemplateImportForm):
  1103. class Meta:
  1104. model = ConsolePortTemplate
  1105. fields = [
  1106. 'device_type', 'name', 'type',
  1107. ]
  1108. class ConsoleServerPortTemplateImportForm(ComponentTemplateImportForm):
  1109. class Meta:
  1110. model = ConsoleServerPortTemplate
  1111. fields = [
  1112. 'device_type', 'name', 'type',
  1113. ]
  1114. class PowerPortTemplateImportForm(ComponentTemplateImportForm):
  1115. class Meta:
  1116. model = PowerPortTemplate
  1117. fields = [
  1118. 'device_type', 'name', 'type', 'maximum_draw', 'allocated_draw',
  1119. ]
  1120. class PowerOutletTemplateImportForm(ComponentTemplateImportForm):
  1121. power_port = forms.ModelChoiceField(
  1122. queryset=PowerPortTemplate.objects.all(),
  1123. to_field_name='name',
  1124. required=False
  1125. )
  1126. class Meta:
  1127. model = PowerOutletTemplate
  1128. fields = [
  1129. 'device_type', 'name', 'type', 'power_port', 'feed_leg',
  1130. ]
  1131. class InterfaceTemplateImportForm(ComponentTemplateImportForm):
  1132. type = forms.ChoiceField(
  1133. choices=InterfaceTypeChoices.CHOICES
  1134. )
  1135. class Meta:
  1136. model = InterfaceTemplate
  1137. fields = [
  1138. 'device_type', 'name', 'type', 'mgmt_only',
  1139. ]
  1140. class FrontPortTemplateImportForm(ComponentTemplateImportForm):
  1141. type = forms.ChoiceField(
  1142. choices=PortTypeChoices.CHOICES
  1143. )
  1144. rear_port = forms.ModelChoiceField(
  1145. queryset=RearPortTemplate.objects.all(),
  1146. to_field_name='name',
  1147. required=False
  1148. )
  1149. class Meta:
  1150. model = FrontPortTemplate
  1151. fields = [
  1152. 'device_type', 'name', 'type', 'rear_port', 'rear_port_position',
  1153. ]
  1154. class RearPortTemplateImportForm(ComponentTemplateImportForm):
  1155. type = forms.ChoiceField(
  1156. choices=PortTypeChoices.CHOICES
  1157. )
  1158. class Meta:
  1159. model = RearPortTemplate
  1160. fields = [
  1161. 'device_type', 'name', 'type', 'positions',
  1162. ]
  1163. class DeviceBayTemplateImportForm(ComponentTemplateImportForm):
  1164. class Meta:
  1165. model = DeviceBayTemplate
  1166. fields = [
  1167. 'device_type', 'name',
  1168. ]
  1169. #
  1170. # Device roles
  1171. #
  1172. class DeviceRoleForm(BootstrapMixin, forms.ModelForm):
  1173. slug = SlugField()
  1174. class Meta:
  1175. model = DeviceRole
  1176. fields = [
  1177. 'name', 'slug', 'color', 'vm_role', 'description',
  1178. ]
  1179. class DeviceRoleCSVForm(forms.ModelForm):
  1180. slug = SlugField()
  1181. class Meta:
  1182. model = DeviceRole
  1183. fields = DeviceRole.csv_headers
  1184. help_texts = {
  1185. 'name': 'Name of device role',
  1186. 'color': 'RGB color in hexadecimal (e.g. 00ff00)'
  1187. }
  1188. #
  1189. # Platforms
  1190. #
  1191. class PlatformForm(BootstrapMixin, forms.ModelForm):
  1192. slug = SlugField(
  1193. max_length=64
  1194. )
  1195. class Meta:
  1196. model = Platform
  1197. fields = [
  1198. 'name', 'slug', 'manufacturer', 'napalm_driver', 'napalm_args',
  1199. ]
  1200. widgets = {
  1201. 'manufacturer': APISelect(
  1202. api_url="/api/dcim/manufacturers/"
  1203. ),
  1204. 'napalm_args': SmallTextarea(),
  1205. }
  1206. class PlatformCSVForm(forms.ModelForm):
  1207. slug = SlugField()
  1208. manufacturer = forms.ModelChoiceField(
  1209. queryset=Manufacturer.objects.all(),
  1210. required=False,
  1211. to_field_name='name',
  1212. help_text='Manufacturer name',
  1213. error_messages={
  1214. 'invalid_choice': 'Manufacturer not found.',
  1215. }
  1216. )
  1217. class Meta:
  1218. model = Platform
  1219. fields = Platform.csv_headers
  1220. help_texts = {
  1221. 'name': 'Platform name',
  1222. }
  1223. #
  1224. # Devices
  1225. #
  1226. class DeviceForm(BootstrapMixin, TenancyForm, CustomFieldForm):
  1227. site = forms.ModelChoiceField(
  1228. queryset=Site.objects.all(),
  1229. widget=APISelect(
  1230. api_url="/api/dcim/sites/",
  1231. filter_for={
  1232. 'rack': 'site_id'
  1233. }
  1234. )
  1235. )
  1236. rack = ChainedModelChoiceField(
  1237. queryset=Rack.objects.all(),
  1238. chains=(
  1239. ('site', 'site'),
  1240. ),
  1241. required=False,
  1242. widget=APISelect(
  1243. api_url='/api/dcim/racks/',
  1244. display_field='display_name'
  1245. )
  1246. )
  1247. position = forms.TypedChoiceField(
  1248. required=False,
  1249. empty_value=None,
  1250. help_text="The lowest-numbered unit occupied by the device",
  1251. widget=APISelect(
  1252. api_url='/api/dcim/racks/{{rack}}/elevation/',
  1253. disabled_indicator='device'
  1254. )
  1255. )
  1256. manufacturer = forms.ModelChoiceField(
  1257. queryset=Manufacturer.objects.all(),
  1258. widget=APISelect(
  1259. api_url="/api/dcim/manufacturers/",
  1260. filter_for={
  1261. 'device_type': 'manufacturer_id'
  1262. }
  1263. )
  1264. )
  1265. device_type = ChainedModelChoiceField(
  1266. queryset=DeviceType.objects.all(),
  1267. chains=(
  1268. ('manufacturer', 'manufacturer'),
  1269. ),
  1270. label='Device type',
  1271. widget=APISelect(
  1272. api_url='/api/dcim/device-types/',
  1273. display_field='model'
  1274. )
  1275. )
  1276. cluster_group = forms.ModelChoiceField(
  1277. queryset=ClusterGroup.objects.all(),
  1278. required=False,
  1279. widget=APISelect(
  1280. api_url="/api/virtualization/cluster-groups/",
  1281. filter_for={
  1282. 'cluster': 'group_id'
  1283. },
  1284. attrs={
  1285. 'nullable': 'true'
  1286. }
  1287. )
  1288. )
  1289. cluster = ChainedModelChoiceField(
  1290. queryset=Cluster.objects.all(),
  1291. chains=(
  1292. ('group', 'cluster_group'),
  1293. ),
  1294. required=False,
  1295. widget=APISelect(
  1296. api_url='/api/virtualization/clusters/',
  1297. )
  1298. )
  1299. comments = CommentField()
  1300. tags = TagField(required=False)
  1301. local_context_data = JSONField(
  1302. required=False,
  1303. label=''
  1304. )
  1305. class Meta:
  1306. model = Device
  1307. fields = [
  1308. 'name', 'device_role', 'device_type', 'serial', 'asset_tag', 'site', 'rack', 'position', 'face',
  1309. 'status', 'platform', 'primary_ip4', 'primary_ip6', 'cluster_group', 'cluster', 'tenant_group', 'tenant',
  1310. 'comments', 'tags', 'local_context_data'
  1311. ]
  1312. help_texts = {
  1313. 'device_role': "The function this device serves",
  1314. 'serial': "Chassis serial number",
  1315. 'local_context_data': "Local config context data overwrites all source contexts in the final rendered "
  1316. "config context",
  1317. }
  1318. widgets = {
  1319. 'face': StaticSelect2(
  1320. filter_for={
  1321. 'position': 'face'
  1322. }
  1323. ),
  1324. 'device_role': APISelect(
  1325. api_url='/api/dcim/device-roles/'
  1326. ),
  1327. 'status': StaticSelect2(),
  1328. 'platform': APISelect(
  1329. api_url="/api/dcim/platforms/"
  1330. ),
  1331. 'primary_ip4': StaticSelect2(),
  1332. 'primary_ip6': StaticSelect2(),
  1333. }
  1334. def __init__(self, *args, **kwargs):
  1335. # Initialize helper selectors
  1336. instance = kwargs.get('instance')
  1337. if 'initial' not in kwargs:
  1338. kwargs['initial'] = {}
  1339. # Using hasattr() instead of "is not None" to avoid RelatedObjectDoesNotExist on required field
  1340. if instance and hasattr(instance, 'device_type'):
  1341. kwargs['initial']['manufacturer'] = instance.device_type.manufacturer
  1342. if instance and instance.cluster is not None:
  1343. kwargs['initial']['cluster_group'] = instance.cluster.group
  1344. super().__init__(*args, **kwargs)
  1345. if self.instance.pk:
  1346. # Compile list of choices for primary IPv4 and IPv6 addresses
  1347. for family in [4, 6]:
  1348. ip_choices = [(None, '---------')]
  1349. # Gather PKs of all interfaces belonging to this Device or a peer VirtualChassis member
  1350. interface_ids = self.instance.vc_interfaces.values('pk')
  1351. # Collect interface IPs
  1352. interface_ips = IPAddress.objects.prefetch_related('interface').filter(
  1353. family=family, interface_id__in=interface_ids
  1354. )
  1355. if interface_ips:
  1356. ip_list = [(ip.id, '{} ({})'.format(ip.address, ip.interface)) for ip in interface_ips]
  1357. ip_choices.append(('Interface IPs', ip_list))
  1358. # Collect NAT IPs
  1359. nat_ips = IPAddress.objects.prefetch_related('nat_inside').filter(
  1360. family=family, nat_inside__interface__in=interface_ids
  1361. )
  1362. if nat_ips:
  1363. ip_list = [(ip.id, '{} ({})'.format(ip.address, ip.nat_inside.address)) for ip in nat_ips]
  1364. ip_choices.append(('NAT IPs', ip_list))
  1365. self.fields['primary_ip{}'.format(family)].choices = ip_choices
  1366. # If editing an existing device, exclude it from the list of occupied rack units. This ensures that a device
  1367. # can be flipped from one face to another.
  1368. self.fields['position'].widget.add_additional_query_param('exclude', self.instance.pk)
  1369. # Limit platform by manufacturer
  1370. self.fields['platform'].queryset = Platform.objects.filter(
  1371. Q(manufacturer__isnull=True) | Q(manufacturer=self.instance.device_type.manufacturer)
  1372. )
  1373. else:
  1374. # An object that doesn't exist yet can't have any IPs assigned to it
  1375. self.fields['primary_ip4'].choices = []
  1376. self.fields['primary_ip4'].widget.attrs['readonly'] = True
  1377. self.fields['primary_ip6'].choices = []
  1378. self.fields['primary_ip6'].widget.attrs['readonly'] = True
  1379. # Rack position
  1380. pk = self.instance.pk if self.instance.pk else None
  1381. try:
  1382. if self.is_bound and self.data.get('rack') and str(self.data.get('face')):
  1383. position_choices = Rack.objects.get(pk=self.data['rack']) \
  1384. .get_rack_units(face=self.data.get('face'), exclude=pk)
  1385. elif self.initial.get('rack') and str(self.initial.get('face')):
  1386. position_choices = Rack.objects.get(pk=self.initial['rack']) \
  1387. .get_rack_units(face=self.initial.get('face'), exclude=pk)
  1388. else:
  1389. position_choices = []
  1390. except Rack.DoesNotExist:
  1391. position_choices = []
  1392. self.fields['position'].choices = [('', '---------')] + [
  1393. (p['id'], {
  1394. 'label': p['name'],
  1395. 'disabled': bool(p['device'] and p['id'] != self.initial.get('position')),
  1396. }) for p in position_choices
  1397. ]
  1398. # Disable rack assignment if this is a child device installed in a parent device
  1399. if pk and self.instance.device_type.is_child_device and hasattr(self.instance, 'parent_bay'):
  1400. self.fields['site'].disabled = True
  1401. self.fields['rack'].disabled = True
  1402. self.initial['site'] = self.instance.parent_bay.device.site_id
  1403. self.initial['rack'] = self.instance.parent_bay.device.rack_id
  1404. class BaseDeviceCSVForm(forms.ModelForm):
  1405. device_role = forms.ModelChoiceField(
  1406. queryset=DeviceRole.objects.all(),
  1407. to_field_name='name',
  1408. help_text='Name of assigned role',
  1409. error_messages={
  1410. 'invalid_choice': 'Invalid device role.',
  1411. }
  1412. )
  1413. tenant = forms.ModelChoiceField(
  1414. queryset=Tenant.objects.all(),
  1415. required=False,
  1416. to_field_name='name',
  1417. help_text='Name of assigned tenant',
  1418. error_messages={
  1419. 'invalid_choice': 'Tenant not found.',
  1420. }
  1421. )
  1422. manufacturer = forms.ModelChoiceField(
  1423. queryset=Manufacturer.objects.all(),
  1424. to_field_name='name',
  1425. help_text='Device type manufacturer',
  1426. error_messages={
  1427. 'invalid_choice': 'Invalid manufacturer.',
  1428. }
  1429. )
  1430. model_name = forms.CharField(
  1431. help_text='Device type model name'
  1432. )
  1433. platform = forms.ModelChoiceField(
  1434. queryset=Platform.objects.all(),
  1435. required=False,
  1436. to_field_name='name',
  1437. help_text='Name of assigned platform',
  1438. error_messages={
  1439. 'invalid_choice': 'Invalid platform.',
  1440. }
  1441. )
  1442. status = CSVChoiceField(
  1443. choices=DeviceStatusChoices,
  1444. help_text='Operational status'
  1445. )
  1446. class Meta:
  1447. fields = []
  1448. model = Device
  1449. help_texts = {
  1450. 'name': 'Device name',
  1451. }
  1452. def clean(self):
  1453. super().clean()
  1454. manufacturer = self.cleaned_data.get('manufacturer')
  1455. model_name = self.cleaned_data.get('model_name')
  1456. # Validate device type
  1457. if manufacturer and model_name:
  1458. try:
  1459. self.instance.device_type = DeviceType.objects.get(manufacturer=manufacturer, model=model_name)
  1460. except DeviceType.DoesNotExist:
  1461. raise forms.ValidationError("Device type {} {} not found".format(manufacturer, model_name))
  1462. class DeviceCSVForm(BaseDeviceCSVForm):
  1463. site = forms.ModelChoiceField(
  1464. queryset=Site.objects.all(),
  1465. to_field_name='name',
  1466. help_text='Name of parent site',
  1467. error_messages={
  1468. 'invalid_choice': 'Invalid site name.',
  1469. }
  1470. )
  1471. rack_group = forms.CharField(
  1472. required=False,
  1473. help_text='Parent rack\'s group (if any)'
  1474. )
  1475. rack_name = forms.CharField(
  1476. required=False,
  1477. help_text='Name of parent rack'
  1478. )
  1479. face = CSVChoiceField(
  1480. choices=DeviceFaceChoices,
  1481. required=False,
  1482. help_text='Mounted rack face'
  1483. )
  1484. cluster = forms.ModelChoiceField(
  1485. queryset=Cluster.objects.all(),
  1486. to_field_name='name',
  1487. required=False,
  1488. help_text='Virtualization cluster',
  1489. error_messages={
  1490. 'invalid_choice': 'Invalid cluster name.',
  1491. }
  1492. )
  1493. class Meta(BaseDeviceCSVForm.Meta):
  1494. fields = [
  1495. 'name', 'device_role', 'tenant', 'manufacturer', 'model_name', 'platform', 'serial', 'asset_tag', 'status',
  1496. 'site', 'rack_group', 'rack_name', 'position', 'face', 'cluster', 'comments',
  1497. ]
  1498. def clean(self):
  1499. super().clean()
  1500. site = self.cleaned_data.get('site')
  1501. rack_group = self.cleaned_data.get('rack_group')
  1502. rack_name = self.cleaned_data.get('rack_name')
  1503. # Validate rack
  1504. if site and rack_group and rack_name:
  1505. try:
  1506. self.instance.rack = Rack.objects.get(site=site, group__name=rack_group, name=rack_name)
  1507. except Rack.DoesNotExist:
  1508. raise forms.ValidationError("Rack {} not found in site {} group {}".format(rack_name, site, rack_group))
  1509. elif site and rack_name:
  1510. try:
  1511. self.instance.rack = Rack.objects.get(site=site, group__isnull=True, name=rack_name)
  1512. except Rack.DoesNotExist:
  1513. raise forms.ValidationError("Rack {} not found in site {} (no group)".format(rack_name, site))
  1514. class ChildDeviceCSVForm(BaseDeviceCSVForm):
  1515. parent = FlexibleModelChoiceField(
  1516. queryset=Device.objects.all(),
  1517. to_field_name='name',
  1518. help_text='Name or ID of parent device',
  1519. error_messages={
  1520. 'invalid_choice': 'Parent device not found.',
  1521. }
  1522. )
  1523. device_bay_name = forms.CharField(
  1524. help_text='Name of device bay',
  1525. )
  1526. cluster = forms.ModelChoiceField(
  1527. queryset=Cluster.objects.all(),
  1528. to_field_name='name',
  1529. required=False,
  1530. help_text='Virtualization cluster',
  1531. error_messages={
  1532. 'invalid_choice': 'Invalid cluster name.',
  1533. }
  1534. )
  1535. class Meta(BaseDeviceCSVForm.Meta):
  1536. fields = [
  1537. 'name', 'device_role', 'tenant', 'manufacturer', 'model_name', 'platform', 'serial', 'asset_tag', 'status',
  1538. 'parent', 'device_bay_name', 'cluster', 'comments',
  1539. ]
  1540. def clean(self):
  1541. super().clean()
  1542. parent = self.cleaned_data.get('parent')
  1543. device_bay_name = self.cleaned_data.get('device_bay_name')
  1544. # Validate device bay
  1545. if parent and device_bay_name:
  1546. try:
  1547. self.instance.parent_bay = DeviceBay.objects.get(device=parent, name=device_bay_name)
  1548. # Inherit site and rack from parent device
  1549. self.instance.site = parent.site
  1550. self.instance.rack = parent.rack
  1551. except DeviceBay.DoesNotExist:
  1552. raise forms.ValidationError("Parent device/bay ({} {}) not found".format(parent, device_bay_name))
  1553. class DeviceBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldBulkEditForm):
  1554. pk = forms.ModelMultipleChoiceField(
  1555. queryset=Device.objects.all(),
  1556. widget=forms.MultipleHiddenInput()
  1557. )
  1558. device_type = forms.ModelChoiceField(
  1559. queryset=DeviceType.objects.all(),
  1560. required=False,
  1561. label='Type',
  1562. widget=APISelect(
  1563. api_url="/api/dcim/device-types/",
  1564. display_field='display_name'
  1565. )
  1566. )
  1567. device_role = forms.ModelChoiceField(
  1568. queryset=DeviceRole.objects.all(),
  1569. required=False,
  1570. label='Role',
  1571. widget=APISelect(
  1572. api_url="/api/dcim/device-roles/"
  1573. )
  1574. )
  1575. tenant = forms.ModelChoiceField(
  1576. queryset=Tenant.objects.all(),
  1577. required=False,
  1578. widget=APISelect(
  1579. api_url="/api/tenancy/tenants/"
  1580. )
  1581. )
  1582. platform = forms.ModelChoiceField(
  1583. queryset=Platform.objects.all(),
  1584. required=False,
  1585. widget=APISelect(
  1586. api_url="/api/dcim/platforms/"
  1587. )
  1588. )
  1589. status = forms.ChoiceField(
  1590. choices=add_blank_choice(DeviceStatusChoices),
  1591. required=False,
  1592. initial='',
  1593. widget=StaticSelect2()
  1594. )
  1595. serial = forms.CharField(
  1596. max_length=50,
  1597. required=False,
  1598. label='Serial Number'
  1599. )
  1600. class Meta:
  1601. nullable_fields = [
  1602. 'tenant', 'platform', 'serial',
  1603. ]
  1604. class DeviceFilterForm(BootstrapMixin, LocalConfigContextFilterForm, TenancyFilterForm, CustomFieldFilterForm):
  1605. model = Device
  1606. field_order = [
  1607. 'q', 'region', 'site', 'rack_group_id', 'rack_id', 'status', 'role', 'tenant_group', 'tenant',
  1608. 'manufacturer_id', 'device_type_id', 'mac_address', 'has_primary_ip',
  1609. ]
  1610. q = forms.CharField(
  1611. required=False,
  1612. label='Search'
  1613. )
  1614. region = FilterChoiceField(
  1615. queryset=Region.objects.all(),
  1616. to_field_name='slug',
  1617. required=False,
  1618. widget=APISelectMultiple(
  1619. api_url="/api/dcim/regions/",
  1620. value_field="slug",
  1621. filter_for={
  1622. 'site': 'region'
  1623. }
  1624. )
  1625. )
  1626. site = FilterChoiceField(
  1627. queryset=Site.objects.all(),
  1628. to_field_name='slug',
  1629. widget=APISelectMultiple(
  1630. api_url="/api/dcim/sites/",
  1631. value_field="slug",
  1632. filter_for={
  1633. 'rack_group_id': 'site',
  1634. 'rack_id': 'site',
  1635. }
  1636. )
  1637. )
  1638. rack_group_id = FilterChoiceField(
  1639. queryset=RackGroup.objects.prefetch_related(
  1640. 'site'
  1641. ),
  1642. label='Rack group',
  1643. widget=APISelectMultiple(
  1644. api_url="/api/dcim/rack-groups/",
  1645. filter_for={
  1646. 'rack_id': 'rack_group_id',
  1647. }
  1648. )
  1649. )
  1650. rack_id = FilterChoiceField(
  1651. queryset=Rack.objects.all(),
  1652. label='Rack',
  1653. null_label='-- None --',
  1654. widget=APISelectMultiple(
  1655. api_url="/api/dcim/racks/",
  1656. null_option=True,
  1657. )
  1658. )
  1659. role = FilterChoiceField(
  1660. queryset=DeviceRole.objects.all(),
  1661. to_field_name='slug',
  1662. widget=APISelectMultiple(
  1663. api_url="/api/dcim/device-roles/",
  1664. value_field="slug",
  1665. )
  1666. )
  1667. manufacturer_id = FilterChoiceField(
  1668. queryset=Manufacturer.objects.all(),
  1669. label='Manufacturer',
  1670. widget=APISelectMultiple(
  1671. api_url="/api/dcim/manufacturers/",
  1672. filter_for={
  1673. 'device_type_id': 'manufacturer_id',
  1674. }
  1675. )
  1676. )
  1677. device_type_id = FilterChoiceField(
  1678. queryset=DeviceType.objects.prefetch_related(
  1679. 'manufacturer'
  1680. ),
  1681. label='Model',
  1682. widget=APISelectMultiple(
  1683. api_url="/api/dcim/device-types/",
  1684. display_field="model",
  1685. )
  1686. )
  1687. platform = FilterChoiceField(
  1688. queryset=Platform.objects.all(),
  1689. to_field_name='slug',
  1690. null_label='-- None --',
  1691. widget=APISelectMultiple(
  1692. api_url="/api/dcim/platforms/",
  1693. value_field="slug",
  1694. null_option=True,
  1695. )
  1696. )
  1697. status = forms.MultipleChoiceField(
  1698. choices=DeviceStatusChoices,
  1699. required=False,
  1700. widget=StaticSelect2Multiple()
  1701. )
  1702. mac_address = forms.CharField(
  1703. required=False,
  1704. label='MAC address'
  1705. )
  1706. has_primary_ip = forms.NullBooleanField(
  1707. required=False,
  1708. label='Has a primary IP',
  1709. widget=StaticSelect2(
  1710. choices=BOOLEAN_WITH_BLANK_CHOICES
  1711. )
  1712. )
  1713. virtual_chassis_member = forms.NullBooleanField(
  1714. required=False,
  1715. label='Virtual chassis member',
  1716. widget=StaticSelect2(
  1717. choices=BOOLEAN_WITH_BLANK_CHOICES
  1718. )
  1719. )
  1720. console_ports = forms.NullBooleanField(
  1721. required=False,
  1722. label='Has console ports',
  1723. widget=StaticSelect2(
  1724. choices=BOOLEAN_WITH_BLANK_CHOICES
  1725. )
  1726. )
  1727. console_server_ports = forms.NullBooleanField(
  1728. required=False,
  1729. label='Has console server ports',
  1730. widget=StaticSelect2(
  1731. choices=BOOLEAN_WITH_BLANK_CHOICES
  1732. )
  1733. )
  1734. power_ports = forms.NullBooleanField(
  1735. required=False,
  1736. label='Has power ports',
  1737. widget=StaticSelect2(
  1738. choices=BOOLEAN_WITH_BLANK_CHOICES
  1739. )
  1740. )
  1741. power_outlets = forms.NullBooleanField(
  1742. required=False,
  1743. label='Has power outlets',
  1744. widget=StaticSelect2(
  1745. choices=BOOLEAN_WITH_BLANK_CHOICES
  1746. )
  1747. )
  1748. interfaces = forms.NullBooleanField(
  1749. required=False,
  1750. label='Has interfaces',
  1751. widget=StaticSelect2(
  1752. choices=BOOLEAN_WITH_BLANK_CHOICES
  1753. )
  1754. )
  1755. pass_through_ports = forms.NullBooleanField(
  1756. required=False,
  1757. label='Has pass-through ports',
  1758. widget=StaticSelect2(
  1759. choices=BOOLEAN_WITH_BLANK_CHOICES
  1760. )
  1761. )
  1762. #
  1763. # Bulk device component creation
  1764. #
  1765. class DeviceBulkAddComponentForm(BootstrapMixin, forms.Form):
  1766. pk = forms.ModelMultipleChoiceField(
  1767. queryset=Device.objects.all(),
  1768. widget=forms.MultipleHiddenInput()
  1769. )
  1770. name_pattern = ExpandableNameField(
  1771. label='Name'
  1772. )
  1773. class DeviceBulkAddInterfaceForm(DeviceBulkAddComponentForm):
  1774. type = forms.ChoiceField(
  1775. choices=InterfaceTypeChoices,
  1776. widget=StaticSelect2()
  1777. )
  1778. enabled = forms.BooleanField(
  1779. required=False,
  1780. initial=True
  1781. )
  1782. mtu = forms.IntegerField(
  1783. required=False,
  1784. min_value=1,
  1785. max_value=32767,
  1786. label='MTU'
  1787. )
  1788. mgmt_only = forms.BooleanField(
  1789. required=False,
  1790. label='Management only'
  1791. )
  1792. description = forms.CharField(
  1793. max_length=100,
  1794. required=False
  1795. )
  1796. #
  1797. # Console ports
  1798. #
  1799. class ConsolePortFilterForm(DeviceComponentFilterForm):
  1800. model = ConsolePort
  1801. class ConsolePortForm(BootstrapMixin, forms.ModelForm):
  1802. tags = TagField(
  1803. required=False
  1804. )
  1805. class Meta:
  1806. model = ConsolePort
  1807. fields = [
  1808. 'device', 'name', 'type', 'description', 'tags',
  1809. ]
  1810. widgets = {
  1811. 'device': forms.HiddenInput(),
  1812. }
  1813. class ConsolePortCreateForm(ComponentForm):
  1814. name_pattern = ExpandableNameField(
  1815. label='Name'
  1816. )
  1817. type = forms.ChoiceField(
  1818. choices=add_blank_choice(ConsolePortTypeChoices),
  1819. required=False,
  1820. widget=StaticSelect2()
  1821. )
  1822. description = forms.CharField(
  1823. max_length=100,
  1824. required=False
  1825. )
  1826. tags = TagField(
  1827. required=False
  1828. )
  1829. class ConsolePortCSVForm(forms.ModelForm):
  1830. device = FlexibleModelChoiceField(
  1831. queryset=Device.objects.all(),
  1832. to_field_name='name',
  1833. help_text='Name or ID of device',
  1834. error_messages={
  1835. 'invalid_choice': 'Device not found.',
  1836. }
  1837. )
  1838. class Meta:
  1839. model = ConsolePort
  1840. fields = ConsolePort.csv_headers
  1841. #
  1842. # Console server ports
  1843. #
  1844. class ConsoleServerPortFilterForm(DeviceComponentFilterForm):
  1845. model = ConsoleServerPort
  1846. class ConsoleServerPortForm(BootstrapMixin, forms.ModelForm):
  1847. tags = TagField(
  1848. required=False
  1849. )
  1850. class Meta:
  1851. model = ConsoleServerPort
  1852. fields = [
  1853. 'device', 'name', 'type', 'description', 'tags',
  1854. ]
  1855. widgets = {
  1856. 'device': forms.HiddenInput(),
  1857. }
  1858. class ConsoleServerPortCreateForm(ComponentForm):
  1859. name_pattern = ExpandableNameField(
  1860. label='Name'
  1861. )
  1862. type = forms.ChoiceField(
  1863. choices=add_blank_choice(ConsolePortTypeChoices),
  1864. required=False,
  1865. widget=StaticSelect2()
  1866. )
  1867. description = forms.CharField(
  1868. max_length=100,
  1869. required=False
  1870. )
  1871. tags = TagField(
  1872. required=False
  1873. )
  1874. class ConsoleServerPortBulkEditForm(BootstrapMixin, AddRemoveTagsForm, BulkEditForm):
  1875. pk = forms.ModelMultipleChoiceField(
  1876. queryset=ConsoleServerPort.objects.all(),
  1877. widget=forms.MultipleHiddenInput()
  1878. )
  1879. type = forms.ChoiceField(
  1880. choices=add_blank_choice(ConsolePortTypeChoices),
  1881. required=False,
  1882. widget=StaticSelect2()
  1883. )
  1884. description = forms.CharField(
  1885. max_length=100,
  1886. required=False
  1887. )
  1888. class Meta:
  1889. nullable_fields = [
  1890. 'description',
  1891. ]
  1892. class ConsoleServerPortBulkRenameForm(BulkRenameForm):
  1893. pk = forms.ModelMultipleChoiceField(
  1894. queryset=ConsoleServerPort.objects.all(),
  1895. widget=forms.MultipleHiddenInput()
  1896. )
  1897. class ConsoleServerPortBulkDisconnectForm(ConfirmationForm):
  1898. pk = forms.ModelMultipleChoiceField(
  1899. queryset=ConsoleServerPort.objects.all(),
  1900. widget=forms.MultipleHiddenInput()
  1901. )
  1902. class ConsoleServerPortCSVForm(forms.ModelForm):
  1903. device = FlexibleModelChoiceField(
  1904. queryset=Device.objects.all(),
  1905. to_field_name='name',
  1906. help_text='Name or ID of device',
  1907. error_messages={
  1908. 'invalid_choice': 'Device not found.',
  1909. }
  1910. )
  1911. class Meta:
  1912. model = ConsoleServerPort
  1913. fields = ConsoleServerPort.csv_headers
  1914. #
  1915. # Power ports
  1916. #
  1917. class PowerPortFilterForm(DeviceComponentFilterForm):
  1918. model = PowerPort
  1919. class PowerPortForm(BootstrapMixin, forms.ModelForm):
  1920. tags = TagField(
  1921. required=False
  1922. )
  1923. class Meta:
  1924. model = PowerPort
  1925. fields = [
  1926. 'device', 'name', 'type', 'maximum_draw', 'allocated_draw', 'description', 'tags',
  1927. ]
  1928. widgets = {
  1929. 'device': forms.HiddenInput(),
  1930. }
  1931. class PowerPortCreateForm(ComponentForm):
  1932. name_pattern = ExpandableNameField(
  1933. label='Name'
  1934. )
  1935. type = forms.ChoiceField(
  1936. choices=add_blank_choice(PowerPortTypeChoices),
  1937. required=False,
  1938. widget=StaticSelect2()
  1939. )
  1940. maximum_draw = forms.IntegerField(
  1941. min_value=1,
  1942. required=False,
  1943. help_text="Maximum draw in watts"
  1944. )
  1945. allocated_draw = forms.IntegerField(
  1946. min_value=1,
  1947. required=False,
  1948. help_text="Allocated draw in watts"
  1949. )
  1950. description = forms.CharField(
  1951. max_length=100,
  1952. required=False
  1953. )
  1954. tags = TagField(
  1955. required=False
  1956. )
  1957. class PowerPortCSVForm(forms.ModelForm):
  1958. device = FlexibleModelChoiceField(
  1959. queryset=Device.objects.all(),
  1960. to_field_name='name',
  1961. help_text='Name or ID of device',
  1962. error_messages={
  1963. 'invalid_choice': 'Device not found.',
  1964. }
  1965. )
  1966. class Meta:
  1967. model = PowerPort
  1968. fields = PowerPort.csv_headers
  1969. #
  1970. # Power outlets
  1971. #
  1972. class PowerOutletFilterForm(DeviceComponentFilterForm):
  1973. model = PowerOutlet
  1974. class PowerOutletForm(BootstrapMixin, forms.ModelForm):
  1975. power_port = forms.ModelChoiceField(
  1976. queryset=PowerPort.objects.all(),
  1977. required=False
  1978. )
  1979. tags = TagField(
  1980. required=False
  1981. )
  1982. class Meta:
  1983. model = PowerOutlet
  1984. fields = [
  1985. 'device', 'name', 'type', 'power_port', 'feed_leg', 'description', 'tags',
  1986. ]
  1987. widgets = {
  1988. 'device': forms.HiddenInput(),
  1989. }
  1990. def __init__(self, *args, **kwargs):
  1991. super().__init__(*args, **kwargs)
  1992. # Limit power_port choices to the local device
  1993. if hasattr(self.instance, 'device'):
  1994. self.fields['power_port'].queryset = PowerPort.objects.filter(
  1995. device=self.instance.device
  1996. )
  1997. class PowerOutletCreateForm(ComponentForm):
  1998. name_pattern = ExpandableNameField(
  1999. label='Name'
  2000. )
  2001. type = forms.ChoiceField(
  2002. choices=add_blank_choice(PowerOutletTypeChoices),
  2003. required=False,
  2004. widget=StaticSelect2()
  2005. )
  2006. power_port = forms.ModelChoiceField(
  2007. queryset=PowerPort.objects.all(),
  2008. required=False
  2009. )
  2010. feed_leg = forms.ChoiceField(
  2011. choices=add_blank_choice(PowerOutletFeedLegChoices),
  2012. required=False
  2013. )
  2014. description = forms.CharField(
  2015. max_length=100,
  2016. required=False
  2017. )
  2018. tags = TagField(
  2019. required=False
  2020. )
  2021. def __init__(self, *args, **kwargs):
  2022. super().__init__(*args, **kwargs)
  2023. # Limit power_port choices to those on the parent device
  2024. self.fields['power_port'].queryset = PowerPort.objects.filter(device=self.parent)
  2025. class PowerOutletCSVForm(forms.ModelForm):
  2026. device = FlexibleModelChoiceField(
  2027. queryset=Device.objects.all(),
  2028. to_field_name='name',
  2029. help_text='Name or ID of device',
  2030. error_messages={
  2031. 'invalid_choice': 'Device not found.',
  2032. }
  2033. )
  2034. power_port = FlexibleModelChoiceField(
  2035. queryset=PowerPort.objects.all(),
  2036. required=False,
  2037. to_field_name='name',
  2038. help_text='Name or ID of Power Port',
  2039. error_messages={
  2040. 'invalid_choice': 'Power Port not found.',
  2041. }
  2042. )
  2043. feed_leg = CSVChoiceField(
  2044. choices=PowerOutletFeedLegChoices,
  2045. required=False,
  2046. )
  2047. class Meta:
  2048. model = PowerOutlet
  2049. fields = PowerOutlet.csv_headers
  2050. def __init__(self, *args, **kwargs):
  2051. super().__init__(*args, **kwargs)
  2052. # Limit PowerPort choices to those belonging to this device (or VC master)
  2053. if self.is_bound:
  2054. try:
  2055. device = self.fields['device'].to_python(self.data['device'])
  2056. except forms.ValidationError:
  2057. device = None
  2058. else:
  2059. try:
  2060. device = self.instance.device
  2061. except Device.DoesNotExist:
  2062. device = None
  2063. if device:
  2064. self.fields['power_port'].queryset = PowerPort.objects.filter(
  2065. device__in=[device, device.get_vc_master()]
  2066. )
  2067. else:
  2068. self.fields['power_port'].queryset = PowerPort.objects.none()
  2069. class PowerOutletBulkEditForm(BootstrapMixin, AddRemoveTagsForm, BulkEditForm):
  2070. pk = forms.ModelMultipleChoiceField(
  2071. queryset=PowerOutlet.objects.all(),
  2072. widget=forms.MultipleHiddenInput()
  2073. )
  2074. type = forms.ChoiceField(
  2075. choices=PowerOutletTypeChoices,
  2076. required=False
  2077. )
  2078. feed_leg = forms.ChoiceField(
  2079. choices=add_blank_choice(PowerOutletFeedLegChoices),
  2080. required=False,
  2081. )
  2082. power_port = forms.ModelChoiceField(
  2083. queryset=PowerPort.objects.all(),
  2084. required=False
  2085. )
  2086. description = forms.CharField(
  2087. max_length=100,
  2088. required=False
  2089. )
  2090. class Meta:
  2091. nullable_fields = [
  2092. 'type', 'feed_leg', 'power_port', 'description',
  2093. ]
  2094. def __init__(self, *args, **kwargs):
  2095. super().__init__(*args, **kwargs)
  2096. # Limit power_port queryset to PowerPorts which belong to the parent Device
  2097. self.fields['power_port'].queryset = PowerPort.objects.filter(device=self.parent_obj)
  2098. class PowerOutletBulkRenameForm(BulkRenameForm):
  2099. pk = forms.ModelMultipleChoiceField(
  2100. queryset=PowerOutlet.objects.all(),
  2101. widget=forms.MultipleHiddenInput
  2102. )
  2103. class PowerOutletBulkDisconnectForm(ConfirmationForm):
  2104. pk = forms.ModelMultipleChoiceField(
  2105. queryset=PowerOutlet.objects.all(),
  2106. widget=forms.MultipleHiddenInput
  2107. )
  2108. #
  2109. # Interfaces
  2110. #
  2111. class InterfaceFilterForm(DeviceComponentFilterForm):
  2112. model = Interface
  2113. class InterfaceForm(InterfaceCommonForm, BootstrapMixin, forms.ModelForm):
  2114. untagged_vlan = forms.ModelChoiceField(
  2115. queryset=VLAN.objects.all(),
  2116. required=False,
  2117. widget=APISelect(
  2118. api_url="/api/ipam/vlans/",
  2119. display_field='display_name',
  2120. full=True
  2121. )
  2122. )
  2123. tagged_vlans = forms.ModelMultipleChoiceField(
  2124. queryset=VLAN.objects.all(),
  2125. required=False,
  2126. widget=APISelectMultiple(
  2127. api_url="/api/ipam/vlans/",
  2128. display_field='display_name',
  2129. full=True
  2130. )
  2131. )
  2132. tags = TagField(
  2133. required=False
  2134. )
  2135. class Meta:
  2136. model = Interface
  2137. fields = [
  2138. 'device', 'name', 'type', 'enabled', 'lag', 'mac_address', 'mtu', 'mgmt_only', 'description',
  2139. 'mode', 'untagged_vlan', 'tagged_vlans', 'tags',
  2140. ]
  2141. widgets = {
  2142. 'device': forms.HiddenInput(),
  2143. 'type': StaticSelect2(),
  2144. 'lag': StaticSelect2(),
  2145. 'mode': StaticSelect2(),
  2146. }
  2147. labels = {
  2148. 'mode': '802.1Q Mode',
  2149. }
  2150. help_texts = {
  2151. 'mode': INTERFACE_MODE_HELP_TEXT,
  2152. }
  2153. def __init__(self, *args, **kwargs):
  2154. super().__init__(*args, **kwargs)
  2155. # Limit LAG choices to interfaces belonging to this device (or VC master)
  2156. if self.is_bound:
  2157. device = Device.objects.get(pk=self.data['device'])
  2158. self.fields['lag'].queryset = Interface.objects.filter(
  2159. device__in=[device, device.get_vc_master()],
  2160. type=InterfaceTypeChoices.TYPE_LAG
  2161. )
  2162. else:
  2163. device = self.instance.device
  2164. self.fields['lag'].queryset = Interface.objects.filter(
  2165. device__in=[self.instance.device, self.instance.device.get_vc_master()],
  2166. type=InterfaceTypeChoices.TYPE_LAG
  2167. )
  2168. # Limit VLan choices to those in: global vlans, global groups, the current site's group, the current site
  2169. vlan_choices = []
  2170. global_vlans = VLAN.objects.filter(site=None, group=None)
  2171. vlan_choices.append(
  2172. ('Global', [(vlan.pk, vlan) for vlan in global_vlans])
  2173. )
  2174. for group in VLANGroup.objects.filter(site=None):
  2175. global_group_vlans = VLAN.objects.filter(group=group)
  2176. vlan_choices.append(
  2177. (group.name, [(vlan.pk, vlan) for vlan in global_group_vlans])
  2178. )
  2179. site = getattr(self.instance.parent, 'site', None)
  2180. if site is not None:
  2181. # Add non-grouped site VLANs
  2182. site_vlans = VLAN.objects.filter(site=site, group=None)
  2183. vlan_choices.append((site.name, [(vlan.pk, vlan) for vlan in site_vlans]))
  2184. # Add grouped site VLANs
  2185. for group in VLANGroup.objects.filter(site=site):
  2186. site_group_vlans = VLAN.objects.filter(group=group)
  2187. vlan_choices.append((
  2188. '{} / {}'.format(group.site.name, group.name),
  2189. [(vlan.pk, vlan) for vlan in site_group_vlans]
  2190. ))
  2191. self.fields['untagged_vlan'].choices = [(None, '---------')] + vlan_choices
  2192. self.fields['tagged_vlans'].choices = vlan_choices
  2193. class InterfaceCreateForm(InterfaceCommonForm, ComponentForm, forms.Form):
  2194. name_pattern = ExpandableNameField(
  2195. label='Name'
  2196. )
  2197. type = forms.ChoiceField(
  2198. choices=InterfaceTypeChoices,
  2199. widget=StaticSelect2(),
  2200. )
  2201. enabled = forms.BooleanField(
  2202. required=False
  2203. )
  2204. lag = forms.ModelChoiceField(
  2205. queryset=Interface.objects.all(),
  2206. required=False,
  2207. label='Parent LAG',
  2208. widget=StaticSelect2(),
  2209. )
  2210. mtu = forms.IntegerField(
  2211. required=False,
  2212. min_value=1,
  2213. max_value=32767,
  2214. label='MTU'
  2215. )
  2216. mac_address = forms.CharField(
  2217. required=False,
  2218. label='MAC Address'
  2219. )
  2220. mgmt_only = forms.BooleanField(
  2221. required=False,
  2222. label='Management only',
  2223. help_text='This interface is used only for out-of-band management'
  2224. )
  2225. description = forms.CharField(
  2226. max_length=100,
  2227. required=False
  2228. )
  2229. mode = forms.ChoiceField(
  2230. choices=add_blank_choice(InterfaceModeChoices),
  2231. required=False,
  2232. widget=StaticSelect2(),
  2233. )
  2234. tags = TagField(
  2235. required=False
  2236. )
  2237. untagged_vlan = forms.ModelChoiceField(
  2238. queryset=VLAN.objects.all(),
  2239. required=False,
  2240. widget=APISelect(
  2241. api_url="/api/ipam/vlans/",
  2242. display_field='display_name',
  2243. full=True
  2244. )
  2245. )
  2246. tagged_vlans = forms.ModelMultipleChoiceField(
  2247. queryset=VLAN.objects.all(),
  2248. required=False,
  2249. widget=APISelectMultiple(
  2250. api_url="/api/ipam/vlans/",
  2251. display_field='display_name',
  2252. full=True
  2253. )
  2254. )
  2255. def __init__(self, *args, **kwargs):
  2256. # Set interfaces enabled by default
  2257. kwargs['initial'] = kwargs.get('initial', {}).copy()
  2258. kwargs['initial'].update({'enabled': True})
  2259. super().__init__(*args, **kwargs)
  2260. # Limit LAG choices to interfaces belonging to this device (or its VC master)
  2261. if self.parent is not None:
  2262. self.fields['lag'].queryset = Interface.objects.filter(
  2263. device__in=[self.parent, self.parent.get_vc_master()],
  2264. type=InterfaceTypeChoices.TYPE_LAG
  2265. )
  2266. else:
  2267. self.fields['lag'].queryset = Interface.objects.none()
  2268. # Limit VLan choices to those in: global vlans, global groups, the current site's group, the current site
  2269. vlan_choices = []
  2270. global_vlans = VLAN.objects.filter(site=None, group=None)
  2271. vlan_choices.append(
  2272. ('Global', [(vlan.pk, vlan) for vlan in global_vlans])
  2273. )
  2274. for group in VLANGroup.objects.filter(site=None):
  2275. global_group_vlans = VLAN.objects.filter(group=group)
  2276. vlan_choices.append(
  2277. (group.name, [(vlan.pk, vlan) for vlan in global_group_vlans])
  2278. )
  2279. site = getattr(self.parent, 'site', None)
  2280. if site is not None:
  2281. # Add non-grouped site VLANs
  2282. site_vlans = VLAN.objects.filter(site=site, group=None)
  2283. vlan_choices.append((site.name, [(vlan.pk, vlan) for vlan in site_vlans]))
  2284. # Add grouped site VLANs
  2285. for group in VLANGroup.objects.filter(site=site):
  2286. site_group_vlans = VLAN.objects.filter(group=group)
  2287. vlan_choices.append((
  2288. '{} / {}'.format(group.site.name, group.name),
  2289. [(vlan.pk, vlan) for vlan in site_group_vlans]
  2290. ))
  2291. self.fields['untagged_vlan'].choices = [(None, '---------')] + vlan_choices
  2292. self.fields['tagged_vlans'].choices = vlan_choices
  2293. class InterfaceCSVForm(forms.ModelForm):
  2294. device = FlexibleModelChoiceField(
  2295. queryset=Device.objects.all(),
  2296. required=False,
  2297. to_field_name='name',
  2298. help_text='Name or ID of device',
  2299. error_messages={
  2300. 'invalid_choice': 'Device not found.',
  2301. }
  2302. )
  2303. virtual_machine = FlexibleModelChoiceField(
  2304. queryset=VirtualMachine.objects.all(),
  2305. required=False,
  2306. to_field_name='name',
  2307. help_text='Name or ID of virtual machine',
  2308. error_messages={
  2309. 'invalid_choice': 'Virtual machine not found.',
  2310. }
  2311. )
  2312. lag = FlexibleModelChoiceField(
  2313. queryset=Interface.objects.all(),
  2314. required=False,
  2315. to_field_name='name',
  2316. help_text='Name or ID of LAG interface',
  2317. error_messages={
  2318. 'invalid_choice': 'LAG interface not found.',
  2319. }
  2320. )
  2321. type = CSVChoiceField(
  2322. choices=InterfaceTypeChoices,
  2323. )
  2324. mode = CSVChoiceField(
  2325. choices=InterfaceModeChoices,
  2326. required=False,
  2327. )
  2328. class Meta:
  2329. model = Interface
  2330. fields = Interface.csv_headers
  2331. def __init__(self, *args, **kwargs):
  2332. super().__init__(*args, **kwargs)
  2333. # Limit LAG choices to interfaces belonging to this device (or VC master)
  2334. if self.is_bound:
  2335. try:
  2336. device = self.fields['device'].to_python(self.data['device'])
  2337. except forms.ValidationError:
  2338. device = None
  2339. else:
  2340. device = self.instance.device
  2341. if device:
  2342. self.fields['lag'].queryset = Interface.objects.filter(
  2343. device__in=[device, device.get_vc_master()], type=InterfaceTypeChoices.TYPE_LAG
  2344. )
  2345. else:
  2346. self.fields['lag'].queryset = Interface.objects.none()
  2347. def clean_enabled(self):
  2348. # Make sure enabled is True when it's not included in the uploaded data
  2349. if 'enabled' not in self.data:
  2350. return True
  2351. else:
  2352. return self.cleaned_data['enabled']
  2353. class InterfaceBulkEditForm(InterfaceCommonForm, BootstrapMixin, AddRemoveTagsForm, BulkEditForm):
  2354. pk = forms.ModelMultipleChoiceField(
  2355. queryset=Interface.objects.all(),
  2356. widget=forms.MultipleHiddenInput()
  2357. )
  2358. type = forms.ChoiceField(
  2359. choices=add_blank_choice(InterfaceTypeChoices),
  2360. required=False,
  2361. widget=StaticSelect2()
  2362. )
  2363. enabled = forms.NullBooleanField(
  2364. required=False,
  2365. widget=BulkEditNullBooleanSelect()
  2366. )
  2367. lag = forms.ModelChoiceField(
  2368. queryset=Interface.objects.all(),
  2369. required=False,
  2370. label='Parent LAG',
  2371. widget=StaticSelect2()
  2372. )
  2373. mac_address = forms.CharField(
  2374. required=False,
  2375. label='MAC Address'
  2376. )
  2377. mtu = forms.IntegerField(
  2378. required=False,
  2379. min_value=1,
  2380. max_value=32767,
  2381. label='MTU'
  2382. )
  2383. mgmt_only = forms.NullBooleanField(
  2384. required=False,
  2385. widget=BulkEditNullBooleanSelect(),
  2386. label='Management only'
  2387. )
  2388. description = forms.CharField(
  2389. max_length=100,
  2390. required=False
  2391. )
  2392. mode = forms.ChoiceField(
  2393. choices=add_blank_choice(InterfaceModeChoices),
  2394. required=False,
  2395. widget=StaticSelect2()
  2396. )
  2397. untagged_vlan = forms.ModelChoiceField(
  2398. queryset=VLAN.objects.all(),
  2399. required=False,
  2400. widget=APISelect(
  2401. api_url="/api/ipam/vlans/",
  2402. display_field='display_name',
  2403. full=True
  2404. )
  2405. )
  2406. tagged_vlans = forms.ModelMultipleChoiceField(
  2407. queryset=VLAN.objects.all(),
  2408. required=False,
  2409. widget=APISelectMultiple(
  2410. api_url="/api/ipam/vlans/",
  2411. display_field='display_name',
  2412. full=True
  2413. )
  2414. )
  2415. class Meta:
  2416. nullable_fields = [
  2417. 'lag', 'mac_address', 'mtu', 'description', 'mode', 'untagged_vlan', 'tagged_vlans'
  2418. ]
  2419. def __init__(self, *args, **kwargs):
  2420. super().__init__(*args, **kwargs)
  2421. # Limit LAG choices to interfaces which belong to the parent device (or VC master)
  2422. device = self.parent_obj
  2423. if device is not None:
  2424. self.fields['lag'].queryset = Interface.objects.filter(
  2425. device__in=[device, device.get_vc_master()],
  2426. type=InterfaceTypeChoices.TYPE_LAG
  2427. )
  2428. else:
  2429. self.fields['lag'].choices = []
  2430. # Limit VLan choices to those in: global vlans, global groups, the current site's group, the current site
  2431. vlan_choices = []
  2432. global_vlans = VLAN.objects.filter(site=None, group=None)
  2433. vlan_choices.append(
  2434. ('Global', [(vlan.pk, vlan) for vlan in global_vlans])
  2435. )
  2436. for group in VLANGroup.objects.filter(site=None):
  2437. global_group_vlans = VLAN.objects.filter(group=group)
  2438. vlan_choices.append(
  2439. (group.name, [(vlan.pk, vlan) for vlan in global_group_vlans])
  2440. )
  2441. if self.parent_obj is not None:
  2442. site = getattr(self.parent_obj, 'site', None)
  2443. if site is not None:
  2444. # Add non-grouped site VLANs
  2445. site_vlans = VLAN.objects.filter(site=site, group=None)
  2446. vlan_choices.append((site.name, [(vlan.pk, vlan) for vlan in site_vlans]))
  2447. # Add grouped site VLANs
  2448. for group in VLANGroup.objects.filter(site=site):
  2449. site_group_vlans = VLAN.objects.filter(group=group)
  2450. vlan_choices.append((
  2451. '{} / {}'.format(group.site.name, group.name),
  2452. [(vlan.pk, vlan) for vlan in site_group_vlans]
  2453. ))
  2454. self.fields['untagged_vlan'].choices = [(None, '---------')] + vlan_choices
  2455. self.fields['tagged_vlans'].choices = vlan_choices
  2456. class InterfaceBulkRenameForm(BulkRenameForm):
  2457. pk = forms.ModelMultipleChoiceField(
  2458. queryset=Interface.objects.all(),
  2459. widget=forms.MultipleHiddenInput()
  2460. )
  2461. class InterfaceBulkDisconnectForm(ConfirmationForm):
  2462. pk = forms.ModelMultipleChoiceField(
  2463. queryset=Interface.objects.all(),
  2464. widget=forms.MultipleHiddenInput()
  2465. )
  2466. #
  2467. # Front pass-through ports
  2468. #
  2469. class FrontPortFilterForm(DeviceComponentFilterForm):
  2470. model = FrontPort
  2471. class FrontPortForm(BootstrapMixin, forms.ModelForm):
  2472. tags = TagField(
  2473. required=False
  2474. )
  2475. class Meta:
  2476. model = FrontPort
  2477. fields = [
  2478. 'device', 'name', 'type', 'rear_port', 'rear_port_position', 'description', 'tags',
  2479. ]
  2480. widgets = {
  2481. 'device': forms.HiddenInput(),
  2482. 'type': StaticSelect2(),
  2483. 'rear_port': StaticSelect2(),
  2484. }
  2485. def __init__(self, *args, **kwargs):
  2486. super().__init__(*args, **kwargs)
  2487. # Limit RearPort choices to the local device
  2488. if hasattr(self.instance, 'device'):
  2489. self.fields['rear_port'].queryset = self.fields['rear_port'].queryset.filter(
  2490. device=self.instance.device
  2491. )
  2492. # TODO: Merge with FrontPortTemplateCreateForm to remove duplicate logic
  2493. class FrontPortCreateForm(ComponentForm):
  2494. name_pattern = ExpandableNameField(
  2495. label='Name'
  2496. )
  2497. type = forms.ChoiceField(
  2498. choices=PortTypeChoices,
  2499. widget=StaticSelect2(),
  2500. )
  2501. rear_port_set = forms.MultipleChoiceField(
  2502. choices=[],
  2503. label='Rear ports',
  2504. help_text='Select one rear port assignment for each front port being created.',
  2505. )
  2506. description = forms.CharField(
  2507. required=False
  2508. )
  2509. def __init__(self, *args, **kwargs):
  2510. super().__init__(*args, **kwargs)
  2511. # Determine which rear port positions are occupied. These will be excluded from the list of available mappings.
  2512. occupied_port_positions = [
  2513. (front_port.rear_port_id, front_port.rear_port_position)
  2514. for front_port in self.parent.frontports.all()
  2515. ]
  2516. # Populate rear port choices
  2517. choices = []
  2518. rear_ports = RearPort.objects.filter(device=self.parent)
  2519. for rear_port in rear_ports:
  2520. for i in range(1, rear_port.positions + 1):
  2521. if (rear_port.pk, i) not in occupied_port_positions:
  2522. choices.append(
  2523. ('{}:{}'.format(rear_port.pk, i), '{}:{}'.format(rear_port.name, i))
  2524. )
  2525. self.fields['rear_port_set'].choices = choices
  2526. def clean(self):
  2527. # Validate that the number of ports being created equals the number of selected (rear port, position) tuples
  2528. front_port_count = len(self.cleaned_data['name_pattern'])
  2529. rear_port_count = len(self.cleaned_data['rear_port_set'])
  2530. if front_port_count != rear_port_count:
  2531. raise forms.ValidationError({
  2532. 'rear_port_set': 'The provided name pattern will create {} ports, however {} rear port assignments '
  2533. 'were selected. These counts must match.'.format(front_port_count, rear_port_count)
  2534. })
  2535. def get_iterative_data(self, iteration):
  2536. # Assign rear port and position from selected set
  2537. rear_port, position = self.cleaned_data['rear_port_set'][iteration].split(':')
  2538. return {
  2539. 'rear_port': int(rear_port),
  2540. 'rear_port_position': int(position),
  2541. }
  2542. class FrontPortCSVForm(forms.ModelForm):
  2543. device = FlexibleModelChoiceField(
  2544. queryset=Device.objects.all(),
  2545. to_field_name='name',
  2546. help_text='Name or ID of device',
  2547. error_messages={
  2548. 'invalid_choice': 'Device not found.',
  2549. }
  2550. )
  2551. rear_port = FlexibleModelChoiceField(
  2552. queryset=RearPort.objects.all(),
  2553. to_field_name='name',
  2554. help_text='Name or ID of Rear Port',
  2555. error_messages={
  2556. 'invalid_choice': 'Rear Port not found.',
  2557. }
  2558. )
  2559. type = CSVChoiceField(
  2560. choices=PortTypeChoices,
  2561. )
  2562. class Meta:
  2563. model = FrontPort
  2564. fields = FrontPort.csv_headers
  2565. def __init__(self, *args, **kwargs):
  2566. super().__init__(*args, **kwargs)
  2567. # Limit RearPort choices to those belonging to this device (or VC master)
  2568. if self.is_bound:
  2569. try:
  2570. device = self.fields['device'].to_python(self.data['device'])
  2571. except forms.ValidationError:
  2572. device = None
  2573. else:
  2574. try:
  2575. device = self.instance.device
  2576. except Device.DoesNotExist:
  2577. device = None
  2578. if device:
  2579. self.fields['rear_port'].queryset = RearPort.objects.filter(
  2580. device__in=[device, device.get_vc_master()]
  2581. )
  2582. else:
  2583. self.fields['rear_port'].queryset = RearPort.objects.none()
  2584. class FrontPortBulkEditForm(BootstrapMixin, AddRemoveTagsForm, BulkEditForm):
  2585. pk = forms.ModelMultipleChoiceField(
  2586. queryset=FrontPort.objects.all(),
  2587. widget=forms.MultipleHiddenInput()
  2588. )
  2589. type = forms.ChoiceField(
  2590. choices=add_blank_choice(PortTypeChoices),
  2591. required=False,
  2592. widget=StaticSelect2()
  2593. )
  2594. description = forms.CharField(
  2595. max_length=100,
  2596. required=False
  2597. )
  2598. class Meta:
  2599. nullable_fields = [
  2600. 'description',
  2601. ]
  2602. class FrontPortBulkRenameForm(BulkRenameForm):
  2603. pk = forms.ModelMultipleChoiceField(
  2604. queryset=FrontPort.objects.all(),
  2605. widget=forms.MultipleHiddenInput
  2606. )
  2607. class FrontPortBulkDisconnectForm(ConfirmationForm):
  2608. pk = forms.ModelMultipleChoiceField(
  2609. queryset=FrontPort.objects.all(),
  2610. widget=forms.MultipleHiddenInput
  2611. )
  2612. #
  2613. # Rear pass-through ports
  2614. #
  2615. class RearPortFilterForm(DeviceComponentFilterForm):
  2616. model = RearPort
  2617. class RearPortForm(BootstrapMixin, forms.ModelForm):
  2618. tags = TagField(
  2619. required=False
  2620. )
  2621. class Meta:
  2622. model = RearPort
  2623. fields = [
  2624. 'device', 'name', 'type', 'positions', 'description', 'tags',
  2625. ]
  2626. widgets = {
  2627. 'device': forms.HiddenInput(),
  2628. 'type': StaticSelect2(),
  2629. }
  2630. class RearPortCreateForm(ComponentForm):
  2631. name_pattern = ExpandableNameField(
  2632. label='Name'
  2633. )
  2634. type = forms.ChoiceField(
  2635. choices=PortTypeChoices,
  2636. widget=StaticSelect2(),
  2637. )
  2638. positions = forms.IntegerField(
  2639. min_value=1,
  2640. max_value=64,
  2641. initial=1,
  2642. help_text='The number of front ports which may be mapped to each rear port'
  2643. )
  2644. description = forms.CharField(
  2645. required=False
  2646. )
  2647. class RearPortCSVForm(forms.ModelForm):
  2648. device = FlexibleModelChoiceField(
  2649. queryset=Device.objects.all(),
  2650. to_field_name='name',
  2651. help_text='Name or ID of device',
  2652. error_messages={
  2653. 'invalid_choice': 'Device not found.',
  2654. }
  2655. )
  2656. type = CSVChoiceField(
  2657. choices=PortTypeChoices,
  2658. )
  2659. class Meta:
  2660. model = RearPort
  2661. fields = RearPort.csv_headers
  2662. class RearPortBulkEditForm(BootstrapMixin, AddRemoveTagsForm, BulkEditForm):
  2663. pk = forms.ModelMultipleChoiceField(
  2664. queryset=RearPort.objects.all(),
  2665. widget=forms.MultipleHiddenInput()
  2666. )
  2667. type = forms.ChoiceField(
  2668. choices=add_blank_choice(PortTypeChoices),
  2669. required=False,
  2670. widget=StaticSelect2()
  2671. )
  2672. description = forms.CharField(
  2673. max_length=100,
  2674. required=False
  2675. )
  2676. class Meta:
  2677. nullable_fields = [
  2678. 'description',
  2679. ]
  2680. class RearPortBulkRenameForm(BulkRenameForm):
  2681. pk = forms.ModelMultipleChoiceField(
  2682. queryset=RearPort.objects.all(),
  2683. widget=forms.MultipleHiddenInput
  2684. )
  2685. class RearPortBulkDisconnectForm(ConfirmationForm):
  2686. pk = forms.ModelMultipleChoiceField(
  2687. queryset=RearPort.objects.all(),
  2688. widget=forms.MultipleHiddenInput
  2689. )
  2690. #
  2691. # Cables
  2692. #
  2693. class ConnectCableToDeviceForm(BootstrapMixin, ChainedFieldsMixin, forms.ModelForm):
  2694. """
  2695. Base form for connecting a Cable to a Device component
  2696. """
  2697. termination_b_site = forms.ModelChoiceField(
  2698. queryset=Site.objects.all(),
  2699. label='Site',
  2700. required=False,
  2701. widget=APISelect(
  2702. api_url='/api/dcim/sites/',
  2703. filter_for={
  2704. 'termination_b_rack': 'site_id',
  2705. 'termination_b_device': 'site_id',
  2706. }
  2707. )
  2708. )
  2709. termination_b_rack = ChainedModelChoiceField(
  2710. queryset=Rack.objects.all(),
  2711. chains=(
  2712. ('site', 'termination_b_site'),
  2713. ),
  2714. label='Rack',
  2715. required=False,
  2716. widget=APISelect(
  2717. api_url='/api/dcim/racks/',
  2718. filter_for={
  2719. 'termination_b_device': 'rack_id',
  2720. },
  2721. attrs={
  2722. 'nullable': 'true',
  2723. }
  2724. )
  2725. )
  2726. termination_b_device = ChainedModelChoiceField(
  2727. queryset=Device.objects.all(),
  2728. chains=(
  2729. ('site', 'termination_b_site'),
  2730. ('rack', 'termination_b_rack'),
  2731. ),
  2732. label='Device',
  2733. required=False,
  2734. widget=APISelect(
  2735. api_url='/api/dcim/devices/',
  2736. display_field='display_name',
  2737. filter_for={
  2738. 'termination_b_id': 'device_id',
  2739. }
  2740. )
  2741. )
  2742. class Meta:
  2743. model = Cable
  2744. fields = [
  2745. 'termination_b_site', 'termination_b_rack', 'termination_b_device', 'termination_b_id', 'type', 'status',
  2746. 'label', 'color', 'length', 'length_unit',
  2747. ]
  2748. class ConnectCableToConsolePortForm(ConnectCableToDeviceForm):
  2749. termination_b_id = forms.IntegerField(
  2750. label='Name',
  2751. widget=APISelect(
  2752. api_url='/api/dcim/console-ports/',
  2753. disabled_indicator='cable',
  2754. )
  2755. )
  2756. class ConnectCableToConsoleServerPortForm(ConnectCableToDeviceForm):
  2757. termination_b_id = forms.IntegerField(
  2758. label='Name',
  2759. widget=APISelect(
  2760. api_url='/api/dcim/console-server-ports/',
  2761. disabled_indicator='cable',
  2762. )
  2763. )
  2764. class ConnectCableToPowerPortForm(ConnectCableToDeviceForm):
  2765. termination_b_id = forms.IntegerField(
  2766. label='Name',
  2767. widget=APISelect(
  2768. api_url='/api/dcim/power-ports/',
  2769. disabled_indicator='cable',
  2770. )
  2771. )
  2772. class ConnectCableToPowerOutletForm(ConnectCableToDeviceForm):
  2773. termination_b_id = forms.IntegerField(
  2774. label='Name',
  2775. widget=APISelect(
  2776. api_url='/api/dcim/power-outlets/',
  2777. disabled_indicator='cable',
  2778. )
  2779. )
  2780. class ConnectCableToInterfaceForm(ConnectCableToDeviceForm):
  2781. termination_b_id = forms.IntegerField(
  2782. label='Name',
  2783. widget=APISelect(
  2784. api_url='/api/dcim/interfaces/',
  2785. disabled_indicator='cable',
  2786. additional_query_params={
  2787. 'kind': 'physical',
  2788. }
  2789. )
  2790. )
  2791. class ConnectCableToFrontPortForm(ConnectCableToDeviceForm):
  2792. termination_b_id = forms.IntegerField(
  2793. label='Name',
  2794. widget=APISelect(
  2795. api_url='/api/dcim/front-ports/',
  2796. disabled_indicator='cable',
  2797. )
  2798. )
  2799. class ConnectCableToRearPortForm(ConnectCableToDeviceForm):
  2800. termination_b_id = forms.IntegerField(
  2801. label='Name',
  2802. widget=APISelect(
  2803. api_url='/api/dcim/rear-ports/',
  2804. disabled_indicator='cable',
  2805. )
  2806. )
  2807. class ConnectCableToCircuitTerminationForm(BootstrapMixin, ChainedFieldsMixin, forms.ModelForm):
  2808. termination_b_provider = forms.ModelChoiceField(
  2809. queryset=Provider.objects.all(),
  2810. label='Provider',
  2811. widget=APISelect(
  2812. api_url='/api/circuits/providers/',
  2813. filter_for={
  2814. 'termination_b_circuit': 'provider_id',
  2815. }
  2816. )
  2817. )
  2818. termination_b_site = forms.ModelChoiceField(
  2819. queryset=Site.objects.all(),
  2820. label='Site',
  2821. required=False,
  2822. widget=APISelect(
  2823. api_url='/api/dcim/sites/',
  2824. filter_for={
  2825. 'termination_b_circuit': 'site_id',
  2826. }
  2827. )
  2828. )
  2829. termination_b_circuit = ChainedModelChoiceField(
  2830. queryset=Circuit.objects.all(),
  2831. chains=(
  2832. ('provider', 'termination_b_provider'),
  2833. ),
  2834. label='Circuit',
  2835. widget=APISelect(
  2836. api_url='/api/circuits/circuits/',
  2837. display_field='cid',
  2838. filter_for={
  2839. 'termination_b_id': 'circuit_id',
  2840. }
  2841. )
  2842. )
  2843. termination_b_id = forms.IntegerField(
  2844. label='Side',
  2845. widget=APISelect(
  2846. api_url='/api/circuits/circuit-terminations/',
  2847. disabled_indicator='cable',
  2848. display_field='term_side'
  2849. )
  2850. )
  2851. class Meta:
  2852. model = Cable
  2853. fields = [
  2854. 'termination_b_provider', 'termination_b_site', 'termination_b_circuit', 'termination_b_id', 'type',
  2855. 'status', 'label', 'color', 'length', 'length_unit',
  2856. ]
  2857. class ConnectCableToPowerFeedForm(BootstrapMixin, ChainedFieldsMixin, forms.ModelForm):
  2858. termination_b_site = forms.ModelChoiceField(
  2859. queryset=Site.objects.all(),
  2860. label='Site',
  2861. widget=APISelect(
  2862. api_url='/api/dcim/sites/',
  2863. display_field='cid',
  2864. filter_for={
  2865. 'termination_b_rackgroup': 'site_id',
  2866. 'termination_b_powerpanel': 'site_id',
  2867. }
  2868. )
  2869. )
  2870. termination_b_rackgroup = ChainedModelChoiceField(
  2871. queryset=RackGroup.objects.all(),
  2872. label='Rack Group',
  2873. chains=(
  2874. ('site', 'termination_b_site'),
  2875. ),
  2876. required=False,
  2877. widget=APISelect(
  2878. api_url='/api/dcim/rack-groups/',
  2879. display_field='cid',
  2880. filter_for={
  2881. 'termination_b_powerpanel': 'rackgroup_id',
  2882. }
  2883. )
  2884. )
  2885. termination_b_powerpanel = ChainedModelChoiceField(
  2886. queryset=PowerPanel.objects.all(),
  2887. chains=(
  2888. ('site', 'termination_b_site'),
  2889. ('rack_group', 'termination_b_rackgroup'),
  2890. ),
  2891. label='Power Panel',
  2892. widget=APISelect(
  2893. api_url='/api/dcim/power-panels/',
  2894. filter_for={
  2895. 'termination_b_id': 'power_panel_id',
  2896. }
  2897. )
  2898. )
  2899. termination_b_id = forms.IntegerField(
  2900. label='Name',
  2901. widget=APISelect(
  2902. api_url='/api/dcim/power-feeds/',
  2903. )
  2904. )
  2905. class Meta:
  2906. model = Cable
  2907. fields = [
  2908. 'termination_b_rackgroup', 'termination_b_powerpanel', 'termination_b_id', 'type', 'status', 'label',
  2909. 'color', 'length', 'length_unit',
  2910. ]
  2911. class CableForm(BootstrapMixin, forms.ModelForm):
  2912. class Meta:
  2913. model = Cable
  2914. fields = [
  2915. 'type', 'status', 'label', 'color', 'length', 'length_unit',
  2916. ]
  2917. class CableCSVForm(forms.ModelForm):
  2918. # Termination A
  2919. side_a_device = FlexibleModelChoiceField(
  2920. queryset=Device.objects.all(),
  2921. to_field_name='name',
  2922. help_text='Side A device name or ID',
  2923. error_messages={
  2924. 'invalid_choice': 'Side A device not found',
  2925. }
  2926. )
  2927. side_a_type = forms.ModelChoiceField(
  2928. queryset=ContentType.objects.all(),
  2929. limit_choices_to={
  2930. 'model__in': CABLE_TERMINATION_TYPES,
  2931. },
  2932. to_field_name='model',
  2933. help_text='Side A type'
  2934. )
  2935. side_a_name = forms.CharField(
  2936. help_text='Side A component'
  2937. )
  2938. # Termination B
  2939. side_b_device = FlexibleModelChoiceField(
  2940. queryset=Device.objects.all(),
  2941. to_field_name='name',
  2942. help_text='Side B device name or ID',
  2943. error_messages={
  2944. 'invalid_choice': 'Side B device not found',
  2945. }
  2946. )
  2947. side_b_type = forms.ModelChoiceField(
  2948. queryset=ContentType.objects.all(),
  2949. limit_choices_to={
  2950. 'model__in': CABLE_TERMINATION_TYPES,
  2951. },
  2952. to_field_name='model',
  2953. help_text='Side B type'
  2954. )
  2955. side_b_name = forms.CharField(
  2956. help_text='Side B component'
  2957. )
  2958. # Cable attributes
  2959. status = CSVChoiceField(
  2960. choices=CableStatusChoices,
  2961. required=False,
  2962. help_text='Connection status'
  2963. )
  2964. type = CSVChoiceField(
  2965. choices=CableTypeChoices,
  2966. required=False,
  2967. help_text='Cable type'
  2968. )
  2969. length_unit = CSVChoiceField(
  2970. choices=CableLengthUnitChoices,
  2971. required=False,
  2972. help_text='Length unit'
  2973. )
  2974. class Meta:
  2975. model = Cable
  2976. fields = [
  2977. 'side_a_device', 'side_a_type', 'side_a_name', 'side_b_device', 'side_b_type', 'side_b_name', 'type',
  2978. 'status', 'label', 'color', 'length', 'length_unit',
  2979. ]
  2980. help_texts = {
  2981. 'color': 'RGB color in hexadecimal (e.g. 00ff00)'
  2982. }
  2983. # TODO: Merge the clean() methods for either end
  2984. def clean_side_a_name(self):
  2985. device = self.cleaned_data.get('side_a_device')
  2986. content_type = self.cleaned_data.get('side_a_type')
  2987. name = self.cleaned_data.get('side_a_name')
  2988. if not device or not content_type or not name:
  2989. return None
  2990. model = content_type.model_class()
  2991. try:
  2992. termination_object = model.objects.get(
  2993. device=device,
  2994. name=name
  2995. )
  2996. if termination_object.cable is not None:
  2997. raise forms.ValidationError(
  2998. "Side A: {} {} is already connected".format(device, termination_object)
  2999. )
  3000. except ObjectDoesNotExist:
  3001. raise forms.ValidationError(
  3002. "A side termination not found: {} {}".format(device, name)
  3003. )
  3004. self.instance.termination_a = termination_object
  3005. return termination_object
  3006. def clean_side_b_name(self):
  3007. device = self.cleaned_data.get('side_b_device')
  3008. content_type = self.cleaned_data.get('side_b_type')
  3009. name = self.cleaned_data.get('side_b_name')
  3010. if not device or not content_type or not name:
  3011. return None
  3012. model = content_type.model_class()
  3013. try:
  3014. termination_object = model.objects.get(
  3015. device=device,
  3016. name=name
  3017. )
  3018. if termination_object.cable is not None:
  3019. raise forms.ValidationError(
  3020. "Side B: {} {} is already connected".format(device, termination_object)
  3021. )
  3022. except ObjectDoesNotExist:
  3023. raise forms.ValidationError(
  3024. "B side termination not found: {} {}".format(device, name)
  3025. )
  3026. self.instance.termination_b = termination_object
  3027. return termination_object
  3028. def clean_length_unit(self):
  3029. # Avoid trying to save as NULL
  3030. length_unit = self.cleaned_data.get('length_unit', None)
  3031. return length_unit if length_unit is not None else ''
  3032. class CableBulkEditForm(BootstrapMixin, BulkEditForm):
  3033. pk = forms.ModelMultipleChoiceField(
  3034. queryset=Cable.objects.all(),
  3035. widget=forms.MultipleHiddenInput
  3036. )
  3037. type = forms.ChoiceField(
  3038. choices=add_blank_choice(CableTypeChoices),
  3039. required=False,
  3040. initial='',
  3041. widget=StaticSelect2()
  3042. )
  3043. status = forms.ChoiceField(
  3044. choices=add_blank_choice(CableStatusChoices),
  3045. required=False,
  3046. widget=StaticSelect2(),
  3047. initial=''
  3048. )
  3049. label = forms.CharField(
  3050. max_length=100,
  3051. required=False
  3052. )
  3053. color = forms.CharField(
  3054. max_length=6,
  3055. required=False,
  3056. widget=ColorSelect()
  3057. )
  3058. length = forms.IntegerField(
  3059. min_value=1,
  3060. required=False
  3061. )
  3062. length_unit = forms.ChoiceField(
  3063. choices=add_blank_choice(CableLengthUnitChoices),
  3064. required=False,
  3065. initial='',
  3066. widget=StaticSelect2()
  3067. )
  3068. class Meta:
  3069. nullable_fields = [
  3070. 'type', 'status', 'label', 'color', 'length',
  3071. ]
  3072. def clean(self):
  3073. # Validate length/unit
  3074. length = self.cleaned_data.get('length')
  3075. length_unit = self.cleaned_data.get('length_unit')
  3076. if length and not length_unit:
  3077. raise forms.ValidationError({
  3078. 'length_unit': "Must specify a unit when setting length"
  3079. })
  3080. class CableFilterForm(BootstrapMixin, forms.Form):
  3081. model = Cable
  3082. q = forms.CharField(
  3083. required=False,
  3084. label='Search'
  3085. )
  3086. site = FilterChoiceField(
  3087. queryset=Site.objects.all(),
  3088. to_field_name='slug',
  3089. widget=APISelectMultiple(
  3090. api_url="/api/dcim/sites/",
  3091. value_field="slug",
  3092. filter_for={
  3093. 'rack_id': 'site',
  3094. }
  3095. )
  3096. )
  3097. rack_id = FilterChoiceField(
  3098. queryset=Rack.objects.all(),
  3099. label='Rack',
  3100. null_label='-- None --',
  3101. widget=APISelectMultiple(
  3102. api_url="/api/dcim/racks/",
  3103. null_option=True,
  3104. )
  3105. )
  3106. type = forms.MultipleChoiceField(
  3107. choices=add_blank_choice(CableTypeChoices),
  3108. required=False,
  3109. widget=StaticSelect2()
  3110. )
  3111. status = forms.ChoiceField(
  3112. required=False,
  3113. choices=add_blank_choice(CableStatusChoices),
  3114. widget=StaticSelect2()
  3115. )
  3116. color = forms.CharField(
  3117. max_length=6,
  3118. required=False,
  3119. widget=ColorSelect()
  3120. )
  3121. device = forms.CharField(
  3122. required=False,
  3123. label='Device name'
  3124. )
  3125. #
  3126. # Device bays
  3127. #
  3128. class DeviceBayFilterForm(DeviceComponentFilterForm):
  3129. model = DeviceBay
  3130. class DeviceBayForm(BootstrapMixin, forms.ModelForm):
  3131. tags = TagField(
  3132. required=False
  3133. )
  3134. class Meta:
  3135. model = DeviceBay
  3136. fields = [
  3137. 'device', 'name', 'description', 'tags',
  3138. ]
  3139. widgets = {
  3140. 'device': forms.HiddenInput(),
  3141. }
  3142. class DeviceBayCreateForm(ComponentForm):
  3143. name_pattern = ExpandableNameField(
  3144. label='Name'
  3145. )
  3146. tags = TagField(
  3147. required=False
  3148. )
  3149. class PopulateDeviceBayForm(BootstrapMixin, forms.Form):
  3150. installed_device = forms.ModelChoiceField(
  3151. queryset=Device.objects.all(),
  3152. label='Child Device',
  3153. help_text="Child devices must first be created and assigned to the site/rack of the parent device.",
  3154. widget=StaticSelect2(),
  3155. )
  3156. def __init__(self, device_bay, *args, **kwargs):
  3157. super().__init__(*args, **kwargs)
  3158. self.fields['installed_device'].queryset = Device.objects.filter(
  3159. site=device_bay.device.site,
  3160. rack=device_bay.device.rack,
  3161. parent_bay__isnull=True,
  3162. device_type__u_height=0,
  3163. device_type__subdevice_role=SubdeviceRoleChoices.ROLE_CHILD
  3164. ).exclude(pk=device_bay.device.pk)
  3165. class DeviceBayCSVForm(forms.ModelForm):
  3166. device = FlexibleModelChoiceField(
  3167. queryset=Device.objects.all(),
  3168. to_field_name='name',
  3169. help_text='Name or ID of device',
  3170. error_messages={
  3171. 'invalid_choice': 'Device not found.',
  3172. }
  3173. )
  3174. installed_device = FlexibleModelChoiceField(
  3175. queryset=Device.objects.all(),
  3176. required=False,
  3177. to_field_name='name',
  3178. help_text='Name or ID of device',
  3179. error_messages={
  3180. 'invalid_choice': 'Child device not found.',
  3181. }
  3182. )
  3183. class Meta:
  3184. model = DeviceBay
  3185. fields = DeviceBay.csv_headers
  3186. def __init__(self, *args, **kwargs):
  3187. super().__init__(*args, **kwargs)
  3188. # Limit installed device choices to devices of the correct type and location
  3189. if self.is_bound:
  3190. try:
  3191. device = self.fields['device'].to_python(self.data['device'])
  3192. except forms.ValidationError:
  3193. device = None
  3194. else:
  3195. try:
  3196. device = self.instance.device
  3197. except Device.DoesNotExist:
  3198. device = None
  3199. if device:
  3200. self.fields['installed_device'].queryset = Device.objects.filter(
  3201. site=device.site,
  3202. rack=device.rack,
  3203. parent_bay__isnull=True,
  3204. device_type__u_height=0,
  3205. device_type__subdevice_role=SubdeviceRoleChoices.ROLE_CHILD
  3206. ).exclude(pk=device.pk)
  3207. else:
  3208. self.fields['installed_device'].queryset = Interface.objects.none()
  3209. class DeviceBayBulkRenameForm(BulkRenameForm):
  3210. pk = forms.ModelMultipleChoiceField(
  3211. queryset=DeviceBay.objects.all(),
  3212. widget=forms.MultipleHiddenInput()
  3213. )
  3214. #
  3215. # Connections
  3216. #
  3217. class ConsoleConnectionFilterForm(BootstrapMixin, forms.Form):
  3218. site = forms.ModelChoiceField(
  3219. queryset=Site.objects.all(),
  3220. required=False,
  3221. to_field_name='slug'
  3222. )
  3223. device = forms.CharField(
  3224. required=False,
  3225. label='Device name'
  3226. )
  3227. class PowerConnectionFilterForm(BootstrapMixin, forms.Form):
  3228. site = forms.ModelChoiceField(
  3229. queryset=Site.objects.all(),
  3230. required=False,
  3231. to_field_name='slug'
  3232. )
  3233. device = forms.CharField(
  3234. required=False,
  3235. label='Device name'
  3236. )
  3237. class InterfaceConnectionFilterForm(BootstrapMixin, forms.Form):
  3238. site = forms.ModelChoiceField(
  3239. queryset=Site.objects.all(),
  3240. required=False,
  3241. to_field_name='slug'
  3242. )
  3243. device = forms.CharField(
  3244. required=False,
  3245. label='Device name'
  3246. )
  3247. #
  3248. # Inventory items
  3249. #
  3250. class InventoryItemForm(BootstrapMixin, forms.ModelForm):
  3251. tags = TagField(
  3252. required=False
  3253. )
  3254. class Meta:
  3255. model = InventoryItem
  3256. fields = [
  3257. 'name', 'manufacturer', 'part_id', 'serial', 'asset_tag', 'description', 'tags',
  3258. ]
  3259. widgets = {
  3260. 'manufacturer': APISelect(
  3261. api_url="/api/dcim/manufacturers/"
  3262. )
  3263. }
  3264. class InventoryItemCSVForm(forms.ModelForm):
  3265. device = FlexibleModelChoiceField(
  3266. queryset=Device.objects.all(),
  3267. to_field_name='name',
  3268. help_text='Device name or ID',
  3269. error_messages={
  3270. 'invalid_choice': 'Device not found.',
  3271. }
  3272. )
  3273. manufacturer = forms.ModelChoiceField(
  3274. queryset=Manufacturer.objects.all(),
  3275. to_field_name='name',
  3276. required=False,
  3277. help_text='Manufacturer name',
  3278. error_messages={
  3279. 'invalid_choice': 'Invalid manufacturer.',
  3280. }
  3281. )
  3282. class Meta:
  3283. model = InventoryItem
  3284. fields = InventoryItem.csv_headers
  3285. class InventoryItemBulkEditForm(BootstrapMixin, BulkEditForm):
  3286. pk = forms.ModelMultipleChoiceField(
  3287. queryset=InventoryItem.objects.all(),
  3288. widget=forms.MultipleHiddenInput()
  3289. )
  3290. manufacturer = forms.ModelChoiceField(
  3291. queryset=Manufacturer.objects.all(),
  3292. required=False
  3293. )
  3294. part_id = forms.CharField(
  3295. max_length=50,
  3296. required=False,
  3297. label='Part ID'
  3298. )
  3299. description = forms.CharField(
  3300. max_length=100,
  3301. required=False
  3302. )
  3303. class Meta:
  3304. nullable_fields = [
  3305. 'manufacturer', 'part_id', 'description',
  3306. ]
  3307. class InventoryItemFilterForm(BootstrapMixin, forms.Form):
  3308. model = InventoryItem
  3309. q = forms.CharField(
  3310. required=False,
  3311. label='Search'
  3312. )
  3313. device = forms.CharField(
  3314. required=False,
  3315. label='Device name'
  3316. )
  3317. manufacturer = FilterChoiceField(
  3318. queryset=Manufacturer.objects.all(),
  3319. to_field_name='slug',
  3320. null_label='-- None --'
  3321. )
  3322. discovered = forms.NullBooleanField(
  3323. required=False,
  3324. widget=forms.Select(
  3325. choices=BOOLEAN_WITH_BLANK_CHOICES
  3326. )
  3327. )
  3328. #
  3329. # Virtual chassis
  3330. #
  3331. class DeviceSelectionForm(forms.Form):
  3332. pk = forms.ModelMultipleChoiceField(
  3333. queryset=Device.objects.all(),
  3334. widget=forms.MultipleHiddenInput()
  3335. )
  3336. class VirtualChassisForm(BootstrapMixin, forms.ModelForm):
  3337. tags = TagField(
  3338. required=False
  3339. )
  3340. class Meta:
  3341. model = VirtualChassis
  3342. fields = [
  3343. 'master', 'domain', 'tags',
  3344. ]
  3345. widgets = {
  3346. 'master': SelectWithPK(),
  3347. }
  3348. class BaseVCMemberFormSet(forms.BaseModelFormSet):
  3349. def clean(self):
  3350. super().clean()
  3351. # Check for duplicate VC position values
  3352. vc_position_list = []
  3353. for form in self.forms:
  3354. vc_position = form.cleaned_data.get('vc_position')
  3355. if vc_position:
  3356. if vc_position in vc_position_list:
  3357. error_msg = 'A virtual chassis member already exists in position {}.'.format(vc_position)
  3358. form.add_error('vc_position', error_msg)
  3359. vc_position_list.append(vc_position)
  3360. class DeviceVCMembershipForm(forms.ModelForm):
  3361. class Meta:
  3362. model = Device
  3363. fields = [
  3364. 'vc_position', 'vc_priority',
  3365. ]
  3366. labels = {
  3367. 'vc_position': 'Position',
  3368. 'vc_priority': 'Priority',
  3369. }
  3370. def __init__(self, validate_vc_position=False, *args, **kwargs):
  3371. super().__init__(*args, **kwargs)
  3372. # Require VC position (only required when the Device is a VirtualChassis member)
  3373. self.fields['vc_position'].required = True
  3374. # Validation of vc_position is optional. This is only required when adding a new member to an existing
  3375. # VirtualChassis. Otherwise, vc_position validation is handled by BaseVCMemberFormSet.
  3376. self.validate_vc_position = validate_vc_position
  3377. def clean_vc_position(self):
  3378. vc_position = self.cleaned_data['vc_position']
  3379. if self.validate_vc_position:
  3380. conflicting_members = Device.objects.filter(
  3381. virtual_chassis=self.instance.virtual_chassis,
  3382. vc_position=vc_position
  3383. )
  3384. if conflicting_members.exists():
  3385. raise forms.ValidationError(
  3386. 'A virtual chassis member already exists in position {}.'.format(vc_position)
  3387. )
  3388. return vc_position
  3389. class VCMemberSelectForm(BootstrapMixin, ChainedFieldsMixin, forms.Form):
  3390. site = forms.ModelChoiceField(
  3391. queryset=Site.objects.all(),
  3392. label='Site',
  3393. required=False,
  3394. widget=APISelect(
  3395. api_url="/api/dcim/sites/",
  3396. filter_for={
  3397. 'rack': 'site_id',
  3398. 'device': 'site_id',
  3399. }
  3400. )
  3401. )
  3402. rack = ChainedModelChoiceField(
  3403. queryset=Rack.objects.all(),
  3404. chains=(
  3405. ('site', 'site'),
  3406. ),
  3407. label='Rack',
  3408. required=False,
  3409. widget=APISelect(
  3410. api_url='/api/dcim/racks/',
  3411. filter_for={
  3412. 'device': 'rack_id'
  3413. },
  3414. attrs={
  3415. 'nullable': 'true',
  3416. }
  3417. )
  3418. )
  3419. device = ChainedModelChoiceField(
  3420. queryset=Device.objects.filter(
  3421. virtual_chassis__isnull=True
  3422. ),
  3423. chains=(
  3424. ('site', 'site'),
  3425. ('rack', 'rack'),
  3426. ),
  3427. label='Device',
  3428. widget=APISelect(
  3429. api_url='/api/dcim/devices/',
  3430. display_field='display_name',
  3431. disabled_indicator='virtual_chassis'
  3432. )
  3433. )
  3434. def clean_device(self):
  3435. device = self.cleaned_data['device']
  3436. if device.virtual_chassis is not None:
  3437. raise forms.ValidationError(
  3438. "Device {} is already assigned to a virtual chassis.".format(device)
  3439. )
  3440. return device
  3441. class VirtualChassisFilterForm(BootstrapMixin, CustomFieldFilterForm):
  3442. model = VirtualChassis
  3443. q = forms.CharField(
  3444. required=False,
  3445. label='Search'
  3446. )
  3447. site = FilterChoiceField(
  3448. queryset=Site.objects.all(),
  3449. to_field_name='slug',
  3450. widget=APISelectMultiple(
  3451. api_url="/api/dcim/sites/",
  3452. value_field="slug",
  3453. )
  3454. )
  3455. tenant_group = FilterChoiceField(
  3456. queryset=TenantGroup.objects.all(),
  3457. to_field_name='slug',
  3458. null_label='-- None --',
  3459. widget=APISelectMultiple(
  3460. api_url="/api/tenancy/tenant-groups/",
  3461. value_field="slug",
  3462. null_option=True,
  3463. filter_for={
  3464. 'tenant': 'group'
  3465. }
  3466. )
  3467. )
  3468. tenant = FilterChoiceField(
  3469. queryset=Tenant.objects.all(),
  3470. to_field_name='slug',
  3471. null_label='-- None --',
  3472. widget=APISelectMultiple(
  3473. api_url="/api/tenancy/tenants/",
  3474. value_field="slug",
  3475. null_option=True,
  3476. )
  3477. )
  3478. #
  3479. # Power panels
  3480. #
  3481. class PowerPanelForm(BootstrapMixin, forms.ModelForm):
  3482. rack_group = ChainedModelChoiceField(
  3483. queryset=RackGroup.objects.all(),
  3484. chains=(
  3485. ('site', 'site'),
  3486. ),
  3487. required=False,
  3488. widget=APISelect(
  3489. api_url='/api/dcim/rack-groups/',
  3490. )
  3491. )
  3492. class Meta:
  3493. model = PowerPanel
  3494. fields = [
  3495. 'site', 'rack_group', 'name',
  3496. ]
  3497. widgets = {
  3498. 'site': APISelect(
  3499. api_url="/api/dcim/sites/",
  3500. filter_for={
  3501. 'rack_group': 'site_id',
  3502. }
  3503. ),
  3504. }
  3505. class PowerPanelCSVForm(forms.ModelForm):
  3506. site = forms.ModelChoiceField(
  3507. queryset=Site.objects.all(),
  3508. to_field_name='name',
  3509. help_text='Name of parent site',
  3510. error_messages={
  3511. 'invalid_choice': 'Site not found.',
  3512. }
  3513. )
  3514. rack_group_name = forms.CharField(
  3515. required=False,
  3516. help_text="Rack group name (optional)"
  3517. )
  3518. class Meta:
  3519. model = PowerPanel
  3520. fields = PowerPanel.csv_headers
  3521. def clean(self):
  3522. super().clean()
  3523. site = self.cleaned_data.get('site')
  3524. rack_group_name = self.cleaned_data.get('rack_group_name')
  3525. # Validate rack group
  3526. if rack_group_name:
  3527. try:
  3528. self.instance.rack_group = RackGroup.objects.get(site=site, name=rack_group_name)
  3529. except RackGroup.DoesNotExist:
  3530. raise forms.ValidationError(
  3531. "Rack group {} not found in site {}".format(rack_group_name, site)
  3532. )
  3533. class PowerPanelFilterForm(BootstrapMixin, CustomFieldFilterForm):
  3534. model = PowerPanel
  3535. q = forms.CharField(
  3536. required=False,
  3537. label='Search'
  3538. )
  3539. site = FilterChoiceField(
  3540. queryset=Site.objects.all(),
  3541. to_field_name='slug',
  3542. widget=APISelectMultiple(
  3543. api_url="/api/dcim/sites/",
  3544. value_field="slug",
  3545. filter_for={
  3546. 'rack_group_id': 'site',
  3547. }
  3548. )
  3549. )
  3550. rack_group_id = FilterChoiceField(
  3551. queryset=RackGroup.objects.all(),
  3552. label='Rack group (ID)',
  3553. null_label='-- None --',
  3554. widget=APISelectMultiple(
  3555. api_url="/api/dcim/rack-groups/",
  3556. null_option=True,
  3557. )
  3558. )
  3559. #
  3560. # Power feeds
  3561. #
  3562. class PowerFeedForm(BootstrapMixin, CustomFieldForm):
  3563. site = ChainedModelChoiceField(
  3564. queryset=Site.objects.all(),
  3565. required=False,
  3566. widget=APISelect(
  3567. api_url='/api/dcim/sites/',
  3568. filter_for={
  3569. 'power_panel': 'site_id',
  3570. 'rack': 'site_id',
  3571. }
  3572. )
  3573. )
  3574. comments = CommentField()
  3575. tags = TagField(
  3576. required=False
  3577. )
  3578. class Meta:
  3579. model = PowerFeed
  3580. fields = [
  3581. 'site', 'power_panel', 'rack', 'name', 'status', 'type', 'supply', 'phase', 'voltage', 'amperage',
  3582. 'max_utilization', 'comments', 'tags',
  3583. ]
  3584. widgets = {
  3585. 'power_panel': APISelect(
  3586. api_url="/api/dcim/power-panels/"
  3587. ),
  3588. 'rack': APISelect(
  3589. api_url="/api/dcim/racks/"
  3590. ),
  3591. 'status': StaticSelect2(),
  3592. 'type': StaticSelect2(),
  3593. 'supply': StaticSelect2(),
  3594. 'phase': StaticSelect2(),
  3595. }
  3596. def __init__(self, *args, **kwargs):
  3597. super().__init__(*args, **kwargs)
  3598. # Initialize site field
  3599. if self.instance and hasattr(self.instance, 'power_panel'):
  3600. self.initial['site'] = self.instance.power_panel.site
  3601. class PowerFeedCSVForm(forms.ModelForm):
  3602. site = forms.ModelChoiceField(
  3603. queryset=Site.objects.all(),
  3604. to_field_name='name',
  3605. help_text='Name of parent site',
  3606. error_messages={
  3607. 'invalid_choice': 'Site not found.',
  3608. }
  3609. )
  3610. panel_name = forms.ModelChoiceField(
  3611. queryset=PowerPanel.objects.all(),
  3612. to_field_name='name',
  3613. help_text='Name of upstream power panel',
  3614. error_messages={
  3615. 'invalid_choice': 'Power panel not found.',
  3616. }
  3617. )
  3618. rack_group = forms.CharField(
  3619. required=False,
  3620. help_text="Rack group name (optional)"
  3621. )
  3622. rack_name = forms.CharField(
  3623. required=False,
  3624. help_text="Rack name (optional)"
  3625. )
  3626. status = CSVChoiceField(
  3627. choices=PowerFeedStatusChoices,
  3628. required=False,
  3629. help_text='Operational status'
  3630. )
  3631. type = CSVChoiceField(
  3632. choices=PowerFeedTypeChoices,
  3633. required=False,
  3634. help_text='Primary or redundant'
  3635. )
  3636. supply = CSVChoiceField(
  3637. choices=PowerFeedSupplyChoices,
  3638. required=False,
  3639. help_text='AC/DC'
  3640. )
  3641. phase = CSVChoiceField(
  3642. choices=PowerFeedPhaseChoices,
  3643. required=False,
  3644. help_text='Single or three-phase'
  3645. )
  3646. class Meta:
  3647. model = PowerFeed
  3648. fields = PowerFeed.csv_headers
  3649. def clean(self):
  3650. super().clean()
  3651. site = self.cleaned_data.get('site')
  3652. panel_name = self.cleaned_data.get('panel_name')
  3653. rack_group = self.cleaned_data.get('rack_group')
  3654. rack_name = self.cleaned_data.get('rack_name')
  3655. # Validate power panel
  3656. if panel_name:
  3657. try:
  3658. self.instance.power_panel = PowerPanel.objects.get(site=site, name=panel_name)
  3659. except Rack.DoesNotExist:
  3660. raise forms.ValidationError(
  3661. "Power panel {} not found in site {}".format(panel_name, site)
  3662. )
  3663. # Validate rack
  3664. if rack_name:
  3665. try:
  3666. self.instance.rack = Rack.objects.get(site=site, group__name=rack_group, name=rack_name)
  3667. except Rack.DoesNotExist:
  3668. raise forms.ValidationError(
  3669. "Rack {} not found in site {}, group {}".format(rack_name, site, rack_group)
  3670. )
  3671. class PowerFeedBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldBulkEditForm):
  3672. pk = forms.ModelMultipleChoiceField(
  3673. queryset=PowerFeed.objects.all(),
  3674. widget=forms.MultipleHiddenInput
  3675. )
  3676. powerpanel = forms.ModelChoiceField(
  3677. queryset=PowerPanel.objects.all(),
  3678. required=False,
  3679. widget=APISelect(
  3680. api_url="/api/dcim/power-panels/",
  3681. filter_for={
  3682. 'rackgroup': 'site_id',
  3683. }
  3684. )
  3685. )
  3686. rack = forms.ModelChoiceField(
  3687. queryset=Rack.objects.all(),
  3688. required=False,
  3689. widget=APISelect(
  3690. api_url="/api/dcim/racks",
  3691. )
  3692. )
  3693. status = forms.ChoiceField(
  3694. choices=add_blank_choice(PowerFeedStatusChoices),
  3695. required=False,
  3696. initial='',
  3697. widget=StaticSelect2()
  3698. )
  3699. type = forms.ChoiceField(
  3700. choices=add_blank_choice(PowerFeedTypeChoices),
  3701. required=False,
  3702. initial='',
  3703. widget=StaticSelect2()
  3704. )
  3705. supply = forms.ChoiceField(
  3706. choices=add_blank_choice(PowerFeedSupplyChoices),
  3707. required=False,
  3708. initial='',
  3709. widget=StaticSelect2()
  3710. )
  3711. phase = forms.ChoiceField(
  3712. choices=add_blank_choice(PowerFeedPhaseChoices),
  3713. required=False,
  3714. initial='',
  3715. widget=StaticSelect2()
  3716. )
  3717. voltage = forms.IntegerField(
  3718. required=False
  3719. )
  3720. amperage = forms.IntegerField(
  3721. required=False
  3722. )
  3723. max_utilization = forms.IntegerField(
  3724. required=False
  3725. )
  3726. comments = forms.CharField(
  3727. required=False
  3728. )
  3729. class Meta:
  3730. nullable_fields = [
  3731. 'rackgroup', 'comments',
  3732. ]
  3733. class PowerFeedFilterForm(BootstrapMixin, CustomFieldFilterForm):
  3734. model = PowerFeed
  3735. q = forms.CharField(
  3736. required=False,
  3737. label='Search'
  3738. )
  3739. site = FilterChoiceField(
  3740. queryset=Site.objects.all(),
  3741. to_field_name='slug',
  3742. widget=APISelectMultiple(
  3743. api_url="/api/dcim/sites/",
  3744. value_field="slug",
  3745. filter_for={
  3746. 'power_panel_id': 'site',
  3747. 'rack_id': 'site',
  3748. }
  3749. )
  3750. )
  3751. power_panel_id = FilterChoiceField(
  3752. queryset=PowerPanel.objects.all(),
  3753. label='Power panel',
  3754. null_label='-- None --',
  3755. widget=APISelectMultiple(
  3756. api_url="/api/dcim/power-panels/",
  3757. null_option=True,
  3758. )
  3759. )
  3760. rack_id = FilterChoiceField(
  3761. queryset=Rack.objects.all(),
  3762. label='Rack',
  3763. null_label='-- None --',
  3764. widget=APISelectMultiple(
  3765. api_url="/api/dcim/racks/",
  3766. null_option=True,
  3767. )
  3768. )
  3769. status = forms.MultipleChoiceField(
  3770. choices=PowerFeedStatusChoices,
  3771. required=False,
  3772. widget=StaticSelect2Multiple()
  3773. )
  3774. type = forms.ChoiceField(
  3775. choices=add_blank_choice(PowerFeedTypeChoices),
  3776. required=False,
  3777. widget=StaticSelect2()
  3778. )
  3779. supply = forms.ChoiceField(
  3780. choices=add_blank_choice(PowerFeedSupplyChoices),
  3781. required=False,
  3782. widget=StaticSelect2()
  3783. )
  3784. phase = forms.ChoiceField(
  3785. choices=add_blank_choice(PowerFeedPhaseChoices),
  3786. required=False,
  3787. widget=StaticSelect2()
  3788. )
  3789. voltage = forms.IntegerField(
  3790. required=False
  3791. )
  3792. amperage = forms.IntegerField(
  3793. required=False
  3794. )
  3795. max_utilization = forms.IntegerField(
  3796. required=False
  3797. )