forms.py 134 KB

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