forms.py 152 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262
  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, StaticSelect2, StaticSelect2Multiple, 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=StaticSelect2()
  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': StaticSelect2(),
  290. 'time_zone': StaticSelect2(),
  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=StaticSelect2()
  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=StaticSelect2()
  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=StaticSelect2Multiple()
  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': StaticSelect2(),
  595. 'type': StaticSelect2(),
  596. 'width': StaticSelect2(),
  597. 'outer_unit': StaticSelect2(),
  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=StaticSelect2()
  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=StaticSelect2()
  713. )
  714. width = forms.ChoiceField(
  715. choices=add_blank_choice(RackWidthChoices),
  716. required=False,
  717. widget=StaticSelect2()
  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=StaticSelect2()
  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=StaticSelect2Multiple()
  783. )
  784. type = forms.MultipleChoiceField(
  785. choices=RackTypeChoices,
  786. required=False,
  787. widget=StaticSelect2Multiple()
  788. )
  789. width = forms.MultipleChoiceField(
  790. choices=RackWidthChoices,
  791. required=False,
  792. widget=StaticSelect2Multiple()
  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=StaticSelect2()
  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=StaticSelect2()
  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': StaticSelect2(),
  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=StaticSelect2Multiple()
  1094. )
  1095. console_ports = forms.NullBooleanField(
  1096. required=False,
  1097. label='Has console ports',
  1098. widget=StaticSelect2(
  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=StaticSelect2(
  1106. choices=BOOLEAN_WITH_BLANK_CHOICES
  1107. )
  1108. )
  1109. power_ports = forms.NullBooleanField(
  1110. required=False,
  1111. label='Has power ports',
  1112. widget=StaticSelect2(
  1113. choices=BOOLEAN_WITH_BLANK_CHOICES
  1114. )
  1115. )
  1116. power_outlets = forms.NullBooleanField(
  1117. required=False,
  1118. label='Has power outlets',
  1119. widget=StaticSelect2(
  1120. choices=BOOLEAN_WITH_BLANK_CHOICES
  1121. )
  1122. )
  1123. interfaces = forms.NullBooleanField(
  1124. required=False,
  1125. label='Has interfaces',
  1126. widget=StaticSelect2(
  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=StaticSelect2(
  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=StaticSelect2()
  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=StaticSelect2()
  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=StaticSelect2()
  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=StaticSelect2()
  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=StaticSelect2()
  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=StaticSelect2()
  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=StaticSelect2()
  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=StaticSelect2()
  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': StaticSelect2(),
  1378. }
  1379. class InterfaceTemplateCreateForm(ComponentTemplateCreateForm):
  1380. type = forms.ChoiceField(
  1381. choices=InterfaceTypeChoices,
  1382. widget=StaticSelect2()
  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=StaticSelect2()
  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': StaticSelect2(),
  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=StaticSelect2()
  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=StaticSelect2()
  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': StaticSelect2(),
  1511. }
  1512. class RearPortTemplateCreateForm(ComponentTemplateCreateForm):
  1513. type = forms.ChoiceField(
  1514. choices=PortTypeChoices,
  1515. widget=StaticSelect2(),
  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=StaticSelect2()
  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. }
  1798. )
  1799. )
  1800. manufacturer = DynamicModelChoiceField(
  1801. queryset=Manufacturer.objects.all(),
  1802. required=False,
  1803. initial_params={
  1804. 'device_types': '$device_type'
  1805. }
  1806. )
  1807. device_type = DynamicModelChoiceField(
  1808. queryset=DeviceType.objects.all(),
  1809. query_params={
  1810. 'manufacturer_id': '$manufacturer'
  1811. }
  1812. )
  1813. device_role = DynamicModelChoiceField(
  1814. queryset=DeviceRole.objects.all()
  1815. )
  1816. platform = DynamicModelChoiceField(
  1817. queryset=Platform.objects.all(),
  1818. required=False,
  1819. query_params={
  1820. 'manufacturer_id': ['$manufacturer', 'null']
  1821. }
  1822. )
  1823. cluster_group = DynamicModelChoiceField(
  1824. queryset=ClusterGroup.objects.all(),
  1825. required=False,
  1826. null_option='None',
  1827. initial_params={
  1828. 'clusters': '$cluster'
  1829. }
  1830. )
  1831. cluster = DynamicModelChoiceField(
  1832. queryset=Cluster.objects.all(),
  1833. required=False,
  1834. query_params={
  1835. 'group_id': '$cluster_group'
  1836. }
  1837. )
  1838. comments = CommentField()
  1839. local_context_data = JSONField(
  1840. required=False,
  1841. label=''
  1842. )
  1843. tags = DynamicModelMultipleChoiceField(
  1844. queryset=Tag.objects.all(),
  1845. required=False
  1846. )
  1847. class Meta:
  1848. model = Device
  1849. fields = [
  1850. 'name', 'device_role', 'device_type', 'serial', 'asset_tag', 'region', 'site_group', 'site', 'rack',
  1851. 'location', 'position', 'face', 'status', 'platform', 'primary_ip4', 'primary_ip6', 'cluster_group',
  1852. 'cluster', 'tenant_group', 'tenant', 'comments', 'tags', 'local_context_data'
  1853. ]
  1854. help_texts = {
  1855. 'device_role': "The function this device serves",
  1856. 'serial': "Chassis serial number",
  1857. 'local_context_data': "Local config context data overwrites all source contexts in the final rendered "
  1858. "config context",
  1859. }
  1860. widgets = {
  1861. 'face': StaticSelect2(),
  1862. 'status': StaticSelect2(),
  1863. 'primary_ip4': StaticSelect2(),
  1864. 'primary_ip6': StaticSelect2(),
  1865. }
  1866. def __init__(self, *args, **kwargs):
  1867. super().__init__(*args, **kwargs)
  1868. if self.instance.pk:
  1869. # Compile list of choices for primary IPv4 and IPv6 addresses
  1870. for family in [4, 6]:
  1871. ip_choices = [(None, '---------')]
  1872. # Gather PKs of all interfaces belonging to this Device or a peer VirtualChassis member
  1873. interface_ids = self.instance.vc_interfaces(if_master=False).values_list('pk', flat=True)
  1874. # Collect interface IPs
  1875. interface_ips = IPAddress.objects.filter(
  1876. address__family=family,
  1877. assigned_object_type=ContentType.objects.get_for_model(Interface),
  1878. assigned_object_id__in=interface_ids
  1879. ).prefetch_related('assigned_object')
  1880. if interface_ips:
  1881. ip_list = [(ip.id, f'{ip.address} ({ip.assigned_object})') for ip in interface_ips]
  1882. ip_choices.append(('Interface IPs', ip_list))
  1883. # Collect NAT IPs
  1884. nat_ips = IPAddress.objects.prefetch_related('nat_inside').filter(
  1885. address__family=family,
  1886. nat_inside__assigned_object_type=ContentType.objects.get_for_model(Interface),
  1887. nat_inside__assigned_object_id__in=interface_ids
  1888. ).prefetch_related('assigned_object')
  1889. if nat_ips:
  1890. ip_list = [(ip.id, f'{ip.address} (NAT)') for ip in nat_ips]
  1891. ip_choices.append(('NAT IPs', ip_list))
  1892. self.fields['primary_ip{}'.format(family)].choices = ip_choices
  1893. # If editing an existing device, exclude it from the list of occupied rack units. This ensures that a device
  1894. # can be flipped from one face to another.
  1895. self.fields['position'].widget.add_query_param('exclude', self.instance.pk)
  1896. # Limit platform by manufacturer
  1897. self.fields['platform'].queryset = Platform.objects.filter(
  1898. Q(manufacturer__isnull=True) | Q(manufacturer=self.instance.device_type.manufacturer)
  1899. )
  1900. # Disable rack assignment if this is a child device installed in a parent device
  1901. if self.instance.device_type.is_child_device and hasattr(self.instance, 'parent_bay'):
  1902. self.fields['site'].disabled = True
  1903. self.fields['rack'].disabled = True
  1904. self.initial['site'] = self.instance.parent_bay.device.site_id
  1905. self.initial['rack'] = self.instance.parent_bay.device.rack_id
  1906. else:
  1907. # An object that doesn't exist yet can't have any IPs assigned to it
  1908. self.fields['primary_ip4'].choices = []
  1909. self.fields['primary_ip4'].widget.attrs['readonly'] = True
  1910. self.fields['primary_ip6'].choices = []
  1911. self.fields['primary_ip6'].widget.attrs['readonly'] = True
  1912. # Rack position
  1913. position = self.data.get('position') or self.initial.get('position')
  1914. if position:
  1915. self.fields['position'].widget.choices = [(position, f'U{position}')]
  1916. class BaseDeviceCSVForm(CustomFieldModelCSVForm):
  1917. device_role = CSVModelChoiceField(
  1918. queryset=DeviceRole.objects.all(),
  1919. to_field_name='name',
  1920. help_text='Assigned role'
  1921. )
  1922. tenant = CSVModelChoiceField(
  1923. queryset=Tenant.objects.all(),
  1924. required=False,
  1925. to_field_name='name',
  1926. help_text='Assigned tenant'
  1927. )
  1928. manufacturer = CSVModelChoiceField(
  1929. queryset=Manufacturer.objects.all(),
  1930. to_field_name='name',
  1931. help_text='Device type manufacturer'
  1932. )
  1933. device_type = CSVModelChoiceField(
  1934. queryset=DeviceType.objects.all(),
  1935. to_field_name='model',
  1936. help_text='Device type model'
  1937. )
  1938. platform = CSVModelChoiceField(
  1939. queryset=Platform.objects.all(),
  1940. required=False,
  1941. to_field_name='name',
  1942. help_text='Assigned platform'
  1943. )
  1944. status = CSVChoiceField(
  1945. choices=DeviceStatusChoices,
  1946. help_text='Operational status'
  1947. )
  1948. virtual_chassis = CSVModelChoiceField(
  1949. queryset=VirtualChassis.objects.all(),
  1950. to_field_name='name',
  1951. required=False,
  1952. help_text='Virtual chassis'
  1953. )
  1954. cluster = CSVModelChoiceField(
  1955. queryset=Cluster.objects.all(),
  1956. to_field_name='name',
  1957. required=False,
  1958. help_text='Virtualization cluster'
  1959. )
  1960. class Meta:
  1961. fields = []
  1962. model = Device
  1963. help_texts = {
  1964. 'vc_position': 'Virtual chassis position',
  1965. 'vc_priority': 'Virtual chassis priority',
  1966. }
  1967. def __init__(self, data=None, *args, **kwargs):
  1968. super().__init__(data, *args, **kwargs)
  1969. if data:
  1970. # Limit device type queryset by manufacturer
  1971. params = {f"manufacturer__{self.fields['manufacturer'].to_field_name}": data.get('manufacturer')}
  1972. self.fields['device_type'].queryset = self.fields['device_type'].queryset.filter(**params)
  1973. class DeviceCSVForm(BaseDeviceCSVForm):
  1974. site = CSVModelChoiceField(
  1975. queryset=Site.objects.all(),
  1976. to_field_name='name',
  1977. help_text='Assigned site'
  1978. )
  1979. location = CSVModelChoiceField(
  1980. queryset=Location.objects.all(),
  1981. to_field_name='name',
  1982. required=False,
  1983. help_text="Assigned location (if any)"
  1984. )
  1985. rack = CSVModelChoiceField(
  1986. queryset=Rack.objects.all(),
  1987. to_field_name='name',
  1988. required=False,
  1989. help_text="Assigned rack (if any)"
  1990. )
  1991. face = CSVChoiceField(
  1992. choices=DeviceFaceChoices,
  1993. required=False,
  1994. help_text='Mounted rack face'
  1995. )
  1996. class Meta(BaseDeviceCSVForm.Meta):
  1997. fields = [
  1998. 'name', 'device_role', 'tenant', 'manufacturer', 'device_type', 'platform', 'serial', 'asset_tag', 'status',
  1999. 'site', 'location', 'rack', 'position', 'face', 'virtual_chassis', 'vc_position', 'vc_priority', 'cluster',
  2000. 'comments',
  2001. ]
  2002. def __init__(self, data=None, *args, **kwargs):
  2003. super().__init__(data, *args, **kwargs)
  2004. if data:
  2005. # Limit location queryset by assigned site
  2006. params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
  2007. self.fields['location'].queryset = self.fields['location'].queryset.filter(**params)
  2008. # Limit rack queryset by assigned site and group
  2009. params = {
  2010. f"site__{self.fields['site'].to_field_name}": data.get('site'),
  2011. f"location__{self.fields['location'].to_field_name}": data.get('location'),
  2012. }
  2013. self.fields['rack'].queryset = self.fields['rack'].queryset.filter(**params)
  2014. class ChildDeviceCSVForm(BaseDeviceCSVForm):
  2015. parent = CSVModelChoiceField(
  2016. queryset=Device.objects.all(),
  2017. to_field_name='name',
  2018. help_text='Parent device'
  2019. )
  2020. device_bay = CSVModelChoiceField(
  2021. queryset=DeviceBay.objects.all(),
  2022. to_field_name='name',
  2023. help_text='Device bay in which this device is installed'
  2024. )
  2025. class Meta(BaseDeviceCSVForm.Meta):
  2026. fields = [
  2027. 'name', 'device_role', 'tenant', 'manufacturer', 'device_type', 'platform', 'serial', 'asset_tag', 'status',
  2028. 'parent', 'device_bay', 'virtual_chassis', 'vc_position', 'vc_priority', 'cluster', 'comments',
  2029. ]
  2030. def __init__(self, data=None, *args, **kwargs):
  2031. super().__init__(data, *args, **kwargs)
  2032. if data:
  2033. # Limit device bay queryset by parent device
  2034. params = {f"device__{self.fields['parent'].to_field_name}": data.get('parent')}
  2035. self.fields['device_bay'].queryset = self.fields['device_bay'].queryset.filter(**params)
  2036. def clean(self):
  2037. super().clean()
  2038. # Set parent_bay reverse relationship
  2039. device_bay = self.cleaned_data.get('device_bay')
  2040. if device_bay:
  2041. self.instance.parent_bay = device_bay
  2042. # Inherit site and rack from parent device
  2043. parent = self.cleaned_data.get('parent')
  2044. if parent:
  2045. self.instance.site = parent.site
  2046. self.instance.rack = parent.rack
  2047. class DeviceBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldModelBulkEditForm):
  2048. pk = forms.ModelMultipleChoiceField(
  2049. queryset=Device.objects.all(),
  2050. widget=forms.MultipleHiddenInput()
  2051. )
  2052. manufacturer = DynamicModelChoiceField(
  2053. queryset=Manufacturer.objects.all(),
  2054. required=False
  2055. )
  2056. device_type = DynamicModelChoiceField(
  2057. queryset=DeviceType.objects.all(),
  2058. required=False,
  2059. query_params={
  2060. 'manufacturer_id': '$manufacturer'
  2061. }
  2062. )
  2063. device_role = DynamicModelChoiceField(
  2064. queryset=DeviceRole.objects.all(),
  2065. required=False
  2066. )
  2067. site = DynamicModelChoiceField(
  2068. queryset=Site.objects.all(),
  2069. required=False
  2070. )
  2071. location = DynamicModelChoiceField(
  2072. queryset=Location.objects.all(),
  2073. required=False,
  2074. query_params={
  2075. 'site_id': '$site'
  2076. }
  2077. )
  2078. tenant = DynamicModelChoiceField(
  2079. queryset=Tenant.objects.all(),
  2080. required=False
  2081. )
  2082. platform = DynamicModelChoiceField(
  2083. queryset=Platform.objects.all(),
  2084. required=False
  2085. )
  2086. status = forms.ChoiceField(
  2087. choices=add_blank_choice(DeviceStatusChoices),
  2088. required=False,
  2089. widget=StaticSelect2()
  2090. )
  2091. serial = forms.CharField(
  2092. max_length=50,
  2093. required=False,
  2094. label='Serial Number'
  2095. )
  2096. class Meta:
  2097. nullable_fields = [
  2098. 'tenant', 'platform', 'serial',
  2099. ]
  2100. class DeviceFilterForm(BootstrapMixin, LocalConfigContextFilterForm, TenancyFilterForm, CustomFieldModelFilterForm):
  2101. model = Device
  2102. field_order = [
  2103. 'region_id', 'site_id', 'location_id', 'rack_id', 'status', 'role_id', 'tenant_group_id', 'tenant_id',
  2104. 'manufacturer_id', 'device_type_id', 'asset_tag', 'mac_address', 'has_primary_ip',
  2105. ]
  2106. field_groups = [
  2107. ['region_id', 'site_id', 'location_id', 'rack_id'],
  2108. ['status', 'role_id', 'asset_tag'],
  2109. ['tenant_group_id', 'tenant_id'],
  2110. ['manufacturer_id', 'device_type_id'],
  2111. ['mac_address', 'has_primary_ip'],
  2112. ]
  2113. region_id = DynamicModelMultipleChoiceField(
  2114. queryset=Region.objects.all(),
  2115. required=False,
  2116. label=_('Region')
  2117. )
  2118. site_id = DynamicModelMultipleChoiceField(
  2119. queryset=Site.objects.all(),
  2120. required=False,
  2121. query_params={
  2122. 'region_id': '$region_id'
  2123. },
  2124. label=_('Site')
  2125. )
  2126. location_id = DynamicModelMultipleChoiceField(
  2127. queryset=Location.objects.all(),
  2128. required=False,
  2129. null_option='None',
  2130. query_params={
  2131. 'site_id': '$site_id'
  2132. },
  2133. label=_('Location')
  2134. )
  2135. rack_id = DynamicModelMultipleChoiceField(
  2136. queryset=Rack.objects.all(),
  2137. required=False,
  2138. null_option='None',
  2139. query_params={
  2140. 'site_id': '$site_id',
  2141. 'location_id': '$location_id',
  2142. },
  2143. label=_('Rack')
  2144. )
  2145. role_id = DynamicModelMultipleChoiceField(
  2146. queryset=DeviceRole.objects.all(),
  2147. required=False,
  2148. label=_('Role')
  2149. )
  2150. manufacturer_id = DynamicModelMultipleChoiceField(
  2151. queryset=Manufacturer.objects.all(),
  2152. required=False,
  2153. label=_('Manufacturer')
  2154. )
  2155. device_type_id = DynamicModelMultipleChoiceField(
  2156. queryset=DeviceType.objects.all(),
  2157. required=False,
  2158. query_params={
  2159. 'manufacturer_id': '$manufacturer_id'
  2160. },
  2161. label=_('Model')
  2162. )
  2163. platform_id = DynamicModelMultipleChoiceField(
  2164. queryset=Platform.objects.all(),
  2165. required=False,
  2166. null_option='None',
  2167. label=_('Platform')
  2168. )
  2169. status = forms.MultipleChoiceField(
  2170. choices=DeviceStatusChoices,
  2171. required=False,
  2172. widget=StaticSelect2Multiple()
  2173. )
  2174. asset_tag = forms.CharField(
  2175. required=False
  2176. )
  2177. mac_address = forms.CharField(
  2178. required=False,
  2179. label='MAC address'
  2180. )
  2181. has_primary_ip = forms.NullBooleanField(
  2182. required=False,
  2183. label='Has a primary IP',
  2184. widget=StaticSelect2(
  2185. choices=BOOLEAN_WITH_BLANK_CHOICES
  2186. )
  2187. )
  2188. virtual_chassis_member = forms.NullBooleanField(
  2189. required=False,
  2190. label='Virtual chassis member',
  2191. widget=StaticSelect2(
  2192. choices=BOOLEAN_WITH_BLANK_CHOICES
  2193. )
  2194. )
  2195. console_ports = forms.NullBooleanField(
  2196. required=False,
  2197. label='Has console ports',
  2198. widget=StaticSelect2(
  2199. choices=BOOLEAN_WITH_BLANK_CHOICES
  2200. )
  2201. )
  2202. console_server_ports = forms.NullBooleanField(
  2203. required=False,
  2204. label='Has console server ports',
  2205. widget=StaticSelect2(
  2206. choices=BOOLEAN_WITH_BLANK_CHOICES
  2207. )
  2208. )
  2209. power_ports = forms.NullBooleanField(
  2210. required=False,
  2211. label='Has power ports',
  2212. widget=StaticSelect2(
  2213. choices=BOOLEAN_WITH_BLANK_CHOICES
  2214. )
  2215. )
  2216. power_outlets = forms.NullBooleanField(
  2217. required=False,
  2218. label='Has power outlets',
  2219. widget=StaticSelect2(
  2220. choices=BOOLEAN_WITH_BLANK_CHOICES
  2221. )
  2222. )
  2223. interfaces = forms.NullBooleanField(
  2224. required=False,
  2225. label='Has interfaces',
  2226. widget=StaticSelect2(
  2227. choices=BOOLEAN_WITH_BLANK_CHOICES
  2228. )
  2229. )
  2230. pass_through_ports = forms.NullBooleanField(
  2231. required=False,
  2232. label='Has pass-through ports',
  2233. widget=StaticSelect2(
  2234. choices=BOOLEAN_WITH_BLANK_CHOICES
  2235. )
  2236. )
  2237. tag = TagFilterField(model)
  2238. #
  2239. # Device components
  2240. #
  2241. class ComponentCreateForm(BootstrapMixin, CustomFieldsMixin, ComponentForm):
  2242. """
  2243. Base form for the creation of device components (models subclassed from ComponentModel).
  2244. """
  2245. device = DynamicModelChoiceField(
  2246. queryset=Device.objects.all()
  2247. )
  2248. description = forms.CharField(
  2249. max_length=200,
  2250. required=False
  2251. )
  2252. tags = DynamicModelMultipleChoiceField(
  2253. queryset=Tag.objects.all(),
  2254. required=False
  2255. )
  2256. class DeviceBulkAddComponentForm(BootstrapMixin, CustomFieldsMixin, ComponentForm):
  2257. pk = forms.ModelMultipleChoiceField(
  2258. queryset=Device.objects.all(),
  2259. widget=forms.MultipleHiddenInput()
  2260. )
  2261. description = forms.CharField(
  2262. max_length=100,
  2263. required=False
  2264. )
  2265. tags = DynamicModelMultipleChoiceField(
  2266. queryset=Tag.objects.all(),
  2267. required=False
  2268. )
  2269. #
  2270. # Console ports
  2271. #
  2272. class ConsolePortFilterForm(DeviceComponentFilterForm):
  2273. model = ConsolePort
  2274. field_groups = [
  2275. ['name', 'label'],
  2276. ['type', 'speed'],
  2277. ['region_id', 'site_group_id', 'site_id'],
  2278. ['tag']
  2279. ]
  2280. type = forms.MultipleChoiceField(
  2281. choices=ConsolePortTypeChoices,
  2282. required=False,
  2283. widget=StaticSelect2Multiple()
  2284. )
  2285. speed = forms.MultipleChoiceField(
  2286. choices=ConsolePortSpeedChoices,
  2287. required=False,
  2288. widget=StaticSelect2Multiple()
  2289. )
  2290. tag = TagFilterField(model)
  2291. class ConsolePortForm(BootstrapMixin, CustomFieldModelForm):
  2292. tags = DynamicModelMultipleChoiceField(
  2293. queryset=Tag.objects.all(),
  2294. required=False
  2295. )
  2296. class Meta:
  2297. model = ConsolePort
  2298. fields = [
  2299. 'device', 'name', 'label', 'type', 'speed', 'mark_connected', 'description', 'tags',
  2300. ]
  2301. widgets = {
  2302. 'device': forms.HiddenInput(),
  2303. }
  2304. class ConsolePortCreateForm(ComponentCreateForm):
  2305. model = ConsolePort
  2306. type = forms.ChoiceField(
  2307. choices=add_blank_choice(ConsolePortTypeChoices),
  2308. required=False,
  2309. widget=StaticSelect2()
  2310. )
  2311. speed = forms.ChoiceField(
  2312. choices=add_blank_choice(ConsolePortSpeedChoices),
  2313. required=False,
  2314. widget=StaticSelect2()
  2315. )
  2316. field_order = ('device', 'name_pattern', 'label_pattern', 'type', 'speed', 'mark_connected', 'description', 'tags')
  2317. class ConsolePortBulkCreateForm(
  2318. form_from_model(ConsolePort, ['type', 'speed', 'mark_connected']),
  2319. DeviceBulkAddComponentForm
  2320. ):
  2321. model = ConsolePort
  2322. field_order = ('name_pattern', 'label_pattern', 'type', 'mark_connected', 'description', 'tags')
  2323. class ConsolePortBulkEditForm(
  2324. form_from_model(ConsolePort, ['label', 'type', 'speed', 'mark_connected', 'description']),
  2325. BootstrapMixin,
  2326. AddRemoveTagsForm,
  2327. CustomFieldModelBulkEditForm
  2328. ):
  2329. pk = forms.ModelMultipleChoiceField(
  2330. queryset=ConsolePort.objects.all(),
  2331. widget=forms.MultipleHiddenInput()
  2332. )
  2333. mark_connected = forms.NullBooleanField(
  2334. required=False,
  2335. widget=BulkEditNullBooleanSelect
  2336. )
  2337. class Meta:
  2338. nullable_fields = ['label', 'description']
  2339. class ConsolePortCSVForm(CustomFieldModelCSVForm):
  2340. device = CSVModelChoiceField(
  2341. queryset=Device.objects.all(),
  2342. to_field_name='name'
  2343. )
  2344. type = CSVChoiceField(
  2345. choices=ConsolePortTypeChoices,
  2346. required=False,
  2347. help_text='Port type'
  2348. )
  2349. speed = CSVTypedChoiceField(
  2350. choices=ConsolePortSpeedChoices,
  2351. coerce=int,
  2352. empty_value=None,
  2353. required=False,
  2354. help_text='Port speed in bps'
  2355. )
  2356. class Meta:
  2357. model = ConsolePort
  2358. fields = ('device', 'name', 'label', 'type', 'speed', 'mark_connected', 'description')
  2359. #
  2360. # Console server ports
  2361. #
  2362. class ConsoleServerPortFilterForm(DeviceComponentFilterForm):
  2363. model = ConsoleServerPort
  2364. field_groups = [
  2365. ['name', 'label'],
  2366. ['type', 'speed'],
  2367. ['region_id', 'site_group_id', 'site_id'],
  2368. ['tag']
  2369. ]
  2370. type = forms.MultipleChoiceField(
  2371. choices=ConsolePortTypeChoices,
  2372. required=False,
  2373. widget=StaticSelect2Multiple()
  2374. )
  2375. speed = forms.MultipleChoiceField(
  2376. choices=ConsolePortSpeedChoices,
  2377. required=False,
  2378. widget=StaticSelect2Multiple()
  2379. )
  2380. tag = TagFilterField(model)
  2381. class ConsoleServerPortForm(BootstrapMixin, CustomFieldModelForm):
  2382. tags = DynamicModelMultipleChoiceField(
  2383. queryset=Tag.objects.all(),
  2384. required=False
  2385. )
  2386. class Meta:
  2387. model = ConsoleServerPort
  2388. fields = [
  2389. 'device', 'name', 'label', 'type', 'speed', 'mark_connected', 'description', 'tags',
  2390. ]
  2391. widgets = {
  2392. 'device': forms.HiddenInput(),
  2393. }
  2394. class ConsoleServerPortCreateForm(ComponentCreateForm):
  2395. model = ConsoleServerPort
  2396. type = forms.ChoiceField(
  2397. choices=add_blank_choice(ConsolePortTypeChoices),
  2398. required=False,
  2399. widget=StaticSelect2()
  2400. )
  2401. speed = forms.ChoiceField(
  2402. choices=add_blank_choice(ConsolePortSpeedChoices),
  2403. required=False,
  2404. widget=StaticSelect2()
  2405. )
  2406. field_order = ('device', 'name_pattern', 'label_pattern', 'type', 'speed', 'mark_connected', 'description', 'tags')
  2407. class ConsoleServerPortBulkCreateForm(
  2408. form_from_model(ConsoleServerPort, ['type', 'speed', 'mark_connected']),
  2409. DeviceBulkAddComponentForm
  2410. ):
  2411. model = ConsoleServerPort
  2412. field_order = ('name_pattern', 'label_pattern', 'type', 'speed', 'description', 'tags')
  2413. class ConsoleServerPortBulkEditForm(
  2414. form_from_model(ConsoleServerPort, ['label', 'type', 'speed', 'mark_connected', 'description']),
  2415. BootstrapMixin,
  2416. AddRemoveTagsForm,
  2417. CustomFieldModelBulkEditForm
  2418. ):
  2419. pk = forms.ModelMultipleChoiceField(
  2420. queryset=ConsoleServerPort.objects.all(),
  2421. widget=forms.MultipleHiddenInput()
  2422. )
  2423. mark_connected = forms.NullBooleanField(
  2424. required=False,
  2425. widget=BulkEditNullBooleanSelect
  2426. )
  2427. class Meta:
  2428. nullable_fields = ['label', 'description']
  2429. class ConsoleServerPortCSVForm(CustomFieldModelCSVForm):
  2430. device = CSVModelChoiceField(
  2431. queryset=Device.objects.all(),
  2432. to_field_name='name'
  2433. )
  2434. type = CSVChoiceField(
  2435. choices=ConsolePortTypeChoices,
  2436. required=False,
  2437. help_text='Port type'
  2438. )
  2439. speed = CSVTypedChoiceField(
  2440. choices=ConsolePortSpeedChoices,
  2441. coerce=int,
  2442. empty_value=None,
  2443. required=False,
  2444. help_text='Port speed in bps'
  2445. )
  2446. class Meta:
  2447. model = ConsoleServerPort
  2448. fields = ('device', 'name', 'label', 'type', 'speed', 'mark_connected', 'description')
  2449. #
  2450. # Power ports
  2451. #
  2452. class PowerPortFilterForm(DeviceComponentFilterForm):
  2453. model = PowerPort
  2454. field_groups = [
  2455. ['name', 'label', 'type'],
  2456. ['region_id', 'site_group_id', 'site_id'],
  2457. ['tag'],
  2458. ]
  2459. type = forms.MultipleChoiceField(
  2460. choices=PowerPortTypeChoices,
  2461. required=False,
  2462. widget=StaticSelect2Multiple()
  2463. )
  2464. tag = TagFilterField(model)
  2465. class PowerPortForm(BootstrapMixin, CustomFieldModelForm):
  2466. tags = DynamicModelMultipleChoiceField(
  2467. queryset=Tag.objects.all(),
  2468. required=False
  2469. )
  2470. class Meta:
  2471. model = PowerPort
  2472. fields = [
  2473. 'device', 'name', 'label', 'type', 'maximum_draw', 'allocated_draw', 'mark_connected', 'description',
  2474. 'tags',
  2475. ]
  2476. widgets = {
  2477. 'device': forms.HiddenInput(),
  2478. }
  2479. class PowerPortCreateForm(ComponentCreateForm):
  2480. model = PowerPort
  2481. type = forms.ChoiceField(
  2482. choices=add_blank_choice(PowerPortTypeChoices),
  2483. required=False,
  2484. widget=StaticSelect2()
  2485. )
  2486. maximum_draw = forms.IntegerField(
  2487. min_value=1,
  2488. required=False,
  2489. help_text="Maximum draw in watts"
  2490. )
  2491. allocated_draw = forms.IntegerField(
  2492. min_value=1,
  2493. required=False,
  2494. help_text="Allocated draw in watts"
  2495. )
  2496. field_order = (
  2497. 'device', 'name_pattern', 'label_pattern', 'type', 'maximum_draw', 'allocated_draw', 'mark_connected',
  2498. 'description', 'tags',
  2499. )
  2500. class PowerPortBulkCreateForm(
  2501. form_from_model(PowerPort, ['type', 'maximum_draw', 'allocated_draw', 'mark_connected']),
  2502. DeviceBulkAddComponentForm
  2503. ):
  2504. model = PowerPort
  2505. field_order = ('name_pattern', 'label_pattern', 'type', 'maximum_draw', 'allocated_draw', 'description', 'tags')
  2506. class PowerPortBulkEditForm(
  2507. form_from_model(PowerPort, ['label', 'type', 'maximum_draw', 'allocated_draw', 'mark_connected', 'description']),
  2508. BootstrapMixin,
  2509. AddRemoveTagsForm,
  2510. CustomFieldModelBulkEditForm
  2511. ):
  2512. pk = forms.ModelMultipleChoiceField(
  2513. queryset=PowerPort.objects.all(),
  2514. widget=forms.MultipleHiddenInput()
  2515. )
  2516. mark_connected = forms.NullBooleanField(
  2517. required=False,
  2518. widget=BulkEditNullBooleanSelect
  2519. )
  2520. class Meta:
  2521. nullable_fields = ['label', 'description']
  2522. class PowerPortCSVForm(CustomFieldModelCSVForm):
  2523. device = CSVModelChoiceField(
  2524. queryset=Device.objects.all(),
  2525. to_field_name='name'
  2526. )
  2527. type = CSVChoiceField(
  2528. choices=PowerPortTypeChoices,
  2529. required=False,
  2530. help_text='Port type'
  2531. )
  2532. class Meta:
  2533. model = PowerPort
  2534. fields = (
  2535. 'device', 'name', 'label', 'type', 'mark_connected', 'maximum_draw', 'allocated_draw', 'description',
  2536. )
  2537. #
  2538. # Power outlets
  2539. #
  2540. class PowerOutletFilterForm(DeviceComponentFilterForm):
  2541. model = PowerOutlet
  2542. field_groups = [
  2543. ['name', 'label', 'type'],
  2544. ['region_id', 'site_group_id', 'site_id'],
  2545. ['tag'],
  2546. ]
  2547. type = forms.MultipleChoiceField(
  2548. choices=PowerOutletTypeChoices,
  2549. required=False,
  2550. widget=StaticSelect2Multiple()
  2551. )
  2552. tag = TagFilterField(model)
  2553. class PowerOutletForm(BootstrapMixin, CustomFieldModelForm):
  2554. power_port = forms.ModelChoiceField(
  2555. queryset=PowerPort.objects.all(),
  2556. required=False
  2557. )
  2558. tags = DynamicModelMultipleChoiceField(
  2559. queryset=Tag.objects.all(),
  2560. required=False
  2561. )
  2562. class Meta:
  2563. model = PowerOutlet
  2564. fields = [
  2565. 'device', 'name', 'label', 'type', 'power_port', 'feed_leg', 'mark_connected', 'description', 'tags',
  2566. ]
  2567. widgets = {
  2568. 'device': forms.HiddenInput(),
  2569. }
  2570. def __init__(self, *args, **kwargs):
  2571. super().__init__(*args, **kwargs)
  2572. # Limit power_port choices to the local device
  2573. if hasattr(self.instance, 'device'):
  2574. self.fields['power_port'].queryset = PowerPort.objects.filter(
  2575. device=self.instance.device
  2576. )
  2577. class PowerOutletCreateForm(ComponentCreateForm):
  2578. model = PowerOutlet
  2579. type = forms.ChoiceField(
  2580. choices=add_blank_choice(PowerOutletTypeChoices),
  2581. required=False,
  2582. widget=StaticSelect2()
  2583. )
  2584. power_port = forms.ModelChoiceField(
  2585. queryset=PowerPort.objects.all(),
  2586. required=False
  2587. )
  2588. feed_leg = forms.ChoiceField(
  2589. choices=add_blank_choice(PowerOutletFeedLegChoices),
  2590. required=False
  2591. )
  2592. field_order = (
  2593. 'device', 'name_pattern', 'label_pattern', 'type', 'power_port', 'feed_leg', 'mark_connected', 'description',
  2594. 'tags',
  2595. )
  2596. def __init__(self, *args, **kwargs):
  2597. super().__init__(*args, **kwargs)
  2598. # Limit power_port queryset to PowerPorts which belong to the parent Device
  2599. device = Device.objects.get(
  2600. pk=self.initial.get('device') or self.data.get('device')
  2601. )
  2602. self.fields['power_port'].queryset = PowerPort.objects.filter(device=device)
  2603. class PowerOutletBulkCreateForm(
  2604. form_from_model(PowerOutlet, ['type', 'feed_leg', 'mark_connected']),
  2605. DeviceBulkAddComponentForm
  2606. ):
  2607. model = PowerOutlet
  2608. field_order = ('name_pattern', 'label_pattern', 'type', 'feed_leg', 'description', 'tags')
  2609. class PowerOutletBulkEditForm(
  2610. form_from_model(PowerOutlet, ['label', 'type', 'feed_leg', 'power_port', 'mark_connected', 'description']),
  2611. BootstrapMixin,
  2612. AddRemoveTagsForm,
  2613. CustomFieldModelBulkEditForm
  2614. ):
  2615. pk = forms.ModelMultipleChoiceField(
  2616. queryset=PowerOutlet.objects.all(),
  2617. widget=forms.MultipleHiddenInput()
  2618. )
  2619. device = forms.ModelChoiceField(
  2620. queryset=Device.objects.all(),
  2621. required=False,
  2622. disabled=True,
  2623. widget=forms.HiddenInput()
  2624. )
  2625. mark_connected = forms.NullBooleanField(
  2626. required=False,
  2627. widget=BulkEditNullBooleanSelect
  2628. )
  2629. class Meta:
  2630. nullable_fields = ['label', 'type', 'feed_leg', 'power_port', 'description']
  2631. def __init__(self, *args, **kwargs):
  2632. super().__init__(*args, **kwargs)
  2633. # Limit power_port queryset to PowerPorts which belong to the parent Device
  2634. if 'device' in self.initial:
  2635. device = Device.objects.filter(pk=self.initial['device']).first()
  2636. self.fields['power_port'].queryset = PowerPort.objects.filter(device=device)
  2637. else:
  2638. self.fields['power_port'].choices = ()
  2639. self.fields['power_port'].widget.attrs['disabled'] = True
  2640. class PowerOutletCSVForm(CustomFieldModelCSVForm):
  2641. device = CSVModelChoiceField(
  2642. queryset=Device.objects.all(),
  2643. to_field_name='name'
  2644. )
  2645. type = CSVChoiceField(
  2646. choices=PowerOutletTypeChoices,
  2647. required=False,
  2648. help_text='Outlet type'
  2649. )
  2650. power_port = CSVModelChoiceField(
  2651. queryset=PowerPort.objects.all(),
  2652. required=False,
  2653. to_field_name='name',
  2654. help_text='Local power port which feeds this outlet'
  2655. )
  2656. feed_leg = CSVChoiceField(
  2657. choices=PowerOutletFeedLegChoices,
  2658. required=False,
  2659. help_text='Electrical phase (for three-phase circuits)'
  2660. )
  2661. class Meta:
  2662. model = PowerOutlet
  2663. fields = ('device', 'name', 'label', 'type', 'mark_connected', 'power_port', 'feed_leg', 'description')
  2664. def __init__(self, *args, **kwargs):
  2665. super().__init__(*args, **kwargs)
  2666. # Limit PowerPort choices to those belonging to this device (or VC master)
  2667. if self.is_bound:
  2668. try:
  2669. device = self.fields['device'].to_python(self.data['device'])
  2670. except forms.ValidationError:
  2671. device = None
  2672. else:
  2673. try:
  2674. device = self.instance.device
  2675. except Device.DoesNotExist:
  2676. device = None
  2677. if device:
  2678. self.fields['power_port'].queryset = PowerPort.objects.filter(
  2679. device__in=[device, device.get_vc_master()]
  2680. )
  2681. else:
  2682. self.fields['power_port'].queryset = PowerPort.objects.none()
  2683. #
  2684. # Interfaces
  2685. #
  2686. class InterfaceFilterForm(DeviceComponentFilterForm):
  2687. model = Interface
  2688. field_groups = [
  2689. ['name', 'label', 'type', 'enabled'],
  2690. ['mgmt_only', 'mac_address'],
  2691. ['region_id', 'site_group_id', 'site_id'],
  2692. ['tag'],
  2693. ]
  2694. type = forms.MultipleChoiceField(
  2695. choices=InterfaceTypeChoices,
  2696. required=False,
  2697. widget=StaticSelect2Multiple()
  2698. )
  2699. enabled = forms.NullBooleanField(
  2700. required=False,
  2701. widget=StaticSelect2(
  2702. choices=BOOLEAN_WITH_BLANK_CHOICES
  2703. )
  2704. )
  2705. mgmt_only = forms.NullBooleanField(
  2706. required=False,
  2707. widget=StaticSelect2(
  2708. choices=BOOLEAN_WITH_BLANK_CHOICES
  2709. )
  2710. )
  2711. mac_address = forms.CharField(
  2712. required=False,
  2713. label='MAC address'
  2714. )
  2715. tag = TagFilterField(model)
  2716. class InterfaceForm(BootstrapMixin, InterfaceCommonForm, CustomFieldModelForm):
  2717. parent = DynamicModelChoiceField(
  2718. queryset=Interface.objects.all(),
  2719. required=False,
  2720. label='Parent interface'
  2721. )
  2722. lag = DynamicModelChoiceField(
  2723. queryset=Interface.objects.all(),
  2724. required=False,
  2725. label='LAG interface',
  2726. query_params={
  2727. 'type': 'lag',
  2728. }
  2729. )
  2730. untagged_vlan = DynamicModelChoiceField(
  2731. queryset=VLAN.objects.all(),
  2732. required=False,
  2733. label='Untagged VLAN'
  2734. )
  2735. tagged_vlans = DynamicModelMultipleChoiceField(
  2736. queryset=VLAN.objects.all(),
  2737. required=False,
  2738. label='Tagged VLANs'
  2739. )
  2740. tags = DynamicModelMultipleChoiceField(
  2741. queryset=Tag.objects.all(),
  2742. required=False
  2743. )
  2744. class Meta:
  2745. model = Interface
  2746. fields = [
  2747. 'device', 'name', 'label', 'type', 'enabled', 'parent', 'lag', 'mac_address', 'mtu', 'mgmt_only',
  2748. 'mark_connected', 'description', 'mode', 'untagged_vlan', 'tagged_vlans', 'tags',
  2749. ]
  2750. widgets = {
  2751. 'device': forms.HiddenInput(),
  2752. 'type': StaticSelect2(),
  2753. 'mode': StaticSelect2(),
  2754. }
  2755. labels = {
  2756. 'mode': '802.1Q Mode',
  2757. }
  2758. help_texts = {
  2759. 'mode': INTERFACE_MODE_HELP_TEXT,
  2760. }
  2761. def __init__(self, *args, **kwargs):
  2762. super().__init__(*args, **kwargs)
  2763. device = Device.objects.get(pk=self.data['device']) if self.is_bound else self.instance.device
  2764. # Restrict parent/LAG interface assignment by device/VC
  2765. self.fields['parent'].widget.add_query_param('device_id', device.pk)
  2766. if device.virtual_chassis and device.virtual_chassis.master:
  2767. # Get available LAG interfaces by VirtualChassis master
  2768. self.fields['lag'].widget.add_query_param('device_id', device.virtual_chassis.master.pk)
  2769. else:
  2770. self.fields['lag'].widget.add_query_param('device_id', device.pk)
  2771. # Limit VLAN choices by device
  2772. self.fields['untagged_vlan'].widget.add_query_param('available_on_device', device.pk)
  2773. self.fields['tagged_vlans'].widget.add_query_param('available_on_device', device.pk)
  2774. class InterfaceCreateForm(ComponentCreateForm, InterfaceCommonForm):
  2775. model = Interface
  2776. type = forms.ChoiceField(
  2777. choices=InterfaceTypeChoices,
  2778. widget=StaticSelect2(),
  2779. )
  2780. enabled = forms.BooleanField(
  2781. required=False,
  2782. initial=True
  2783. )
  2784. parent = DynamicModelChoiceField(
  2785. queryset=Interface.objects.all(),
  2786. required=False,
  2787. query_params={
  2788. 'device_id': '$device',
  2789. }
  2790. )
  2791. lag = DynamicModelChoiceField(
  2792. queryset=Interface.objects.all(),
  2793. required=False,
  2794. query_params={
  2795. 'device_id': '$device',
  2796. 'type': 'lag',
  2797. }
  2798. )
  2799. mtu = forms.IntegerField(
  2800. required=False,
  2801. min_value=INTERFACE_MTU_MIN,
  2802. max_value=INTERFACE_MTU_MAX,
  2803. label='MTU'
  2804. )
  2805. mac_address = forms.CharField(
  2806. required=False,
  2807. label='MAC Address'
  2808. )
  2809. mgmt_only = forms.BooleanField(
  2810. required=False,
  2811. label='Management only',
  2812. help_text='This interface is used only for out-of-band management'
  2813. )
  2814. mode = forms.ChoiceField(
  2815. choices=add_blank_choice(InterfaceModeChoices),
  2816. required=False,
  2817. widget=StaticSelect2(),
  2818. )
  2819. untagged_vlan = DynamicModelChoiceField(
  2820. queryset=VLAN.objects.all(),
  2821. required=False
  2822. )
  2823. tagged_vlans = DynamicModelMultipleChoiceField(
  2824. queryset=VLAN.objects.all(),
  2825. required=False
  2826. )
  2827. field_order = (
  2828. 'device', 'name_pattern', 'label_pattern', 'type', 'enabled', 'parent', 'lag', 'mtu', 'mac_address',
  2829. 'description', 'mgmt_only', 'mark_connected', 'mode', 'untagged_vlan', 'tagged_vlans', 'tags'
  2830. )
  2831. def __init__(self, *args, **kwargs):
  2832. super().__init__(*args, **kwargs)
  2833. # Limit VLAN choices by device
  2834. device_id = self.initial.get('device') or self.data.get('device')
  2835. self.fields['untagged_vlan'].widget.add_query_param('available_on_device', device_id)
  2836. self.fields['tagged_vlans'].widget.add_query_param('available_on_device', device_id)
  2837. class InterfaceBulkCreateForm(
  2838. form_from_model(Interface, ['type', 'enabled', 'mtu', 'mgmt_only', 'mark_connected']),
  2839. DeviceBulkAddComponentForm
  2840. ):
  2841. model = Interface
  2842. field_order = (
  2843. 'name_pattern', 'label_pattern', 'type', 'enabled', 'mtu', 'mgmt_only', 'mark_connected', 'description', 'tags',
  2844. )
  2845. class InterfaceBulkEditForm(
  2846. form_from_model(Interface, [
  2847. 'label', 'type', 'parent', 'lag', 'mac_address', 'mtu', 'mgmt_only', 'mark_connected', 'description', 'mode',
  2848. ]),
  2849. BootstrapMixin,
  2850. AddRemoveTagsForm,
  2851. CustomFieldModelBulkEditForm
  2852. ):
  2853. pk = forms.ModelMultipleChoiceField(
  2854. queryset=Interface.objects.all(),
  2855. widget=forms.MultipleHiddenInput()
  2856. )
  2857. device = forms.ModelChoiceField(
  2858. queryset=Device.objects.all(),
  2859. required=False,
  2860. disabled=True,
  2861. widget=forms.HiddenInput()
  2862. )
  2863. enabled = forms.NullBooleanField(
  2864. required=False,
  2865. widget=BulkEditNullBooleanSelect
  2866. )
  2867. parent = DynamicModelChoiceField(
  2868. queryset=Interface.objects.all(),
  2869. required=False
  2870. )
  2871. lag = DynamicModelChoiceField(
  2872. queryset=Interface.objects.all(),
  2873. required=False,
  2874. query_params={
  2875. 'type': 'lag',
  2876. }
  2877. )
  2878. mgmt_only = forms.NullBooleanField(
  2879. required=False,
  2880. widget=BulkEditNullBooleanSelect,
  2881. label='Management only'
  2882. )
  2883. mark_connected = forms.NullBooleanField(
  2884. required=False,
  2885. widget=BulkEditNullBooleanSelect
  2886. )
  2887. untagged_vlan = DynamicModelChoiceField(
  2888. queryset=VLAN.objects.all(),
  2889. required=False
  2890. )
  2891. tagged_vlans = DynamicModelMultipleChoiceField(
  2892. queryset=VLAN.objects.all(),
  2893. required=False
  2894. )
  2895. class Meta:
  2896. nullable_fields = [
  2897. 'label', 'parent', 'lag', 'mac_address', 'mtu', 'description', 'mode', 'untagged_vlan', 'tagged_vlans'
  2898. ]
  2899. def __init__(self, *args, **kwargs):
  2900. super().__init__(*args, **kwargs)
  2901. if 'device' in self.initial:
  2902. device = Device.objects.filter(pk=self.initial['device']).first()
  2903. # Restrict parent/LAG interface assignment by device
  2904. self.fields['parent'].widget.add_query_param('device_id', device.pk)
  2905. self.fields['lag'].widget.add_query_param('device_id', device.pk)
  2906. # Limit VLAN choices by device
  2907. self.fields['untagged_vlan'].widget.add_query_param('available_on_device', device.pk)
  2908. self.fields['tagged_vlans'].widget.add_query_param('available_on_device', device.pk)
  2909. else:
  2910. # See #4523
  2911. if 'pk' in self.initial:
  2912. site = None
  2913. interfaces = Interface.objects.filter(pk__in=self.initial['pk']).prefetch_related('device__site')
  2914. # Check interface sites. First interface should set site, further interfaces will either continue the
  2915. # loop or reset back to no site and break the loop.
  2916. for interface in interfaces:
  2917. if site is None:
  2918. site = interface.device.site
  2919. elif interface.device.site is not site:
  2920. site = None
  2921. break
  2922. if site is not None:
  2923. self.fields['untagged_vlan'].widget.add_query_param('site_id', site.pk)
  2924. self.fields['tagged_vlans'].widget.add_query_param('site_id', site.pk)
  2925. self.fields['parent'].choices = ()
  2926. self.fields['parent'].widget.attrs['disabled'] = True
  2927. self.fields['lag'].choices = ()
  2928. self.fields['lag'].widget.attrs['disabled'] = True
  2929. def clean(self):
  2930. super().clean()
  2931. # Untagged interfaces cannot be assigned tagged VLANs
  2932. if self.cleaned_data['mode'] == InterfaceModeChoices.MODE_ACCESS and self.cleaned_data['tagged_vlans']:
  2933. raise forms.ValidationError({
  2934. 'mode': "An access interface cannot have tagged VLANs assigned."
  2935. })
  2936. # Remove all tagged VLAN assignments from "tagged all" interfaces
  2937. elif self.cleaned_data['mode'] == InterfaceModeChoices.MODE_TAGGED_ALL:
  2938. self.cleaned_data['tagged_vlans'] = []
  2939. class InterfaceCSVForm(CustomFieldModelCSVForm):
  2940. device = CSVModelChoiceField(
  2941. queryset=Device.objects.all(),
  2942. to_field_name='name'
  2943. )
  2944. parent = CSVModelChoiceField(
  2945. queryset=Interface.objects.all(),
  2946. required=False,
  2947. to_field_name='name',
  2948. help_text='Parent interface'
  2949. )
  2950. lag = CSVModelChoiceField(
  2951. queryset=Interface.objects.all(),
  2952. required=False,
  2953. to_field_name='name',
  2954. help_text='Parent LAG interface'
  2955. )
  2956. type = CSVChoiceField(
  2957. choices=InterfaceTypeChoices,
  2958. help_text='Physical medium'
  2959. )
  2960. mode = CSVChoiceField(
  2961. choices=InterfaceModeChoices,
  2962. required=False,
  2963. help_text='IEEE 802.1Q operational mode (for L2 interfaces)'
  2964. )
  2965. class Meta:
  2966. model = Interface
  2967. fields = (
  2968. 'device', 'name', 'label', 'parent', 'lag', 'type', 'enabled', 'mark_connected', 'mac_address', 'mtu',
  2969. 'mgmt_only', 'description', 'mode',
  2970. )
  2971. def __init__(self, *args, **kwargs):
  2972. super().__init__(*args, **kwargs)
  2973. # Limit LAG choices to interfaces belonging to this device (or virtual chassis)
  2974. device = None
  2975. if self.is_bound and 'device' in self.data:
  2976. try:
  2977. device = self.fields['device'].to_python(self.data['device'])
  2978. except forms.ValidationError:
  2979. pass
  2980. if device and device.virtual_chassis:
  2981. self.fields['lag'].queryset = Interface.objects.filter(
  2982. Q(device=device) | Q(device__virtual_chassis=device.virtual_chassis),
  2983. type=InterfaceTypeChoices.TYPE_LAG
  2984. )
  2985. elif device:
  2986. self.fields['lag'].queryset = Interface.objects.filter(
  2987. device=device,
  2988. type=InterfaceTypeChoices.TYPE_LAG
  2989. )
  2990. else:
  2991. self.fields['lag'].queryset = Interface.objects.none()
  2992. def clean_enabled(self):
  2993. # Make sure enabled is True when it's not included in the uploaded data
  2994. if 'enabled' not in self.data:
  2995. return True
  2996. else:
  2997. return self.cleaned_data['enabled']
  2998. #
  2999. # Front pass-through ports
  3000. #
  3001. class FrontPortFilterForm(DeviceComponentFilterForm):
  3002. field_groups = [
  3003. ['name', 'label', 'type', 'color'],
  3004. ['region_id', 'site_group_id', 'site_id'],
  3005. ['tag']
  3006. ]
  3007. model = FrontPort
  3008. type = forms.MultipleChoiceField(
  3009. choices=PortTypeChoices,
  3010. required=False,
  3011. widget=StaticSelect2Multiple()
  3012. )
  3013. color = ColorField(
  3014. required=False
  3015. )
  3016. tag = TagFilterField(model)
  3017. class FrontPortForm(BootstrapMixin, CustomFieldModelForm):
  3018. tags = DynamicModelMultipleChoiceField(
  3019. queryset=Tag.objects.all(),
  3020. required=False
  3021. )
  3022. class Meta:
  3023. model = FrontPort
  3024. fields = [
  3025. 'device', 'name', 'label', 'type', 'color', 'rear_port', 'rear_port_position', 'mark_connected',
  3026. 'description', 'tags',
  3027. ]
  3028. widgets = {
  3029. 'device': forms.HiddenInput(),
  3030. 'type': StaticSelect2(),
  3031. 'rear_port': StaticSelect2(),
  3032. }
  3033. def __init__(self, *args, **kwargs):
  3034. super().__init__(*args, **kwargs)
  3035. # Limit RearPort choices to the local device
  3036. if hasattr(self.instance, 'device'):
  3037. self.fields['rear_port'].queryset = self.fields['rear_port'].queryset.filter(
  3038. device=self.instance.device
  3039. )
  3040. # TODO: Merge with FrontPortTemplateCreateForm to remove duplicate logic
  3041. class FrontPortCreateForm(ComponentCreateForm):
  3042. model = FrontPort
  3043. type = forms.ChoiceField(
  3044. choices=PortTypeChoices,
  3045. widget=StaticSelect2(),
  3046. )
  3047. color = ColorField(
  3048. required=False
  3049. )
  3050. rear_port_set = forms.MultipleChoiceField(
  3051. choices=[],
  3052. label='Rear ports',
  3053. help_text='Select one rear port assignment for each front port being created.',
  3054. )
  3055. field_order = (
  3056. 'device', 'name_pattern', 'label_pattern', 'type', 'color', 'rear_port_set', 'mark_connected', 'description',
  3057. 'tags',
  3058. )
  3059. def __init__(self, *args, **kwargs):
  3060. super().__init__(*args, **kwargs)
  3061. device = Device.objects.get(
  3062. pk=self.initial.get('device') or self.data.get('device')
  3063. )
  3064. # Determine which rear port positions are occupied. These will be excluded from the list of available
  3065. # mappings.
  3066. occupied_port_positions = [
  3067. (front_port.rear_port_id, front_port.rear_port_position)
  3068. for front_port in device.frontports.all()
  3069. ]
  3070. # Populate rear port choices
  3071. choices = []
  3072. rear_ports = RearPort.objects.filter(device=device)
  3073. for rear_port in rear_ports:
  3074. for i in range(1, rear_port.positions + 1):
  3075. if (rear_port.pk, i) not in occupied_port_positions:
  3076. choices.append(
  3077. ('{}:{}'.format(rear_port.pk, i), '{}:{}'.format(rear_port.name, i))
  3078. )
  3079. self.fields['rear_port_set'].choices = choices
  3080. def clean(self):
  3081. super().clean()
  3082. # Validate that the number of ports being created equals the number of selected (rear port, position) tuples
  3083. front_port_count = len(self.cleaned_data['name_pattern'])
  3084. rear_port_count = len(self.cleaned_data['rear_port_set'])
  3085. if front_port_count != rear_port_count:
  3086. raise forms.ValidationError({
  3087. 'rear_port_set': 'The provided name pattern will create {} ports, however {} rear port assignments '
  3088. 'were selected. These counts must match.'.format(front_port_count, rear_port_count)
  3089. })
  3090. def get_iterative_data(self, iteration):
  3091. # Assign rear port and position from selected set
  3092. rear_port, position = self.cleaned_data['rear_port_set'][iteration].split(':')
  3093. return {
  3094. 'rear_port': int(rear_port),
  3095. 'rear_port_position': int(position),
  3096. }
  3097. # class FrontPortBulkCreateForm(
  3098. # form_from_model(FrontPort, ['label', 'type', 'description', 'tags']),
  3099. # DeviceBulkAddComponentForm
  3100. # ):
  3101. # pass
  3102. class FrontPortBulkEditForm(
  3103. form_from_model(FrontPort, ['label', 'type', 'color', 'mark_connected', 'description']),
  3104. BootstrapMixin,
  3105. AddRemoveTagsForm,
  3106. CustomFieldModelBulkEditForm
  3107. ):
  3108. pk = forms.ModelMultipleChoiceField(
  3109. queryset=FrontPort.objects.all(),
  3110. widget=forms.MultipleHiddenInput()
  3111. )
  3112. class Meta:
  3113. nullable_fields = ['label', 'description']
  3114. class FrontPortCSVForm(CustomFieldModelCSVForm):
  3115. device = CSVModelChoiceField(
  3116. queryset=Device.objects.all(),
  3117. to_field_name='name'
  3118. )
  3119. rear_port = CSVModelChoiceField(
  3120. queryset=RearPort.objects.all(),
  3121. to_field_name='name',
  3122. help_text='Corresponding rear port'
  3123. )
  3124. type = CSVChoiceField(
  3125. choices=PortTypeChoices,
  3126. help_text='Physical medium classification'
  3127. )
  3128. class Meta:
  3129. model = FrontPort
  3130. fields = (
  3131. 'device', 'name', 'label', 'type', 'color', 'mark_connected', 'rear_port', 'rear_port_position',
  3132. 'description',
  3133. )
  3134. help_texts = {
  3135. 'rear_port_position': 'Mapped position on corresponding rear port',
  3136. }
  3137. def __init__(self, *args, **kwargs):
  3138. super().__init__(*args, **kwargs)
  3139. # Limit RearPort choices to those belonging to this device (or VC master)
  3140. if self.is_bound:
  3141. try:
  3142. device = self.fields['device'].to_python(self.data['device'])
  3143. except forms.ValidationError:
  3144. device = None
  3145. else:
  3146. try:
  3147. device = self.instance.device
  3148. except Device.DoesNotExist:
  3149. device = None
  3150. if device:
  3151. self.fields['rear_port'].queryset = RearPort.objects.filter(
  3152. device__in=[device, device.get_vc_master()]
  3153. )
  3154. else:
  3155. self.fields['rear_port'].queryset = RearPort.objects.none()
  3156. #
  3157. # Rear pass-through ports
  3158. #
  3159. class RearPortFilterForm(DeviceComponentFilterForm):
  3160. model = RearPort
  3161. field_groups = [
  3162. ['name', 'label', 'type', 'color'],
  3163. ['region_id', 'site_group_id', 'site_id'],
  3164. ['tag']
  3165. ]
  3166. type = forms.MultipleChoiceField(
  3167. choices=PortTypeChoices,
  3168. required=False,
  3169. widget=StaticSelect2Multiple()
  3170. )
  3171. color = ColorField(
  3172. required=False
  3173. )
  3174. tag = TagFilterField(model)
  3175. class RearPortForm(BootstrapMixin, CustomFieldModelForm):
  3176. tags = DynamicModelMultipleChoiceField(
  3177. queryset=Tag.objects.all(),
  3178. required=False
  3179. )
  3180. class Meta:
  3181. model = RearPort
  3182. fields = [
  3183. 'device', 'name', 'label', 'type', 'color', 'positions', 'mark_connected', 'description', 'tags',
  3184. ]
  3185. widgets = {
  3186. 'device': forms.HiddenInput(),
  3187. 'type': StaticSelect2(),
  3188. }
  3189. class RearPortCreateForm(ComponentCreateForm):
  3190. model = RearPort
  3191. type = forms.ChoiceField(
  3192. choices=PortTypeChoices,
  3193. widget=StaticSelect2(),
  3194. )
  3195. color = ColorField(
  3196. required=False
  3197. )
  3198. positions = forms.IntegerField(
  3199. min_value=REARPORT_POSITIONS_MIN,
  3200. max_value=REARPORT_POSITIONS_MAX,
  3201. initial=1,
  3202. help_text='The number of front ports which may be mapped to each rear port'
  3203. )
  3204. field_order = (
  3205. 'device', 'name_pattern', 'label_pattern', 'type', 'color', 'positions', 'mark_connected', 'description',
  3206. 'tags',
  3207. )
  3208. class RearPortBulkCreateForm(
  3209. form_from_model(RearPort, ['type', 'color', 'positions', 'mark_connected']),
  3210. DeviceBulkAddComponentForm
  3211. ):
  3212. model = RearPort
  3213. field_order = ('name_pattern', 'label_pattern', 'type', 'positions', 'mark_connected', 'description', 'tags')
  3214. class RearPortBulkEditForm(
  3215. form_from_model(RearPort, ['label', 'type', 'color', 'mark_connected', 'description']),
  3216. BootstrapMixin,
  3217. AddRemoveTagsForm,
  3218. CustomFieldModelBulkEditForm
  3219. ):
  3220. pk = forms.ModelMultipleChoiceField(
  3221. queryset=RearPort.objects.all(),
  3222. widget=forms.MultipleHiddenInput()
  3223. )
  3224. class Meta:
  3225. nullable_fields = ['label', 'description']
  3226. class RearPortCSVForm(CustomFieldModelCSVForm):
  3227. device = CSVModelChoiceField(
  3228. queryset=Device.objects.all(),
  3229. to_field_name='name'
  3230. )
  3231. type = CSVChoiceField(
  3232. help_text='Physical medium classification',
  3233. choices=PortTypeChoices,
  3234. )
  3235. class Meta:
  3236. model = RearPort
  3237. fields = ('device', 'name', 'label', 'type', 'color', 'mark_connected', 'positions', 'description')
  3238. help_texts = {
  3239. 'positions': 'Number of front ports which may be mapped'
  3240. }
  3241. #
  3242. # Device bays
  3243. #
  3244. class DeviceBayFilterForm(DeviceComponentFilterForm):
  3245. model = DeviceBay
  3246. field_groups = [
  3247. ['name', 'label'],
  3248. ['region_id', 'site_group_id', 'site_id'],
  3249. ['tag']
  3250. ]
  3251. tag = TagFilterField(model)
  3252. class DeviceBayForm(BootstrapMixin, CustomFieldModelForm):
  3253. tags = DynamicModelMultipleChoiceField(
  3254. queryset=Tag.objects.all(),
  3255. required=False
  3256. )
  3257. class Meta:
  3258. model = DeviceBay
  3259. fields = [
  3260. 'device', 'name', 'label', 'description', 'tags',
  3261. ]
  3262. widgets = {
  3263. 'device': forms.HiddenInput(),
  3264. }
  3265. class DeviceBayCreateForm(ComponentCreateForm):
  3266. model = DeviceBay
  3267. field_order = ('device', 'name_pattern', 'label_pattern', 'description', 'tags')
  3268. class PopulateDeviceBayForm(BootstrapMixin, forms.Form):
  3269. installed_device = forms.ModelChoiceField(
  3270. queryset=Device.objects.all(),
  3271. label='Child Device',
  3272. help_text="Child devices must first be created and assigned to the site/rack of the parent device.",
  3273. widget=StaticSelect2(),
  3274. )
  3275. def __init__(self, device_bay, *args, **kwargs):
  3276. super().__init__(*args, **kwargs)
  3277. self.fields['installed_device'].queryset = Device.objects.filter(
  3278. site=device_bay.device.site,
  3279. rack=device_bay.device.rack,
  3280. parent_bay__isnull=True,
  3281. device_type__u_height=0,
  3282. device_type__subdevice_role=SubdeviceRoleChoices.ROLE_CHILD
  3283. ).exclude(pk=device_bay.device.pk)
  3284. class DeviceBayBulkCreateForm(DeviceBulkAddComponentForm):
  3285. model = DeviceBay
  3286. field_order = ('name_pattern', 'label_pattern', 'description', 'tags')
  3287. class DeviceBayBulkEditForm(
  3288. form_from_model(DeviceBay, ['label', 'description']),
  3289. BootstrapMixin,
  3290. AddRemoveTagsForm,
  3291. CustomFieldModelBulkEditForm
  3292. ):
  3293. pk = forms.ModelMultipleChoiceField(
  3294. queryset=DeviceBay.objects.all(),
  3295. widget=forms.MultipleHiddenInput()
  3296. )
  3297. class Meta:
  3298. nullable_fields = ['label', 'description']
  3299. class DeviceBayCSVForm(CustomFieldModelCSVForm):
  3300. device = CSVModelChoiceField(
  3301. queryset=Device.objects.all(),
  3302. to_field_name='name'
  3303. )
  3304. installed_device = CSVModelChoiceField(
  3305. queryset=Device.objects.all(),
  3306. required=False,
  3307. to_field_name='name',
  3308. help_text='Child device installed within this bay',
  3309. error_messages={
  3310. 'invalid_choice': 'Child device not found.',
  3311. }
  3312. )
  3313. class Meta:
  3314. model = DeviceBay
  3315. fields = ('device', 'name', 'label', 'installed_device', 'description')
  3316. def __init__(self, *args, **kwargs):
  3317. super().__init__(*args, **kwargs)
  3318. # Limit installed device choices to devices of the correct type and location
  3319. if self.is_bound:
  3320. try:
  3321. device = self.fields['device'].to_python(self.data['device'])
  3322. except forms.ValidationError:
  3323. device = None
  3324. else:
  3325. try:
  3326. device = self.instance.device
  3327. except Device.DoesNotExist:
  3328. device = None
  3329. if device:
  3330. self.fields['installed_device'].queryset = Device.objects.filter(
  3331. site=device.site,
  3332. rack=device.rack,
  3333. parent_bay__isnull=True,
  3334. device_type__u_height=0,
  3335. device_type__subdevice_role=SubdeviceRoleChoices.ROLE_CHILD
  3336. ).exclude(pk=device.pk)
  3337. else:
  3338. self.fields['installed_device'].queryset = Interface.objects.none()
  3339. #
  3340. # Inventory items
  3341. #
  3342. class InventoryItemForm(BootstrapMixin, CustomFieldModelForm):
  3343. device = DynamicModelChoiceField(
  3344. queryset=Device.objects.all()
  3345. )
  3346. parent = DynamicModelChoiceField(
  3347. queryset=InventoryItem.objects.all(),
  3348. required=False,
  3349. query_params={
  3350. 'device_id': '$device'
  3351. }
  3352. )
  3353. manufacturer = DynamicModelChoiceField(
  3354. queryset=Manufacturer.objects.all(),
  3355. required=False
  3356. )
  3357. tags = DynamicModelMultipleChoiceField(
  3358. queryset=Tag.objects.all(),
  3359. required=False
  3360. )
  3361. class Meta:
  3362. model = InventoryItem
  3363. fields = [
  3364. 'device', 'parent', 'name', 'label', 'manufacturer', 'part_id', 'serial', 'asset_tag', 'description',
  3365. 'tags',
  3366. ]
  3367. class InventoryItemCreateForm(ComponentCreateForm):
  3368. model = InventoryItem
  3369. manufacturer = DynamicModelChoiceField(
  3370. queryset=Manufacturer.objects.all(),
  3371. required=False
  3372. )
  3373. parent = DynamicModelChoiceField(
  3374. queryset=InventoryItem.objects.all(),
  3375. required=False,
  3376. query_params={
  3377. 'device_id': '$device'
  3378. }
  3379. )
  3380. part_id = forms.CharField(
  3381. max_length=50,
  3382. required=False,
  3383. label='Part ID'
  3384. )
  3385. serial = forms.CharField(
  3386. max_length=50,
  3387. required=False,
  3388. )
  3389. asset_tag = forms.CharField(
  3390. max_length=50,
  3391. required=False,
  3392. )
  3393. field_order = (
  3394. 'device', 'parent', 'name_pattern', 'label_pattern', 'manufacturer', 'part_id', 'serial', 'asset_tag',
  3395. 'description', 'tags',
  3396. )
  3397. class InventoryItemCSVForm(CustomFieldModelCSVForm):
  3398. device = CSVModelChoiceField(
  3399. queryset=Device.objects.all(),
  3400. to_field_name='name'
  3401. )
  3402. manufacturer = CSVModelChoiceField(
  3403. queryset=Manufacturer.objects.all(),
  3404. to_field_name='name',
  3405. required=False
  3406. )
  3407. class Meta:
  3408. model = InventoryItem
  3409. fields = (
  3410. 'device', 'name', 'label', 'manufacturer', 'part_id', 'serial', 'asset_tag', 'discovered', 'description',
  3411. )
  3412. class InventoryItemBulkCreateForm(
  3413. form_from_model(InventoryItem, ['manufacturer', 'part_id', 'serial', 'asset_tag', 'discovered']),
  3414. DeviceBulkAddComponentForm
  3415. ):
  3416. model = InventoryItem
  3417. field_order = (
  3418. 'name_pattern', 'label_pattern', 'manufacturer', 'part_id', 'serial', 'asset_tag', 'discovered', 'description',
  3419. 'tags',
  3420. )
  3421. class InventoryItemBulkEditForm(
  3422. form_from_model(InventoryItem, ['label', 'manufacturer', 'part_id', 'description']),
  3423. BootstrapMixin,
  3424. AddRemoveTagsForm,
  3425. CustomFieldModelBulkEditForm
  3426. ):
  3427. pk = forms.ModelMultipleChoiceField(
  3428. queryset=InventoryItem.objects.all(),
  3429. widget=forms.MultipleHiddenInput()
  3430. )
  3431. manufacturer = DynamicModelChoiceField(
  3432. queryset=Manufacturer.objects.all(),
  3433. required=False
  3434. )
  3435. class Meta:
  3436. nullable_fields = ['label', 'manufacturer', 'part_id', 'description']
  3437. class InventoryItemFilterForm(DeviceComponentFilterForm):
  3438. model = InventoryItem
  3439. field_groups = [
  3440. ['name', 'label', 'manufacturer_id'],
  3441. ['serial', 'asset_tag', 'discovered'],
  3442. ['region_id', 'site_group_id', 'site_id'],
  3443. ['tag']
  3444. ]
  3445. manufacturer_id = DynamicModelMultipleChoiceField(
  3446. queryset=Manufacturer.objects.all(),
  3447. required=False,
  3448. label=_('Manufacturer')
  3449. )
  3450. serial = forms.CharField(
  3451. required=False
  3452. )
  3453. asset_tag = forms.CharField(
  3454. required=False
  3455. )
  3456. discovered = forms.NullBooleanField(
  3457. required=False,
  3458. widget=StaticSelect2(
  3459. choices=BOOLEAN_WITH_BLANK_CHOICES
  3460. )
  3461. )
  3462. tag = TagFilterField(model)
  3463. #
  3464. # Cables
  3465. #
  3466. class ConnectCableToDeviceForm(BootstrapMixin, CustomFieldModelForm):
  3467. """
  3468. Base form for connecting a Cable to a Device component
  3469. """
  3470. termination_b_region = DynamicModelChoiceField(
  3471. queryset=Region.objects.all(),
  3472. label='Region',
  3473. required=False
  3474. )
  3475. termination_b_site_group = DynamicModelChoiceField(
  3476. queryset=SiteGroup.objects.all(),
  3477. label='Site group',
  3478. required=False
  3479. )
  3480. termination_b_site = DynamicModelChoiceField(
  3481. queryset=Site.objects.all(),
  3482. label='Site',
  3483. required=False,
  3484. query_params={
  3485. 'region_id': '$termination_b_region',
  3486. 'group_id': '$termination_b_site_group',
  3487. }
  3488. )
  3489. termination_b_location = DynamicModelChoiceField(
  3490. queryset=Location.objects.all(),
  3491. label='Location',
  3492. required=False,
  3493. null_option='None',
  3494. query_params={
  3495. 'site_id': '$termination_b_site'
  3496. }
  3497. )
  3498. termination_b_rack = DynamicModelChoiceField(
  3499. queryset=Rack.objects.all(),
  3500. label='Rack',
  3501. required=False,
  3502. null_option='None',
  3503. query_params={
  3504. 'site_id': '$termination_b_site',
  3505. 'location_id': '$termination_b_location',
  3506. }
  3507. )
  3508. termination_b_device = DynamicModelChoiceField(
  3509. queryset=Device.objects.all(),
  3510. label='Device',
  3511. required=False,
  3512. query_params={
  3513. 'site_id': '$termination_b_site',
  3514. 'location_id': '$termination_b_location',
  3515. 'rack_id': '$termination_b_rack',
  3516. }
  3517. )
  3518. tags = DynamicModelMultipleChoiceField(
  3519. queryset=Tag.objects.all(),
  3520. required=False
  3521. )
  3522. class Meta:
  3523. model = Cable
  3524. fields = [
  3525. 'termination_b_region', 'termination_b_site', 'termination_b_rack', 'termination_b_device',
  3526. 'termination_b_id', 'type', 'status', 'label', 'color', 'length', 'length_unit', 'tags',
  3527. ]
  3528. widgets = {
  3529. 'status': StaticSelect2,
  3530. 'type': StaticSelect2,
  3531. 'length_unit': StaticSelect2,
  3532. }
  3533. def clean_termination_b_id(self):
  3534. # Return the PK rather than the object
  3535. return getattr(self.cleaned_data['termination_b_id'], 'pk', None)
  3536. class ConnectCableToConsolePortForm(ConnectCableToDeviceForm):
  3537. termination_b_id = DynamicModelChoiceField(
  3538. queryset=ConsolePort.objects.all(),
  3539. label='Name',
  3540. disabled_indicator='_occupied',
  3541. query_params={
  3542. 'device_id': '$termination_b_device'
  3543. }
  3544. )
  3545. class ConnectCableToConsoleServerPortForm(ConnectCableToDeviceForm):
  3546. termination_b_id = DynamicModelChoiceField(
  3547. queryset=ConsoleServerPort.objects.all(),
  3548. label='Name',
  3549. disabled_indicator='_occupied',
  3550. query_params={
  3551. 'device_id': '$termination_b_device'
  3552. }
  3553. )
  3554. class ConnectCableToPowerPortForm(ConnectCableToDeviceForm):
  3555. termination_b_id = DynamicModelChoiceField(
  3556. queryset=PowerPort.objects.all(),
  3557. label='Name',
  3558. disabled_indicator='_occupied',
  3559. query_params={
  3560. 'device_id': '$termination_b_device'
  3561. }
  3562. )
  3563. class ConnectCableToPowerOutletForm(ConnectCableToDeviceForm):
  3564. termination_b_id = DynamicModelChoiceField(
  3565. queryset=PowerOutlet.objects.all(),
  3566. label='Name',
  3567. disabled_indicator='_occupied',
  3568. query_params={
  3569. 'device_id': '$termination_b_device'
  3570. }
  3571. )
  3572. class ConnectCableToInterfaceForm(ConnectCableToDeviceForm):
  3573. termination_b_id = DynamicModelChoiceField(
  3574. queryset=Interface.objects.all(),
  3575. label='Name',
  3576. disabled_indicator='_occupied',
  3577. query_params={
  3578. 'device_id': '$termination_b_device',
  3579. 'kind': 'physical',
  3580. }
  3581. )
  3582. class ConnectCableToFrontPortForm(ConnectCableToDeviceForm):
  3583. termination_b_id = DynamicModelChoiceField(
  3584. queryset=FrontPort.objects.all(),
  3585. label='Name',
  3586. disabled_indicator='_occupied',
  3587. query_params={
  3588. 'device_id': '$termination_b_device'
  3589. }
  3590. )
  3591. class ConnectCableToRearPortForm(ConnectCableToDeviceForm):
  3592. termination_b_id = DynamicModelChoiceField(
  3593. queryset=RearPort.objects.all(),
  3594. label='Name',
  3595. disabled_indicator='_occupied',
  3596. query_params={
  3597. 'device_id': '$termination_b_device'
  3598. }
  3599. )
  3600. class ConnectCableToCircuitTerminationForm(BootstrapMixin, CustomFieldModelForm):
  3601. termination_b_provider = DynamicModelChoiceField(
  3602. queryset=Provider.objects.all(),
  3603. label='Provider',
  3604. required=False
  3605. )
  3606. termination_b_region = DynamicModelChoiceField(
  3607. queryset=Region.objects.all(),
  3608. label='Region',
  3609. required=False
  3610. )
  3611. termination_b_site_group = DynamicModelChoiceField(
  3612. queryset=SiteGroup.objects.all(),
  3613. label='Site group',
  3614. required=False
  3615. )
  3616. termination_b_site = DynamicModelChoiceField(
  3617. queryset=Site.objects.all(),
  3618. label='Site',
  3619. required=False,
  3620. query_params={
  3621. 'region_id': '$termination_b_region',
  3622. 'group_id': '$termination_b_site_group',
  3623. }
  3624. )
  3625. termination_b_circuit = DynamicModelChoiceField(
  3626. queryset=Circuit.objects.all(),
  3627. label='Circuit',
  3628. query_params={
  3629. 'provider_id': '$termination_b_provider',
  3630. 'site_id': '$termination_b_site',
  3631. }
  3632. )
  3633. termination_b_id = DynamicModelChoiceField(
  3634. queryset=CircuitTermination.objects.all(),
  3635. label='Side',
  3636. disabled_indicator='_occupied',
  3637. query_params={
  3638. 'circuit_id': '$termination_b_circuit'
  3639. }
  3640. )
  3641. tags = DynamicModelMultipleChoiceField(
  3642. queryset=Tag.objects.all(),
  3643. required=False
  3644. )
  3645. class Meta:
  3646. model = Cable
  3647. fields = [
  3648. 'termination_b_provider', 'termination_b_region', 'termination_b_site', 'termination_b_circuit',
  3649. 'termination_b_id', 'type', 'status', 'label', 'color', 'length', 'length_unit', 'tags',
  3650. ]
  3651. def clean_termination_b_id(self):
  3652. # Return the PK rather than the object
  3653. return getattr(self.cleaned_data['termination_b_id'], 'pk', None)
  3654. class ConnectCableToPowerFeedForm(BootstrapMixin, CustomFieldModelForm):
  3655. termination_b_region = DynamicModelChoiceField(
  3656. queryset=Region.objects.all(),
  3657. label='Region',
  3658. required=False
  3659. )
  3660. termination_b_site_group = DynamicModelChoiceField(
  3661. queryset=SiteGroup.objects.all(),
  3662. label='Site group',
  3663. required=False
  3664. )
  3665. termination_b_site = DynamicModelChoiceField(
  3666. queryset=Site.objects.all(),
  3667. label='Site',
  3668. required=False,
  3669. query_params={
  3670. 'region_id': '$termination_b_region',
  3671. 'group_id': '$termination_b_site_group',
  3672. }
  3673. )
  3674. termination_b_location = DynamicModelChoiceField(
  3675. queryset=Location.objects.all(),
  3676. label='Location',
  3677. required=False,
  3678. query_params={
  3679. 'site_id': '$termination_b_site'
  3680. }
  3681. )
  3682. termination_b_powerpanel = DynamicModelChoiceField(
  3683. queryset=PowerPanel.objects.all(),
  3684. label='Power Panel',
  3685. required=False,
  3686. query_params={
  3687. 'site_id': '$termination_b_site',
  3688. 'location_id': '$termination_b_location',
  3689. }
  3690. )
  3691. termination_b_id = DynamicModelChoiceField(
  3692. queryset=PowerFeed.objects.all(),
  3693. label='Name',
  3694. disabled_indicator='_occupied',
  3695. query_params={
  3696. 'power_panel_id': '$termination_b_powerpanel'
  3697. }
  3698. )
  3699. tags = DynamicModelMultipleChoiceField(
  3700. queryset=Tag.objects.all(),
  3701. required=False
  3702. )
  3703. class Meta:
  3704. model = Cable
  3705. fields = [
  3706. 'termination_b_location', 'termination_b_powerpanel', 'termination_b_id', 'type', 'status', 'label',
  3707. 'color', 'length', 'length_unit', 'tags',
  3708. ]
  3709. def clean_termination_b_id(self):
  3710. # Return the PK rather than the object
  3711. return getattr(self.cleaned_data['termination_b_id'], 'pk', None)
  3712. class CableForm(BootstrapMixin, CustomFieldModelForm):
  3713. tags = DynamicModelMultipleChoiceField(
  3714. queryset=Tag.objects.all(),
  3715. required=False
  3716. )
  3717. class Meta:
  3718. model = Cable
  3719. fields = [
  3720. 'type', 'status', 'label', 'color', 'length', 'length_unit', 'tags',
  3721. ]
  3722. widgets = {
  3723. 'status': StaticSelect2,
  3724. 'type': StaticSelect2,
  3725. 'length_unit': StaticSelect2,
  3726. }
  3727. error_messages = {
  3728. 'length': {
  3729. 'max_value': 'Maximum length is 32767 (any unit)'
  3730. }
  3731. }
  3732. class CableCSVForm(CustomFieldModelCSVForm):
  3733. # Termination A
  3734. side_a_device = CSVModelChoiceField(
  3735. queryset=Device.objects.all(),
  3736. to_field_name='name',
  3737. help_text='Side A device'
  3738. )
  3739. side_a_type = CSVContentTypeField(
  3740. queryset=ContentType.objects.all(),
  3741. limit_choices_to=CABLE_TERMINATION_MODELS,
  3742. help_text='Side A type'
  3743. )
  3744. side_a_name = forms.CharField(
  3745. help_text='Side A component name'
  3746. )
  3747. # Termination B
  3748. side_b_device = CSVModelChoiceField(
  3749. queryset=Device.objects.all(),
  3750. to_field_name='name',
  3751. help_text='Side B device'
  3752. )
  3753. side_b_type = CSVContentTypeField(
  3754. queryset=ContentType.objects.all(),
  3755. limit_choices_to=CABLE_TERMINATION_MODELS,
  3756. help_text='Side B type'
  3757. )
  3758. side_b_name = forms.CharField(
  3759. help_text='Side B component name'
  3760. )
  3761. # Cable attributes
  3762. status = CSVChoiceField(
  3763. choices=CableStatusChoices,
  3764. required=False,
  3765. help_text='Connection status'
  3766. )
  3767. type = CSVChoiceField(
  3768. choices=CableTypeChoices,
  3769. required=False,
  3770. help_text='Physical medium classification'
  3771. )
  3772. length_unit = CSVChoiceField(
  3773. choices=CableLengthUnitChoices,
  3774. required=False,
  3775. help_text='Length unit'
  3776. )
  3777. class Meta:
  3778. model = Cable
  3779. fields = [
  3780. 'side_a_device', 'side_a_type', 'side_a_name', 'side_b_device', 'side_b_type', 'side_b_name', 'type',
  3781. 'status', 'label', 'color', 'length', 'length_unit',
  3782. ]
  3783. help_texts = {
  3784. 'color': mark_safe('RGB color in hexadecimal (e.g. <code>00ff00</code>)'),
  3785. }
  3786. def _clean_side(self, side):
  3787. """
  3788. Derive a Cable's A/B termination objects.
  3789. :param side: 'a' or 'b'
  3790. """
  3791. assert side in 'ab', f"Invalid side designation: {side}"
  3792. device = self.cleaned_data.get(f'side_{side}_device')
  3793. content_type = self.cleaned_data.get(f'side_{side}_type')
  3794. name = self.cleaned_data.get(f'side_{side}_name')
  3795. if not device or not content_type or not name:
  3796. return None
  3797. model = content_type.model_class()
  3798. try:
  3799. termination_object = model.objects.get(device=device, name=name)
  3800. if termination_object.cable is not None:
  3801. raise forms.ValidationError(f"Side {side.upper()}: {device} {termination_object} is already connected")
  3802. except ObjectDoesNotExist:
  3803. raise forms.ValidationError(f"{side.upper()} side termination not found: {device} {name}")
  3804. setattr(self.instance, f'termination_{side}', termination_object)
  3805. return termination_object
  3806. def clean_side_a_name(self):
  3807. return self._clean_side('a')
  3808. def clean_side_b_name(self):
  3809. return self._clean_side('b')
  3810. def clean_length_unit(self):
  3811. # Avoid trying to save as NULL
  3812. length_unit = self.cleaned_data.get('length_unit', None)
  3813. return length_unit if length_unit is not None else ''
  3814. class CableBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldModelBulkEditForm):
  3815. pk = forms.ModelMultipleChoiceField(
  3816. queryset=Cable.objects.all(),
  3817. widget=forms.MultipleHiddenInput
  3818. )
  3819. type = forms.ChoiceField(
  3820. choices=add_blank_choice(CableTypeChoices),
  3821. required=False,
  3822. initial='',
  3823. widget=StaticSelect2()
  3824. )
  3825. status = forms.ChoiceField(
  3826. choices=add_blank_choice(CableStatusChoices),
  3827. required=False,
  3828. widget=StaticSelect2(),
  3829. initial=''
  3830. )
  3831. label = forms.CharField(
  3832. max_length=100,
  3833. required=False
  3834. )
  3835. color = ColorField(
  3836. required=False
  3837. )
  3838. length = forms.IntegerField(
  3839. min_value=1,
  3840. required=False
  3841. )
  3842. length_unit = forms.ChoiceField(
  3843. choices=add_blank_choice(CableLengthUnitChoices),
  3844. required=False,
  3845. initial='',
  3846. widget=StaticSelect2()
  3847. )
  3848. class Meta:
  3849. nullable_fields = [
  3850. 'type', 'status', 'label', 'color', 'length',
  3851. ]
  3852. def clean(self):
  3853. super().clean()
  3854. # Validate length/unit
  3855. length = self.cleaned_data.get('length')
  3856. length_unit = self.cleaned_data.get('length_unit')
  3857. if length and not length_unit:
  3858. raise forms.ValidationError({
  3859. 'length_unit': "Must specify a unit when setting length"
  3860. })
  3861. class CableFilterForm(BootstrapMixin, CustomFieldModelFilterForm):
  3862. model = Cable
  3863. field_groups = [
  3864. ['type', 'status', 'color'],
  3865. ['device_id', 'rack_id'],
  3866. ['region_id', 'site_id', 'tenant_id'],
  3867. ['tag']
  3868. ]
  3869. region_id = DynamicModelMultipleChoiceField(
  3870. queryset=Region.objects.all(),
  3871. required=False,
  3872. label=_('Region')
  3873. )
  3874. site_id = DynamicModelMultipleChoiceField(
  3875. queryset=Site.objects.all(),
  3876. required=False,
  3877. query_params={
  3878. 'region_id': '$region_id'
  3879. },
  3880. label=_('Site')
  3881. )
  3882. tenant_id = DynamicModelMultipleChoiceField(
  3883. queryset=Tenant.objects.all(),
  3884. required=False,
  3885. label=_('Tenant')
  3886. )
  3887. rack_id = DynamicModelMultipleChoiceField(
  3888. queryset=Rack.objects.all(),
  3889. required=False,
  3890. label=_('Rack'),
  3891. null_option='None',
  3892. query_params={
  3893. 'site_id': '$site_id'
  3894. }
  3895. )
  3896. type = forms.MultipleChoiceField(
  3897. choices=add_blank_choice(CableTypeChoices),
  3898. required=False,
  3899. widget=StaticSelect2()
  3900. )
  3901. status = forms.ChoiceField(
  3902. required=False,
  3903. choices=add_blank_choice(CableStatusChoices),
  3904. widget=StaticSelect2()
  3905. )
  3906. color = ColorField(
  3907. required=False
  3908. )
  3909. device_id = DynamicModelMultipleChoiceField(
  3910. queryset=Device.objects.all(),
  3911. required=False,
  3912. query_params={
  3913. 'site_id': '$site_id',
  3914. 'tenant_id': '$tenant_id',
  3915. 'rack_id': '$rack_id',
  3916. },
  3917. label=_('Device')
  3918. )
  3919. tag = TagFilterField(model)
  3920. #
  3921. # Connections
  3922. #
  3923. class ConsoleConnectionFilterForm(BootstrapMixin, forms.Form):
  3924. region_id = DynamicModelMultipleChoiceField(
  3925. queryset=Region.objects.all(),
  3926. required=False,
  3927. label=_('Region')
  3928. )
  3929. site_id = DynamicModelMultipleChoiceField(
  3930. queryset=Site.objects.all(),
  3931. required=False,
  3932. query_params={
  3933. 'region_id': '$region_id'
  3934. },
  3935. label=_('Site')
  3936. )
  3937. device_id = DynamicModelMultipleChoiceField(
  3938. queryset=Device.objects.all(),
  3939. required=False,
  3940. query_params={
  3941. 'site_id': '$site_id'
  3942. },
  3943. label=_('Device')
  3944. )
  3945. class PowerConnectionFilterForm(BootstrapMixin, forms.Form):
  3946. region_id = DynamicModelMultipleChoiceField(
  3947. queryset=Region.objects.all(),
  3948. required=False,
  3949. label=_('Region')
  3950. )
  3951. site_id = DynamicModelMultipleChoiceField(
  3952. queryset=Site.objects.all(),
  3953. required=False,
  3954. query_params={
  3955. 'region_id': '$region_id'
  3956. },
  3957. label=_('Site')
  3958. )
  3959. device_id = DynamicModelMultipleChoiceField(
  3960. queryset=Device.objects.all(),
  3961. required=False,
  3962. query_params={
  3963. 'site_id': '$site_id'
  3964. },
  3965. label=_('Device')
  3966. )
  3967. class InterfaceConnectionFilterForm(BootstrapMixin, forms.Form):
  3968. region_id = DynamicModelMultipleChoiceField(
  3969. queryset=Region.objects.all(),
  3970. required=False,
  3971. label=_('Region')
  3972. )
  3973. site_id = DynamicModelMultipleChoiceField(
  3974. queryset=Site.objects.all(),
  3975. required=False,
  3976. query_params={
  3977. 'region_id': '$region_id'
  3978. },
  3979. label=_('Site')
  3980. )
  3981. device_id = DynamicModelMultipleChoiceField(
  3982. queryset=Device.objects.all(),
  3983. required=False,
  3984. query_params={
  3985. 'site_id': '$site_id'
  3986. },
  3987. label=_('Device')
  3988. )
  3989. #
  3990. # Virtual chassis
  3991. #
  3992. class DeviceSelectionForm(forms.Form):
  3993. pk = forms.ModelMultipleChoiceField(
  3994. queryset=Device.objects.all(),
  3995. widget=forms.MultipleHiddenInput()
  3996. )
  3997. class VirtualChassisCreateForm(BootstrapMixin, CustomFieldModelForm):
  3998. region = DynamicModelChoiceField(
  3999. queryset=Region.objects.all(),
  4000. required=False,
  4001. initial_params={
  4002. 'sites': '$site'
  4003. }
  4004. )
  4005. site_group = DynamicModelChoiceField(
  4006. queryset=SiteGroup.objects.all(),
  4007. required=False,
  4008. initial_params={
  4009. 'sites': '$site'
  4010. }
  4011. )
  4012. site = DynamicModelChoiceField(
  4013. queryset=Site.objects.all(),
  4014. required=False,
  4015. query_params={
  4016. 'region_id': '$region',
  4017. 'group_id': '$site_group',
  4018. }
  4019. )
  4020. rack = DynamicModelChoiceField(
  4021. queryset=Rack.objects.all(),
  4022. required=False,
  4023. null_option='None',
  4024. query_params={
  4025. 'site_id': '$site'
  4026. }
  4027. )
  4028. members = DynamicModelMultipleChoiceField(
  4029. queryset=Device.objects.all(),
  4030. required=False,
  4031. query_params={
  4032. 'site_id': '$site',
  4033. 'rack_id': '$rack',
  4034. }
  4035. )
  4036. initial_position = forms.IntegerField(
  4037. initial=1,
  4038. required=False,
  4039. help_text='Position of the first member device. Increases by one for each additional member.'
  4040. )
  4041. tags = DynamicModelMultipleChoiceField(
  4042. queryset=Tag.objects.all(),
  4043. required=False
  4044. )
  4045. class Meta:
  4046. model = VirtualChassis
  4047. fields = [
  4048. 'name', 'domain', 'region', 'site_group', 'site', 'rack', 'members', 'initial_position', 'tags',
  4049. ]
  4050. def save(self, *args, **kwargs):
  4051. instance = super().save(*args, **kwargs)
  4052. # Assign VC members
  4053. if instance.pk:
  4054. initial_position = self.cleaned_data.get('initial_position') or 1
  4055. for i, member in enumerate(self.cleaned_data['members'], start=initial_position):
  4056. member.virtual_chassis = instance
  4057. member.vc_position = i
  4058. member.save()
  4059. return instance
  4060. class VirtualChassisForm(BootstrapMixin, CustomFieldModelForm):
  4061. master = forms.ModelChoiceField(
  4062. queryset=Device.objects.all(),
  4063. required=False,
  4064. )
  4065. tags = DynamicModelMultipleChoiceField(
  4066. queryset=Tag.objects.all(),
  4067. required=False
  4068. )
  4069. class Meta:
  4070. model = VirtualChassis
  4071. fields = [
  4072. 'name', 'domain', 'master', 'tags',
  4073. ]
  4074. widgets = {
  4075. 'master': SelectWithPK(),
  4076. }
  4077. def __init__(self, *args, **kwargs):
  4078. super().__init__(*args, **kwargs)
  4079. self.fields['master'].queryset = Device.objects.filter(virtual_chassis=self.instance)
  4080. class BaseVCMemberFormSet(forms.BaseModelFormSet):
  4081. def clean(self):
  4082. super().clean()
  4083. # Check for duplicate VC position values
  4084. vc_position_list = []
  4085. for form in self.forms:
  4086. vc_position = form.cleaned_data.get('vc_position')
  4087. if vc_position:
  4088. if vc_position in vc_position_list:
  4089. error_msg = 'A virtual chassis member already exists in position {}.'.format(vc_position)
  4090. form.add_error('vc_position', error_msg)
  4091. vc_position_list.append(vc_position)
  4092. class DeviceVCMembershipForm(forms.ModelForm):
  4093. class Meta:
  4094. model = Device
  4095. fields = [
  4096. 'vc_position', 'vc_priority',
  4097. ]
  4098. labels = {
  4099. 'vc_position': 'Position',
  4100. 'vc_priority': 'Priority',
  4101. }
  4102. def __init__(self, validate_vc_position=False, *args, **kwargs):
  4103. super().__init__(*args, **kwargs)
  4104. # Require VC position (only required when the Device is a VirtualChassis member)
  4105. self.fields['vc_position'].required = True
  4106. # Add bootstrap classes to form elements.
  4107. self.fields['vc_position'].widget.attrs = {'class': 'form-control'}
  4108. self.fields['vc_priority'].widget.attrs = {'class': 'form-control'}
  4109. # Validation of vc_position is optional. This is only required when adding a new member to an existing
  4110. # VirtualChassis. Otherwise, vc_position validation is handled by BaseVCMemberFormSet.
  4111. self.validate_vc_position = validate_vc_position
  4112. def clean_vc_position(self):
  4113. vc_position = self.cleaned_data['vc_position']
  4114. if self.validate_vc_position:
  4115. conflicting_members = Device.objects.filter(
  4116. virtual_chassis=self.instance.virtual_chassis,
  4117. vc_position=vc_position
  4118. )
  4119. if conflicting_members.exists():
  4120. raise forms.ValidationError(
  4121. 'A virtual chassis member already exists in position {}.'.format(vc_position)
  4122. )
  4123. return vc_position
  4124. class VCMemberSelectForm(BootstrapMixin, forms.Form):
  4125. region = DynamicModelChoiceField(
  4126. queryset=Region.objects.all(),
  4127. required=False,
  4128. initial_params={
  4129. 'sites': '$site'
  4130. }
  4131. )
  4132. site_group = DynamicModelChoiceField(
  4133. queryset=SiteGroup.objects.all(),
  4134. required=False,
  4135. initial_params={
  4136. 'sites': '$site'
  4137. }
  4138. )
  4139. site = DynamicModelChoiceField(
  4140. queryset=Site.objects.all(),
  4141. required=False,
  4142. query_params={
  4143. 'region_id': '$region',
  4144. 'group_id': '$site_group',
  4145. }
  4146. )
  4147. rack = DynamicModelChoiceField(
  4148. queryset=Rack.objects.all(),
  4149. required=False,
  4150. null_option='None',
  4151. query_params={
  4152. 'site_id': '$site'
  4153. }
  4154. )
  4155. device = DynamicModelChoiceField(
  4156. queryset=Device.objects.all(),
  4157. query_params={
  4158. 'site_id': '$site',
  4159. 'rack_id': '$rack',
  4160. 'virtual_chassis_id': 'null',
  4161. }
  4162. )
  4163. def clean_device(self):
  4164. device = self.cleaned_data['device']
  4165. if device.virtual_chassis is not None:
  4166. raise forms.ValidationError(
  4167. f"Device {device} is already assigned to a virtual chassis."
  4168. )
  4169. return device
  4170. class VirtualChassisBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldModelBulkEditForm):
  4171. pk = forms.ModelMultipleChoiceField(
  4172. queryset=VirtualChassis.objects.all(),
  4173. widget=forms.MultipleHiddenInput()
  4174. )
  4175. domain = forms.CharField(
  4176. max_length=30,
  4177. required=False
  4178. )
  4179. class Meta:
  4180. nullable_fields = ['domain']
  4181. class VirtualChassisCSVForm(CustomFieldModelCSVForm):
  4182. master = CSVModelChoiceField(
  4183. queryset=Device.objects.all(),
  4184. to_field_name='name',
  4185. required=False,
  4186. help_text='Master device'
  4187. )
  4188. class Meta:
  4189. model = VirtualChassis
  4190. fields = ('name', 'domain', 'master')
  4191. class VirtualChassisFilterForm(BootstrapMixin, TenancyFilterForm, CustomFieldModelFilterForm):
  4192. model = VirtualChassis
  4193. field_order = ['region_id', 'site_group_id', 'site_id', 'tenant_group_id', 'tenant_id']
  4194. field_groups = [
  4195. ['region_id', 'site_group_id', 'site_id'],
  4196. ['tenant_group_id', 'tenant_id'],
  4197. ['tag']
  4198. ]
  4199. region_id = DynamicModelMultipleChoiceField(
  4200. queryset=Region.objects.all(),
  4201. required=False,
  4202. label=_('Region')
  4203. )
  4204. site_group_id = DynamicModelMultipleChoiceField(
  4205. queryset=SiteGroup.objects.all(),
  4206. required=False,
  4207. label=_('Site group')
  4208. )
  4209. site_id = DynamicModelMultipleChoiceField(
  4210. queryset=Site.objects.all(),
  4211. required=False,
  4212. query_params={
  4213. 'region_id': '$region_id'
  4214. },
  4215. label=_('Site')
  4216. )
  4217. tag = TagFilterField(model)
  4218. #
  4219. # Power panels
  4220. #
  4221. class PowerPanelForm(BootstrapMixin, CustomFieldModelForm):
  4222. region = DynamicModelChoiceField(
  4223. queryset=Region.objects.all(),
  4224. required=False,
  4225. initial_params={
  4226. 'sites': '$site'
  4227. }
  4228. )
  4229. site_group = DynamicModelChoiceField(
  4230. queryset=SiteGroup.objects.all(),
  4231. required=False,
  4232. initial_params={
  4233. 'sites': '$site'
  4234. }
  4235. )
  4236. site = DynamicModelChoiceField(
  4237. queryset=Site.objects.all(),
  4238. query_params={
  4239. 'region_id': '$region',
  4240. 'group_id': '$site_group',
  4241. }
  4242. )
  4243. location = DynamicModelChoiceField(
  4244. queryset=Location.objects.all(),
  4245. required=False,
  4246. query_params={
  4247. 'site_id': '$site'
  4248. }
  4249. )
  4250. tags = DynamicModelMultipleChoiceField(
  4251. queryset=Tag.objects.all(),
  4252. required=False
  4253. )
  4254. class Meta:
  4255. model = PowerPanel
  4256. fields = [
  4257. 'region', 'site_group', 'site', 'location', 'name', 'tags',
  4258. ]
  4259. fieldsets = (
  4260. ('Power Panel', ('region', 'site_group', 'site', 'location', 'name', 'tags')),
  4261. )
  4262. class PowerPanelCSVForm(CustomFieldModelCSVForm):
  4263. site = CSVModelChoiceField(
  4264. queryset=Site.objects.all(),
  4265. to_field_name='name',
  4266. help_text='Name of parent site'
  4267. )
  4268. location = CSVModelChoiceField(
  4269. queryset=Location.objects.all(),
  4270. required=False,
  4271. to_field_name='name'
  4272. )
  4273. class Meta:
  4274. model = PowerPanel
  4275. fields = ('site', 'location', 'name')
  4276. def __init__(self, data=None, *args, **kwargs):
  4277. super().__init__(data, *args, **kwargs)
  4278. if data:
  4279. # Limit group queryset by assigned site
  4280. params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
  4281. self.fields['location'].queryset = self.fields['location'].queryset.filter(**params)
  4282. class PowerPanelBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldModelBulkEditForm):
  4283. pk = forms.ModelMultipleChoiceField(
  4284. queryset=PowerPanel.objects.all(),
  4285. widget=forms.MultipleHiddenInput
  4286. )
  4287. region = DynamicModelChoiceField(
  4288. queryset=Region.objects.all(),
  4289. required=False,
  4290. initial_params={
  4291. 'sites': '$site'
  4292. }
  4293. )
  4294. site_group = DynamicModelChoiceField(
  4295. queryset=SiteGroup.objects.all(),
  4296. required=False,
  4297. initial_params={
  4298. 'sites': '$site'
  4299. }
  4300. )
  4301. site = DynamicModelChoiceField(
  4302. queryset=Site.objects.all(),
  4303. required=False,
  4304. query_params={
  4305. 'region_id': '$region',
  4306. 'group_id': '$site_group',
  4307. }
  4308. )
  4309. location = DynamicModelChoiceField(
  4310. queryset=Location.objects.all(),
  4311. required=False,
  4312. query_params={
  4313. 'site_id': '$site'
  4314. }
  4315. )
  4316. class Meta:
  4317. nullable_fields = ['location']
  4318. class PowerPanelFilterForm(BootstrapMixin, CustomFieldModelFilterForm):
  4319. model = PowerPanel
  4320. region_id = DynamicModelMultipleChoiceField(
  4321. queryset=Region.objects.all(),
  4322. required=False,
  4323. label=_('Region')
  4324. )
  4325. site_group_id = DynamicModelMultipleChoiceField(
  4326. queryset=SiteGroup.objects.all(),
  4327. required=False,
  4328. label=_('Site group')
  4329. )
  4330. site_id = DynamicModelMultipleChoiceField(
  4331. queryset=Site.objects.all(),
  4332. required=False,
  4333. query_params={
  4334. 'region_id': '$region_id'
  4335. },
  4336. label=_('Site')
  4337. )
  4338. location_id = DynamicModelMultipleChoiceField(
  4339. queryset=Location.objects.all(),
  4340. required=False,
  4341. null_option='None',
  4342. query_params={
  4343. 'site_id': '$site_id'
  4344. },
  4345. label=_('Location')
  4346. )
  4347. tag = TagFilterField(model)
  4348. #
  4349. # Power feeds
  4350. #
  4351. class PowerFeedForm(BootstrapMixin, CustomFieldModelForm):
  4352. region = DynamicModelChoiceField(
  4353. queryset=Region.objects.all(),
  4354. required=False,
  4355. initial_params={
  4356. 'sites__powerpanel': '$power_panel'
  4357. }
  4358. )
  4359. site_group = DynamicModelChoiceField(
  4360. queryset=SiteGroup.objects.all(),
  4361. required=False,
  4362. initial_params={
  4363. 'sites': '$site'
  4364. }
  4365. )
  4366. site = DynamicModelChoiceField(
  4367. queryset=Site.objects.all(),
  4368. required=False,
  4369. initial_params={
  4370. 'powerpanel': '$power_panel'
  4371. },
  4372. query_params={
  4373. 'region_id': '$region',
  4374. 'group_id': '$site_group',
  4375. }
  4376. )
  4377. power_panel = DynamicModelChoiceField(
  4378. queryset=PowerPanel.objects.all(),
  4379. query_params={
  4380. 'site_id': '$site'
  4381. }
  4382. )
  4383. rack = DynamicModelChoiceField(
  4384. queryset=Rack.objects.all(),
  4385. required=False,
  4386. query_params={
  4387. 'site_id': '$site'
  4388. }
  4389. )
  4390. comments = CommentField()
  4391. tags = DynamicModelMultipleChoiceField(
  4392. queryset=Tag.objects.all(),
  4393. required=False
  4394. )
  4395. class Meta:
  4396. model = PowerFeed
  4397. fields = [
  4398. 'region', 'site_group', 'site', 'power_panel', 'rack', 'name', 'status', 'type', 'mark_connected', 'supply',
  4399. 'phase', 'voltage', 'amperage', 'max_utilization', 'comments', 'tags',
  4400. ]
  4401. fieldsets = (
  4402. ('Power Panel', ('region', 'site', 'power_panel')),
  4403. ('Power Feed', ('rack', 'name', 'status', 'type', 'mark_connected', 'tags')),
  4404. ('Characteristics', ('supply', 'voltage', 'amperage', 'phase', 'max_utilization')),
  4405. )
  4406. widgets = {
  4407. 'status': StaticSelect2(),
  4408. 'type': StaticSelect2(),
  4409. 'supply': StaticSelect2(),
  4410. 'phase': StaticSelect2(),
  4411. }
  4412. class PowerFeedCSVForm(CustomFieldModelCSVForm):
  4413. site = CSVModelChoiceField(
  4414. queryset=Site.objects.all(),
  4415. to_field_name='name',
  4416. help_text='Assigned site'
  4417. )
  4418. power_panel = CSVModelChoiceField(
  4419. queryset=PowerPanel.objects.all(),
  4420. to_field_name='name',
  4421. help_text='Upstream power panel'
  4422. )
  4423. location = CSVModelChoiceField(
  4424. queryset=Location.objects.all(),
  4425. to_field_name='name',
  4426. required=False,
  4427. help_text="Rack's location (if any)"
  4428. )
  4429. rack = CSVModelChoiceField(
  4430. queryset=Rack.objects.all(),
  4431. to_field_name='name',
  4432. required=False,
  4433. help_text='Rack'
  4434. )
  4435. status = CSVChoiceField(
  4436. choices=PowerFeedStatusChoices,
  4437. required=False,
  4438. help_text='Operational status'
  4439. )
  4440. type = CSVChoiceField(
  4441. choices=PowerFeedTypeChoices,
  4442. required=False,
  4443. help_text='Primary or redundant'
  4444. )
  4445. supply = CSVChoiceField(
  4446. choices=PowerFeedSupplyChoices,
  4447. required=False,
  4448. help_text='Supply type (AC/DC)'
  4449. )
  4450. phase = CSVChoiceField(
  4451. choices=PowerFeedPhaseChoices,
  4452. required=False,
  4453. help_text='Single or three-phase'
  4454. )
  4455. class Meta:
  4456. model = PowerFeed
  4457. fields = (
  4458. 'site', 'power_panel', 'location', 'rack', 'name', 'status', 'type', 'mark_connected', 'supply', 'phase',
  4459. 'voltage', 'amperage', 'max_utilization', 'comments',
  4460. )
  4461. def __init__(self, data=None, *args, **kwargs):
  4462. super().__init__(data, *args, **kwargs)
  4463. if data:
  4464. # Limit power_panel queryset by site
  4465. params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
  4466. self.fields['power_panel'].queryset = self.fields['power_panel'].queryset.filter(**params)
  4467. # Limit location queryset by site
  4468. params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
  4469. self.fields['location'].queryset = self.fields['location'].queryset.filter(**params)
  4470. # Limit rack queryset by site and group
  4471. params = {
  4472. f"site__{self.fields['site'].to_field_name}": data.get('site'),
  4473. f"location__{self.fields['location'].to_field_name}": data.get('location'),
  4474. }
  4475. self.fields['rack'].queryset = self.fields['rack'].queryset.filter(**params)
  4476. class PowerFeedBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldModelBulkEditForm):
  4477. pk = forms.ModelMultipleChoiceField(
  4478. queryset=PowerFeed.objects.all(),
  4479. widget=forms.MultipleHiddenInput
  4480. )
  4481. power_panel = DynamicModelChoiceField(
  4482. queryset=PowerPanel.objects.all(),
  4483. required=False
  4484. )
  4485. rack = DynamicModelChoiceField(
  4486. queryset=Rack.objects.all(),
  4487. required=False,
  4488. )
  4489. status = forms.ChoiceField(
  4490. choices=add_blank_choice(PowerFeedStatusChoices),
  4491. required=False,
  4492. initial='',
  4493. widget=StaticSelect2()
  4494. )
  4495. type = forms.ChoiceField(
  4496. choices=add_blank_choice(PowerFeedTypeChoices),
  4497. required=False,
  4498. initial='',
  4499. widget=StaticSelect2()
  4500. )
  4501. supply = forms.ChoiceField(
  4502. choices=add_blank_choice(PowerFeedSupplyChoices),
  4503. required=False,
  4504. initial='',
  4505. widget=StaticSelect2()
  4506. )
  4507. phase = forms.ChoiceField(
  4508. choices=add_blank_choice(PowerFeedPhaseChoices),
  4509. required=False,
  4510. initial='',
  4511. widget=StaticSelect2()
  4512. )
  4513. voltage = forms.IntegerField(
  4514. required=False
  4515. )
  4516. amperage = forms.IntegerField(
  4517. required=False
  4518. )
  4519. max_utilization = forms.IntegerField(
  4520. required=False
  4521. )
  4522. mark_connected = forms.NullBooleanField(
  4523. required=False,
  4524. widget=BulkEditNullBooleanSelect
  4525. )
  4526. comments = CommentField(
  4527. widget=SmallTextarea,
  4528. label='Comments'
  4529. )
  4530. class Meta:
  4531. nullable_fields = [
  4532. 'location', 'comments',
  4533. ]
  4534. class PowerFeedFilterForm(BootstrapMixin, CustomFieldModelFilterForm):
  4535. model = PowerFeed
  4536. field_groups = [
  4537. ['region_id', 'site_group_id', 'site_id'],
  4538. ['power_panel_id', 'rack_id'],
  4539. ['type', 'supply', 'max_utilization'],
  4540. ['phase', 'voltage', 'amperage'],
  4541. ['status', 'tag']
  4542. ]
  4543. region_id = DynamicModelMultipleChoiceField(
  4544. queryset=Region.objects.all(),
  4545. required=False,
  4546. label=_('Region')
  4547. )
  4548. site_group_id = DynamicModelMultipleChoiceField(
  4549. queryset=SiteGroup.objects.all(),
  4550. required=False,
  4551. label=_('Site group')
  4552. )
  4553. site_id = DynamicModelMultipleChoiceField(
  4554. queryset=Site.objects.all(),
  4555. required=False,
  4556. query_params={
  4557. 'region_id': '$region_id'
  4558. },
  4559. label=_('Site')
  4560. )
  4561. power_panel_id = DynamicModelMultipleChoiceField(
  4562. queryset=PowerPanel.objects.all(),
  4563. required=False,
  4564. null_option='None',
  4565. query_params={
  4566. 'site_id': '$site_id'
  4567. },
  4568. label=_('Power panel')
  4569. )
  4570. rack_id = DynamicModelMultipleChoiceField(
  4571. queryset=Rack.objects.all(),
  4572. required=False,
  4573. null_option='None',
  4574. query_params={
  4575. 'site_id': '$site_id'
  4576. },
  4577. label=_('Rack')
  4578. )
  4579. status = forms.MultipleChoiceField(
  4580. choices=PowerFeedStatusChoices,
  4581. required=False,
  4582. widget=StaticSelect2Multiple()
  4583. )
  4584. type = forms.ChoiceField(
  4585. choices=add_blank_choice(PowerFeedTypeChoices),
  4586. required=False,
  4587. widget=StaticSelect2()
  4588. )
  4589. supply = forms.ChoiceField(
  4590. choices=add_blank_choice(PowerFeedSupplyChoices),
  4591. required=False,
  4592. widget=StaticSelect2()
  4593. )
  4594. phase = forms.ChoiceField(
  4595. choices=add_blank_choice(PowerFeedPhaseChoices),
  4596. required=False,
  4597. widget=StaticSelect2()
  4598. )
  4599. voltage = forms.IntegerField(
  4600. required=False
  4601. )
  4602. amperage = forms.IntegerField(
  4603. required=False
  4604. )
  4605. max_utilization = forms.IntegerField(
  4606. required=False
  4607. )
  4608. tag = TagFilterField(model)