forms.py 129 KB

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