forms.py 134 KB

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