forms.py 152 KB

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