forms.py 129 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502
  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} (NAT)') 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', 'label', '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', 'label', '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', 'label', '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(
  2301. device_query,
  2302. type=InterfaceTypeChoices.TYPE_LAG
  2303. ).exclude(pk=self.instance.pk)
  2304. # Add current site to VLANs query params
  2305. self.fields['untagged_vlan'].widget.add_query_param('site_id', device.site.pk)
  2306. self.fields['tagged_vlans'].widget.add_query_param('site_id', device.site.pk)
  2307. class InterfaceCreateForm(ComponentCreateForm, InterfaceCommonForm):
  2308. type = forms.ChoiceField(
  2309. choices=InterfaceTypeChoices,
  2310. widget=StaticSelect2(),
  2311. )
  2312. enabled = forms.BooleanField(
  2313. required=False,
  2314. initial=True
  2315. )
  2316. lag = forms.ModelChoiceField(
  2317. queryset=Interface.objects.all(),
  2318. required=False,
  2319. label='Parent LAG',
  2320. widget=StaticSelect2(),
  2321. )
  2322. mtu = forms.IntegerField(
  2323. required=False,
  2324. min_value=INTERFACE_MTU_MIN,
  2325. max_value=INTERFACE_MTU_MAX,
  2326. label='MTU'
  2327. )
  2328. mac_address = forms.CharField(
  2329. required=False,
  2330. label='MAC Address'
  2331. )
  2332. mgmt_only = forms.BooleanField(
  2333. required=False,
  2334. label='Management only',
  2335. help_text='This interface is used only for out-of-band management'
  2336. )
  2337. mode = forms.ChoiceField(
  2338. choices=add_blank_choice(InterfaceModeChoices),
  2339. required=False,
  2340. widget=StaticSelect2(),
  2341. )
  2342. untagged_vlan = DynamicModelChoiceField(
  2343. queryset=VLAN.objects.all(),
  2344. required=False,
  2345. display_field='display_name',
  2346. brief_mode=False,
  2347. query_params={
  2348. 'site_id': 'null',
  2349. }
  2350. )
  2351. tagged_vlans = DynamicModelMultipleChoiceField(
  2352. queryset=VLAN.objects.all(),
  2353. required=False,
  2354. display_field='display_name',
  2355. brief_mode=False,
  2356. query_params={
  2357. 'site_id': 'null',
  2358. }
  2359. )
  2360. field_order = (
  2361. 'device', 'name_pattern', 'label_pattern', 'type', 'enabled', 'lag', 'mtu', 'mac_address', 'description',
  2362. 'mgmt_only', 'mode', 'untagged_vlan', 'tagged_vlans', 'tags'
  2363. )
  2364. def __init__(self, *args, **kwargs):
  2365. super().__init__(*args, **kwargs)
  2366. # Limit LAG choices to interfaces belonging to this device or a peer VC member
  2367. device = Device.objects.get(
  2368. pk=self.initial.get('device') or self.data.get('device')
  2369. )
  2370. device_query = Q(device=device)
  2371. if device.virtual_chassis:
  2372. device_query |= Q(device__virtual_chassis=device.virtual_chassis)
  2373. self.fields['lag'].queryset = Interface.objects.filter(device_query, type=InterfaceTypeChoices.TYPE_LAG)
  2374. # Add current site to VLANs query params
  2375. self.fields['untagged_vlan'].widget.add_query_param('site_id', device.site.pk)
  2376. self.fields['tagged_vlans'].widget.add_query_param('site_id', device.site.pk)
  2377. class InterfaceBulkCreateForm(
  2378. form_from_model(Interface, ['type', 'enabled', 'mtu', 'mgmt_only']),
  2379. DeviceBulkAddComponentForm
  2380. ):
  2381. field_order = ('name_pattern', 'label_pattern', 'type', 'enabled', 'mtu', 'mgmt_only', 'description', 'tags')
  2382. class InterfaceBulkEditForm(
  2383. form_from_model(Interface, [
  2384. 'label', 'type', 'enabled', 'lag', 'mac_address', 'mtu', 'mgmt_only', 'description', 'mode'
  2385. ]),
  2386. BootstrapMixin,
  2387. AddRemoveTagsForm,
  2388. BulkEditForm
  2389. ):
  2390. pk = forms.ModelMultipleChoiceField(
  2391. queryset=Interface.objects.all(),
  2392. widget=forms.MultipleHiddenInput()
  2393. )
  2394. device = forms.ModelChoiceField(
  2395. queryset=Device.objects.all(),
  2396. required=False,
  2397. disabled=True,
  2398. widget=forms.HiddenInput()
  2399. )
  2400. untagged_vlan = DynamicModelChoiceField(
  2401. queryset=VLAN.objects.all(),
  2402. required=False,
  2403. display_field='display_name',
  2404. brief_mode=False,
  2405. query_params={
  2406. 'site_id': 'null',
  2407. }
  2408. )
  2409. tagged_vlans = DynamicModelMultipleChoiceField(
  2410. queryset=VLAN.objects.all(),
  2411. required=False,
  2412. display_field='display_name',
  2413. brief_mode=False,
  2414. query_params={
  2415. 'site_id': 'null',
  2416. }
  2417. )
  2418. class Meta:
  2419. nullable_fields = (
  2420. 'label', 'lag', 'mac_address', 'mtu', 'description', 'mode', 'untagged_vlan', 'tagged_vlans'
  2421. )
  2422. def __init__(self, *args, **kwargs):
  2423. super().__init__(*args, **kwargs)
  2424. # Limit LAG choices to interfaces which belong to the parent device (or VC master)
  2425. if 'device' in self.initial:
  2426. device = Device.objects.filter(pk=self.initial['device']).first()
  2427. self.fields['lag'].queryset = Interface.objects.filter(
  2428. device__in=[device, device.get_vc_master()],
  2429. type=InterfaceTypeChoices.TYPE_LAG
  2430. )
  2431. # Add current site to VLANs query params
  2432. self.fields['untagged_vlan'].widget.add_query_param('site_id', device.site.pk)
  2433. self.fields['tagged_vlans'].widget.add_query_param('site_id', device.site.pk)
  2434. else:
  2435. self.fields['lag'].choices = ()
  2436. self.fields['lag'].widget.attrs['disabled'] = True
  2437. def clean(self):
  2438. # Untagged interfaces cannot be assigned tagged VLANs
  2439. if self.cleaned_data['mode'] == InterfaceModeChoices.MODE_ACCESS and self.cleaned_data['tagged_vlans']:
  2440. raise forms.ValidationError({
  2441. 'mode': "An access interface cannot have tagged VLANs assigned."
  2442. })
  2443. # Remove all tagged VLAN assignments from "tagged all" interfaces
  2444. elif self.cleaned_data['mode'] == InterfaceModeChoices.MODE_TAGGED_ALL:
  2445. self.cleaned_data['tagged_vlans'] = []
  2446. class InterfaceCSVForm(CSVModelForm):
  2447. device = CSVModelChoiceField(
  2448. queryset=Device.objects.all(),
  2449. to_field_name='name'
  2450. )
  2451. lag = CSVModelChoiceField(
  2452. queryset=Interface.objects.all(),
  2453. required=False,
  2454. to_field_name='name',
  2455. help_text='Parent LAG interface'
  2456. )
  2457. type = CSVChoiceField(
  2458. choices=InterfaceTypeChoices,
  2459. help_text='Physical medium'
  2460. )
  2461. mode = CSVChoiceField(
  2462. choices=InterfaceModeChoices,
  2463. required=False,
  2464. help_text='IEEE 802.1Q operational mode (for L2 interfaces)'
  2465. )
  2466. class Meta:
  2467. model = Interface
  2468. fields = Interface.csv_headers
  2469. def __init__(self, *args, **kwargs):
  2470. super().__init__(*args, **kwargs)
  2471. # Limit LAG choices to interfaces belonging to this device (or virtual chassis)
  2472. device = None
  2473. if self.is_bound and 'device' in self.data:
  2474. try:
  2475. device = self.fields['device'].to_python(self.data['device'])
  2476. except forms.ValidationError:
  2477. pass
  2478. if device and device.virtual_chassis:
  2479. self.fields['lag'].queryset = Interface.objects.filter(
  2480. Q(device=device) | Q(device__virtual_chassis=device.virtual_chassis),
  2481. type=InterfaceTypeChoices.TYPE_LAG
  2482. )
  2483. elif device:
  2484. self.fields['lag'].queryset = Interface.objects.filter(
  2485. device=device,
  2486. type=InterfaceTypeChoices.TYPE_LAG
  2487. )
  2488. else:
  2489. self.fields['lag'].queryset = Interface.objects.none()
  2490. def clean_enabled(self):
  2491. # Make sure enabled is True when it's not included in the uploaded data
  2492. if 'enabled' not in self.data:
  2493. return True
  2494. else:
  2495. return self.cleaned_data['enabled']
  2496. #
  2497. # Front pass-through ports
  2498. #
  2499. class FrontPortFilterForm(DeviceComponentFilterForm):
  2500. model = FrontPort
  2501. type = forms.MultipleChoiceField(
  2502. choices=PortTypeChoices,
  2503. required=False,
  2504. widget=StaticSelect2Multiple()
  2505. )
  2506. tag = TagFilterField(model)
  2507. class FrontPortForm(BootstrapMixin, forms.ModelForm):
  2508. tags = DynamicModelMultipleChoiceField(
  2509. queryset=Tag.objects.all(),
  2510. required=False
  2511. )
  2512. class Meta:
  2513. model = FrontPort
  2514. fields = [
  2515. 'device', 'name', 'label', 'type', 'rear_port', 'rear_port_position', 'description', 'tags',
  2516. ]
  2517. widgets = {
  2518. 'device': forms.HiddenInput(),
  2519. 'type': StaticSelect2(),
  2520. 'rear_port': StaticSelect2(),
  2521. }
  2522. def __init__(self, *args, **kwargs):
  2523. super().__init__(*args, **kwargs)
  2524. # Limit RearPort choices to the local device
  2525. if hasattr(self.instance, 'device'):
  2526. self.fields['rear_port'].queryset = self.fields['rear_port'].queryset.filter(
  2527. device=self.instance.device
  2528. )
  2529. # TODO: Merge with FrontPortTemplateCreateForm to remove duplicate logic
  2530. class FrontPortCreateForm(ComponentCreateForm):
  2531. type = forms.ChoiceField(
  2532. choices=PortTypeChoices,
  2533. widget=StaticSelect2(),
  2534. )
  2535. rear_port_set = forms.MultipleChoiceField(
  2536. choices=[],
  2537. label='Rear ports',
  2538. help_text='Select one rear port assignment for each front port being created.',
  2539. )
  2540. field_order = ('device', 'name_pattern', 'label_pattern', 'type', 'rear_port_set', 'description', 'tags')
  2541. def __init__(self, *args, **kwargs):
  2542. super().__init__(*args, **kwargs)
  2543. device = Device.objects.get(
  2544. pk=self.initial.get('device') or self.data.get('device')
  2545. )
  2546. # Determine which rear port positions are occupied. These will be excluded from the list of available
  2547. # mappings.
  2548. occupied_port_positions = [
  2549. (front_port.rear_port_id, front_port.rear_port_position)
  2550. for front_port in device.frontports.all()
  2551. ]
  2552. # Populate rear port choices
  2553. choices = []
  2554. rear_ports = RearPort.objects.filter(device=device)
  2555. for rear_port in rear_ports:
  2556. for i in range(1, rear_port.positions + 1):
  2557. if (rear_port.pk, i) not in occupied_port_positions:
  2558. choices.append(
  2559. ('{}:{}'.format(rear_port.pk, i), '{}:{}'.format(rear_port.name, i))
  2560. )
  2561. self.fields['rear_port_set'].choices = choices
  2562. def clean(self):
  2563. # Validate that the number of ports being created equals the number of selected (rear port, position) tuples
  2564. front_port_count = len(self.cleaned_data['name_pattern'])
  2565. rear_port_count = len(self.cleaned_data['rear_port_set'])
  2566. if front_port_count != rear_port_count:
  2567. raise forms.ValidationError({
  2568. 'rear_port_set': 'The provided name pattern will create {} ports, however {} rear port assignments '
  2569. 'were selected. These counts must match.'.format(front_port_count, rear_port_count)
  2570. })
  2571. def get_iterative_data(self, iteration):
  2572. # Assign rear port and position from selected set
  2573. rear_port, position = self.cleaned_data['rear_port_set'][iteration].split(':')
  2574. return {
  2575. 'rear_port': int(rear_port),
  2576. 'rear_port_position': int(position),
  2577. }
  2578. # class FrontPortBulkCreateForm(
  2579. # form_from_model(FrontPort, ['label', 'type', 'description', 'tags']),
  2580. # DeviceBulkAddComponentForm
  2581. # ):
  2582. # pass
  2583. class FrontPortBulkEditForm(
  2584. form_from_model(FrontPort, ['label', 'type', 'description']),
  2585. BootstrapMixin,
  2586. AddRemoveTagsForm,
  2587. BulkEditForm
  2588. ):
  2589. pk = forms.ModelMultipleChoiceField(
  2590. queryset=FrontPort.objects.all(),
  2591. widget=forms.MultipleHiddenInput()
  2592. )
  2593. class Meta:
  2594. nullable_fields = ('label', 'description')
  2595. class FrontPortCSVForm(CSVModelForm):
  2596. device = CSVModelChoiceField(
  2597. queryset=Device.objects.all(),
  2598. to_field_name='name'
  2599. )
  2600. rear_port = CSVModelChoiceField(
  2601. queryset=RearPort.objects.all(),
  2602. to_field_name='name',
  2603. help_text='Corresponding rear port'
  2604. )
  2605. type = CSVChoiceField(
  2606. choices=PortTypeChoices,
  2607. help_text='Physical medium classification'
  2608. )
  2609. class Meta:
  2610. model = FrontPort
  2611. fields = FrontPort.csv_headers
  2612. help_texts = {
  2613. 'rear_port_position': 'Mapped position on corresponding rear port',
  2614. }
  2615. def __init__(self, *args, **kwargs):
  2616. super().__init__(*args, **kwargs)
  2617. # Limit RearPort choices to those belonging to this device (or VC master)
  2618. if self.is_bound:
  2619. try:
  2620. device = self.fields['device'].to_python(self.data['device'])
  2621. except forms.ValidationError:
  2622. device = None
  2623. else:
  2624. try:
  2625. device = self.instance.device
  2626. except Device.DoesNotExist:
  2627. device = None
  2628. if device:
  2629. self.fields['rear_port'].queryset = RearPort.objects.filter(
  2630. device__in=[device, device.get_vc_master()]
  2631. )
  2632. else:
  2633. self.fields['rear_port'].queryset = RearPort.objects.none()
  2634. #
  2635. # Rear pass-through ports
  2636. #
  2637. class RearPortFilterForm(DeviceComponentFilterForm):
  2638. model = RearPort
  2639. type = forms.MultipleChoiceField(
  2640. choices=PortTypeChoices,
  2641. required=False,
  2642. widget=StaticSelect2Multiple()
  2643. )
  2644. tag = TagFilterField(model)
  2645. class RearPortForm(BootstrapMixin, forms.ModelForm):
  2646. tags = DynamicModelMultipleChoiceField(
  2647. queryset=Tag.objects.all(),
  2648. required=False
  2649. )
  2650. class Meta:
  2651. model = RearPort
  2652. fields = [
  2653. 'device', 'name', 'label', 'type', 'positions', 'description', 'tags',
  2654. ]
  2655. widgets = {
  2656. 'device': forms.HiddenInput(),
  2657. 'type': StaticSelect2(),
  2658. }
  2659. class RearPortCreateForm(ComponentCreateForm):
  2660. type = forms.ChoiceField(
  2661. choices=PortTypeChoices,
  2662. widget=StaticSelect2(),
  2663. )
  2664. positions = forms.IntegerField(
  2665. min_value=REARPORT_POSITIONS_MIN,
  2666. max_value=REARPORT_POSITIONS_MAX,
  2667. initial=1,
  2668. help_text='The number of front ports which may be mapped to each rear port'
  2669. )
  2670. field_order = ('device', 'name_pattern', 'label_pattern', 'type', 'positions', 'description', 'tags')
  2671. class RearPortBulkCreateForm(
  2672. form_from_model(RearPort, ['type', 'positions']),
  2673. DeviceBulkAddComponentForm
  2674. ):
  2675. field_order = ('name_pattern', 'label_pattern', 'type', 'positions', 'description', 'tags')
  2676. class RearPortBulkEditForm(
  2677. form_from_model(RearPort, ['label', 'type', 'description']),
  2678. BootstrapMixin,
  2679. AddRemoveTagsForm,
  2680. BulkEditForm
  2681. ):
  2682. pk = forms.ModelMultipleChoiceField(
  2683. queryset=RearPort.objects.all(),
  2684. widget=forms.MultipleHiddenInput()
  2685. )
  2686. class Meta:
  2687. nullable_fields = ('label', 'description')
  2688. class RearPortCSVForm(CSVModelForm):
  2689. device = CSVModelChoiceField(
  2690. queryset=Device.objects.all(),
  2691. to_field_name='name'
  2692. )
  2693. type = CSVChoiceField(
  2694. help_text='Physical medium classification',
  2695. choices=PortTypeChoices,
  2696. )
  2697. class Meta:
  2698. model = RearPort
  2699. fields = RearPort.csv_headers
  2700. help_texts = {
  2701. 'positions': 'Number of front ports which may be mapped'
  2702. }
  2703. #
  2704. # Device bays
  2705. #
  2706. class DeviceBayFilterForm(DeviceComponentFilterForm):
  2707. model = DeviceBay
  2708. tag = TagFilterField(model)
  2709. class DeviceBayForm(BootstrapMixin, forms.ModelForm):
  2710. tags = DynamicModelMultipleChoiceField(
  2711. queryset=Tag.objects.all(),
  2712. required=False
  2713. )
  2714. class Meta:
  2715. model = DeviceBay
  2716. fields = [
  2717. 'device', 'name', 'label', 'description', 'tags',
  2718. ]
  2719. widgets = {
  2720. 'device': forms.HiddenInput(),
  2721. }
  2722. class DeviceBayCreateForm(ComponentCreateForm):
  2723. field_order = ('device', 'name_pattern', 'label_pattern', 'description', 'tags')
  2724. class PopulateDeviceBayForm(BootstrapMixin, forms.Form):
  2725. installed_device = forms.ModelChoiceField(
  2726. queryset=Device.objects.all(),
  2727. label='Child Device',
  2728. help_text="Child devices must first be created and assigned to the site/rack of the parent device.",
  2729. widget=StaticSelect2(),
  2730. )
  2731. def __init__(self, device_bay, *args, **kwargs):
  2732. super().__init__(*args, **kwargs)
  2733. self.fields['installed_device'].queryset = Device.objects.filter(
  2734. site=device_bay.device.site,
  2735. rack=device_bay.device.rack,
  2736. parent_bay__isnull=True,
  2737. device_type__u_height=0,
  2738. device_type__subdevice_role=SubdeviceRoleChoices.ROLE_CHILD
  2739. ).exclude(pk=device_bay.device.pk)
  2740. class DeviceBayBulkCreateForm(DeviceBulkAddComponentForm):
  2741. field_order = ('name_pattern', 'label_pattern', 'description', 'tags')
  2742. class DeviceBayBulkEditForm(
  2743. form_from_model(DeviceBay, ['label', 'description']),
  2744. BootstrapMixin,
  2745. AddRemoveTagsForm,
  2746. BulkEditForm
  2747. ):
  2748. pk = forms.ModelMultipleChoiceField(
  2749. queryset=DeviceBay.objects.all(),
  2750. widget=forms.MultipleHiddenInput()
  2751. )
  2752. class Meta:
  2753. nullable_fields = ('label', 'description')
  2754. class DeviceBayCSVForm(CSVModelForm):
  2755. device = CSVModelChoiceField(
  2756. queryset=Device.objects.all(),
  2757. to_field_name='name'
  2758. )
  2759. installed_device = CSVModelChoiceField(
  2760. queryset=Device.objects.all(),
  2761. required=False,
  2762. to_field_name='name',
  2763. help_text='Child device installed within this bay',
  2764. error_messages={
  2765. 'invalid_choice': 'Child device not found.',
  2766. }
  2767. )
  2768. class Meta:
  2769. model = DeviceBay
  2770. fields = DeviceBay.csv_headers
  2771. def __init__(self, *args, **kwargs):
  2772. super().__init__(*args, **kwargs)
  2773. # Limit installed device choices to devices of the correct type and location
  2774. if self.is_bound:
  2775. try:
  2776. device = self.fields['device'].to_python(self.data['device'])
  2777. except forms.ValidationError:
  2778. device = None
  2779. else:
  2780. try:
  2781. device = self.instance.device
  2782. except Device.DoesNotExist:
  2783. device = None
  2784. if device:
  2785. self.fields['installed_device'].queryset = Device.objects.filter(
  2786. site=device.site,
  2787. rack=device.rack,
  2788. parent_bay__isnull=True,
  2789. device_type__u_height=0,
  2790. device_type__subdevice_role=SubdeviceRoleChoices.ROLE_CHILD
  2791. ).exclude(pk=device.pk)
  2792. else:
  2793. self.fields['installed_device'].queryset = Interface.objects.none()
  2794. #
  2795. # Inventory items
  2796. #
  2797. class InventoryItemForm(BootstrapMixin, forms.ModelForm):
  2798. device = DynamicModelChoiceField(
  2799. queryset=Device.objects.all(),
  2800. display_field='display_name'
  2801. )
  2802. manufacturer = DynamicModelChoiceField(
  2803. queryset=Manufacturer.objects.all(),
  2804. required=False
  2805. )
  2806. tags = DynamicModelMultipleChoiceField(
  2807. queryset=Tag.objects.all(),
  2808. required=False
  2809. )
  2810. class Meta:
  2811. model = InventoryItem
  2812. fields = [
  2813. 'name', 'label', 'device', 'manufacturer', 'part_id', 'serial', 'asset_tag', 'description', 'tags',
  2814. ]
  2815. class InventoryItemCreateForm(ComponentCreateForm):
  2816. manufacturer = DynamicModelChoiceField(
  2817. queryset=Manufacturer.objects.all(),
  2818. required=False
  2819. )
  2820. part_id = forms.CharField(
  2821. max_length=50,
  2822. required=False,
  2823. label='Part ID'
  2824. )
  2825. serial = forms.CharField(
  2826. max_length=50,
  2827. required=False,
  2828. )
  2829. asset_tag = forms.CharField(
  2830. max_length=50,
  2831. required=False,
  2832. )
  2833. field_order = (
  2834. 'device', 'name_pattern', 'label_pattern', 'manufacturer', 'part_id', 'serial', 'asset_tag', 'description',
  2835. 'tags',
  2836. )
  2837. class InventoryItemCSVForm(CSVModelForm):
  2838. device = CSVModelChoiceField(
  2839. queryset=Device.objects.all(),
  2840. to_field_name='name'
  2841. )
  2842. manufacturer = CSVModelChoiceField(
  2843. queryset=Manufacturer.objects.all(),
  2844. to_field_name='name',
  2845. required=False
  2846. )
  2847. class Meta:
  2848. model = InventoryItem
  2849. fields = InventoryItem.csv_headers
  2850. class InventoryItemBulkCreateForm(
  2851. form_from_model(InventoryItem, ['manufacturer', 'part_id', 'serial', 'asset_tag', 'discovered']),
  2852. DeviceBulkAddComponentForm
  2853. ):
  2854. field_order = (
  2855. 'name_pattern', 'label_pattern', 'manufacturer', 'part_id', 'serial', 'asset_tag', 'discovered', 'description',
  2856. 'tags',
  2857. )
  2858. class InventoryItemBulkEditForm(
  2859. form_from_model(InventoryItem, ['label', 'manufacturer', 'part_id', 'description']),
  2860. BootstrapMixin,
  2861. AddRemoveTagsForm,
  2862. BulkEditForm
  2863. ):
  2864. pk = forms.ModelMultipleChoiceField(
  2865. queryset=InventoryItem.objects.all(),
  2866. widget=forms.MultipleHiddenInput()
  2867. )
  2868. manufacturer = DynamicModelChoiceField(
  2869. queryset=Manufacturer.objects.all(),
  2870. required=False
  2871. )
  2872. class Meta:
  2873. nullable_fields = ('label', 'manufacturer', 'part_id', 'description')
  2874. class InventoryItemFilterForm(DeviceComponentFilterForm):
  2875. model = InventoryItem
  2876. manufacturer = DynamicModelMultipleChoiceField(
  2877. queryset=Manufacturer.objects.all(),
  2878. to_field_name='slug',
  2879. required=False
  2880. )
  2881. serial = forms.CharField(
  2882. required=False
  2883. )
  2884. asset_tag = forms.CharField(
  2885. required=False
  2886. )
  2887. discovered = forms.NullBooleanField(
  2888. required=False,
  2889. widget=StaticSelect2(
  2890. choices=BOOLEAN_WITH_BLANK_CHOICES
  2891. )
  2892. )
  2893. tag = TagFilterField(model)
  2894. #
  2895. # Cables
  2896. #
  2897. class ConnectCableToDeviceForm(BootstrapMixin, forms.ModelForm):
  2898. """
  2899. Base form for connecting a Cable to a Device component
  2900. """
  2901. termination_b_site = DynamicModelChoiceField(
  2902. queryset=Site.objects.all(),
  2903. label='Site',
  2904. required=False
  2905. )
  2906. termination_b_rack = DynamicModelChoiceField(
  2907. queryset=Rack.objects.all(),
  2908. label='Rack',
  2909. required=False,
  2910. display_field='display_name',
  2911. null_option='None',
  2912. query_params={
  2913. 'site_id': '$termination_b_site'
  2914. }
  2915. )
  2916. termination_b_device = DynamicModelChoiceField(
  2917. queryset=Device.objects.all(),
  2918. label='Device',
  2919. required=False,
  2920. display_field='display_name',
  2921. query_params={
  2922. 'site_id': '$termination_b_site',
  2923. 'rack_id': '$termination_b_rack',
  2924. }
  2925. )
  2926. class Meta:
  2927. model = Cable
  2928. fields = [
  2929. 'termination_b_site', 'termination_b_rack', 'termination_b_device', 'termination_b_id', 'type', 'status',
  2930. 'label', 'color', 'length', 'length_unit',
  2931. ]
  2932. widgets = {
  2933. 'status': StaticSelect2,
  2934. 'type': StaticSelect2,
  2935. 'length_unit': StaticSelect2,
  2936. }
  2937. def clean_termination_b_id(self):
  2938. # Return the PK rather than the object
  2939. return getattr(self.cleaned_data['termination_b_id'], 'pk', None)
  2940. class ConnectCableToConsolePortForm(ConnectCableToDeviceForm):
  2941. termination_b_id = DynamicModelChoiceField(
  2942. queryset=ConsolePort.objects.all(),
  2943. label='Name',
  2944. disabled_indicator='cable',
  2945. query_params={
  2946. 'device_id': '$termination_b_device'
  2947. }
  2948. )
  2949. class ConnectCableToConsoleServerPortForm(ConnectCableToDeviceForm):
  2950. termination_b_id = DynamicModelChoiceField(
  2951. queryset=ConsoleServerPort.objects.all(),
  2952. label='Name',
  2953. disabled_indicator='cable',
  2954. query_params={
  2955. 'device_id': '$termination_b_device'
  2956. }
  2957. )
  2958. class ConnectCableToPowerPortForm(ConnectCableToDeviceForm):
  2959. termination_b_id = DynamicModelChoiceField(
  2960. queryset=PowerPort.objects.all(),
  2961. label='Name',
  2962. disabled_indicator='cable',
  2963. query_params={
  2964. 'device_id': '$termination_b_device'
  2965. }
  2966. )
  2967. class ConnectCableToPowerOutletForm(ConnectCableToDeviceForm):
  2968. termination_b_id = DynamicModelChoiceField(
  2969. queryset=PowerOutlet.objects.all(),
  2970. label='Name',
  2971. disabled_indicator='cable',
  2972. query_params={
  2973. 'device_id': '$termination_b_device'
  2974. }
  2975. )
  2976. class ConnectCableToInterfaceForm(ConnectCableToDeviceForm):
  2977. termination_b_id = DynamicModelChoiceField(
  2978. queryset=Interface.objects.all(),
  2979. label='Name',
  2980. disabled_indicator='cable',
  2981. query_params={
  2982. 'device_id': '$termination_b_device',
  2983. 'kind': 'physical',
  2984. }
  2985. )
  2986. class ConnectCableToFrontPortForm(ConnectCableToDeviceForm):
  2987. termination_b_id = DynamicModelChoiceField(
  2988. queryset=FrontPort.objects.all(),
  2989. label='Name',
  2990. disabled_indicator='cable',
  2991. query_params={
  2992. 'device_id': '$termination_b_device'
  2993. }
  2994. )
  2995. class ConnectCableToRearPortForm(ConnectCableToDeviceForm):
  2996. termination_b_id = DynamicModelChoiceField(
  2997. queryset=RearPort.objects.all(),
  2998. label='Name',
  2999. disabled_indicator='cable',
  3000. query_params={
  3001. 'device_id': '$termination_b_device'
  3002. }
  3003. )
  3004. class ConnectCableToCircuitTerminationForm(BootstrapMixin, forms.ModelForm):
  3005. termination_b_provider = DynamicModelChoiceField(
  3006. queryset=Provider.objects.all(),
  3007. label='Provider',
  3008. required=False
  3009. )
  3010. termination_b_site = DynamicModelChoiceField(
  3011. queryset=Site.objects.all(),
  3012. label='Site',
  3013. required=False
  3014. )
  3015. termination_b_circuit = DynamicModelChoiceField(
  3016. queryset=Circuit.objects.all(),
  3017. label='Circuit',
  3018. display_field='cid',
  3019. query_params={
  3020. 'provider_id': '$termination_b_provider',
  3021. 'site_id': '$termination_b_site',
  3022. }
  3023. )
  3024. termination_b_id = DynamicModelChoiceField(
  3025. queryset=CircuitTermination.objects.all(),
  3026. label='Side',
  3027. display_field='term_side',
  3028. disabled_indicator='cable',
  3029. query_params={
  3030. 'circuit_id': '$termination_b_circuit'
  3031. }
  3032. )
  3033. class Meta:
  3034. model = Cable
  3035. fields = [
  3036. 'termination_b_provider', 'termination_b_site', 'termination_b_circuit', 'termination_b_id', 'type',
  3037. 'status', 'label', 'color', 'length', 'length_unit',
  3038. ]
  3039. def clean_termination_b_id(self):
  3040. # Return the PK rather than the object
  3041. return getattr(self.cleaned_data['termination_b_id'], 'pk', None)
  3042. class ConnectCableToPowerFeedForm(BootstrapMixin, forms.ModelForm):
  3043. termination_b_site = DynamicModelChoiceField(
  3044. queryset=Site.objects.all(),
  3045. label='Site',
  3046. required=False,
  3047. display_field='cid'
  3048. )
  3049. termination_b_rackgroup = DynamicModelChoiceField(
  3050. queryset=RackGroup.objects.all(),
  3051. label='Rack Group',
  3052. required=False,
  3053. display_field='cid',
  3054. query_params={
  3055. 'site_id': '$termination_b_site'
  3056. }
  3057. )
  3058. termination_b_powerpanel = DynamicModelChoiceField(
  3059. queryset=PowerPanel.objects.all(),
  3060. label='Power Panel',
  3061. required=False,
  3062. query_params={
  3063. 'site_id': '$termination_b_site',
  3064. 'rack_group_id': '$termination_b_rackgroup',
  3065. }
  3066. )
  3067. termination_b_id = DynamicModelChoiceField(
  3068. queryset=PowerFeed.objects.all(),
  3069. label='Name',
  3070. disabled_indicator='cable',
  3071. query_params={
  3072. 'power_panel_id': '$termination_b_powerpanel'
  3073. }
  3074. )
  3075. class Meta:
  3076. model = Cable
  3077. fields = [
  3078. 'termination_b_rackgroup', 'termination_b_powerpanel', 'termination_b_id', 'type', 'status', 'label',
  3079. 'color', 'length', 'length_unit',
  3080. ]
  3081. def clean_termination_b_id(self):
  3082. # Return the PK rather than the object
  3083. return getattr(self.cleaned_data['termination_b_id'], 'pk', None)
  3084. class CableForm(BootstrapMixin, forms.ModelForm):
  3085. tags = DynamicModelMultipleChoiceField(
  3086. queryset=Tag.objects.all(),
  3087. required=False
  3088. )
  3089. class Meta:
  3090. model = Cable
  3091. fields = [
  3092. 'type', 'status', 'label', 'color', 'length', 'length_unit', 'tags',
  3093. ]
  3094. widgets = {
  3095. 'status': StaticSelect2,
  3096. 'type': StaticSelect2,
  3097. 'length_unit': StaticSelect2,
  3098. }
  3099. error_messages = {
  3100. 'length': {
  3101. 'max_value': 'Maximum length is 32767 (any unit)'
  3102. }
  3103. }
  3104. class CableCSVForm(CSVModelForm):
  3105. # Termination A
  3106. side_a_device = CSVModelChoiceField(
  3107. queryset=Device.objects.all(),
  3108. to_field_name='name',
  3109. help_text='Side A device'
  3110. )
  3111. side_a_type = CSVModelChoiceField(
  3112. queryset=ContentType.objects.all(),
  3113. limit_choices_to=CABLE_TERMINATION_MODELS,
  3114. to_field_name='model',
  3115. help_text='Side A type'
  3116. )
  3117. side_a_name = forms.CharField(
  3118. help_text='Side A component name'
  3119. )
  3120. # Termination B
  3121. side_b_device = CSVModelChoiceField(
  3122. queryset=Device.objects.all(),
  3123. to_field_name='name',
  3124. help_text='Side B device'
  3125. )
  3126. side_b_type = CSVModelChoiceField(
  3127. queryset=ContentType.objects.all(),
  3128. limit_choices_to=CABLE_TERMINATION_MODELS,
  3129. to_field_name='model',
  3130. help_text='Side B type'
  3131. )
  3132. side_b_name = forms.CharField(
  3133. help_text='Side B component name'
  3134. )
  3135. # Cable attributes
  3136. status = CSVChoiceField(
  3137. choices=CableStatusChoices,
  3138. required=False,
  3139. help_text='Connection status'
  3140. )
  3141. type = CSVChoiceField(
  3142. choices=CableTypeChoices,
  3143. required=False,
  3144. help_text='Physical medium classification'
  3145. )
  3146. length_unit = CSVChoiceField(
  3147. choices=CableLengthUnitChoices,
  3148. required=False,
  3149. help_text='Length unit'
  3150. )
  3151. class Meta:
  3152. model = Cable
  3153. fields = [
  3154. 'side_a_device', 'side_a_type', 'side_a_name', 'side_b_device', 'side_b_type', 'side_b_name', 'type',
  3155. 'status', 'label', 'color', 'length', 'length_unit',
  3156. ]
  3157. help_texts = {
  3158. 'color': mark_safe('RGB color in hexadecimal (e.g. <code>00ff00</code>)'),
  3159. }
  3160. # TODO: Merge the clean() methods for either end
  3161. def clean_side_a_name(self):
  3162. device = self.cleaned_data.get('side_a_device')
  3163. content_type = self.cleaned_data.get('side_a_type')
  3164. name = self.cleaned_data.get('side_a_name')
  3165. if not device or not content_type or not name:
  3166. return None
  3167. model = content_type.model_class()
  3168. try:
  3169. termination_object = model.objects.get(
  3170. device=device,
  3171. name=name
  3172. )
  3173. if termination_object.cable is not None:
  3174. raise forms.ValidationError(
  3175. "Side A: {} {} is already connected".format(device, termination_object)
  3176. )
  3177. except ObjectDoesNotExist:
  3178. raise forms.ValidationError(
  3179. "A side termination not found: {} {}".format(device, name)
  3180. )
  3181. self.instance.termination_a = termination_object
  3182. return termination_object
  3183. def clean_side_b_name(self):
  3184. device = self.cleaned_data.get('side_b_device')
  3185. content_type = self.cleaned_data.get('side_b_type')
  3186. name = self.cleaned_data.get('side_b_name')
  3187. if not device or not content_type or not name:
  3188. return None
  3189. model = content_type.model_class()
  3190. try:
  3191. termination_object = model.objects.get(
  3192. device=device,
  3193. name=name
  3194. )
  3195. if termination_object.cable is not None:
  3196. raise forms.ValidationError(
  3197. "Side B: {} {} is already connected".format(device, termination_object)
  3198. )
  3199. except ObjectDoesNotExist:
  3200. raise forms.ValidationError(
  3201. "B side termination not found: {} {}".format(device, name)
  3202. )
  3203. self.instance.termination_b = termination_object
  3204. return termination_object
  3205. def clean_length_unit(self):
  3206. # Avoid trying to save as NULL
  3207. length_unit = self.cleaned_data.get('length_unit', None)
  3208. return length_unit if length_unit is not None else ''
  3209. class CableBulkEditForm(BootstrapMixin, AddRemoveTagsForm, BulkEditForm):
  3210. pk = forms.ModelMultipleChoiceField(
  3211. queryset=Cable.objects.all(),
  3212. widget=forms.MultipleHiddenInput
  3213. )
  3214. type = forms.ChoiceField(
  3215. choices=add_blank_choice(CableTypeChoices),
  3216. required=False,
  3217. initial='',
  3218. widget=StaticSelect2()
  3219. )
  3220. status = forms.ChoiceField(
  3221. choices=add_blank_choice(CableStatusChoices),
  3222. required=False,
  3223. widget=StaticSelect2(),
  3224. initial=''
  3225. )
  3226. label = forms.CharField(
  3227. max_length=100,
  3228. required=False
  3229. )
  3230. color = forms.CharField(
  3231. max_length=6, # RGB color code
  3232. required=False,
  3233. widget=ColorSelect()
  3234. )
  3235. length = forms.IntegerField(
  3236. min_value=1,
  3237. required=False
  3238. )
  3239. length_unit = forms.ChoiceField(
  3240. choices=add_blank_choice(CableLengthUnitChoices),
  3241. required=False,
  3242. initial='',
  3243. widget=StaticSelect2()
  3244. )
  3245. class Meta:
  3246. nullable_fields = [
  3247. 'type', 'status', 'label', 'color', 'length',
  3248. ]
  3249. def clean(self):
  3250. # Validate length/unit
  3251. length = self.cleaned_data.get('length')
  3252. length_unit = self.cleaned_data.get('length_unit')
  3253. if length and not length_unit:
  3254. raise forms.ValidationError({
  3255. 'length_unit': "Must specify a unit when setting length"
  3256. })
  3257. class CableFilterForm(BootstrapMixin, forms.Form):
  3258. model = Cable
  3259. q = forms.CharField(
  3260. required=False,
  3261. label='Search'
  3262. )
  3263. site = DynamicModelMultipleChoiceField(
  3264. queryset=Site.objects.all(),
  3265. to_field_name='slug',
  3266. required=False
  3267. )
  3268. tenant = DynamicModelMultipleChoiceField(
  3269. queryset=Tenant.objects.all(),
  3270. to_field_name='slug',
  3271. required=False
  3272. )
  3273. rack_id = DynamicModelMultipleChoiceField(
  3274. queryset=Rack.objects.all(),
  3275. required=False,
  3276. label='Rack',
  3277. null_option='None',
  3278. query_params={
  3279. 'site': '$site'
  3280. }
  3281. )
  3282. type = forms.MultipleChoiceField(
  3283. choices=add_blank_choice(CableTypeChoices),
  3284. required=False,
  3285. widget=StaticSelect2()
  3286. )
  3287. status = forms.ChoiceField(
  3288. required=False,
  3289. choices=add_blank_choice(CableStatusChoices),
  3290. widget=StaticSelect2()
  3291. )
  3292. color = forms.CharField(
  3293. max_length=6, # RGB color code
  3294. required=False,
  3295. widget=ColorSelect()
  3296. )
  3297. device_id = DynamicModelMultipleChoiceField(
  3298. queryset=Device.objects.all(),
  3299. required=False,
  3300. label='Device',
  3301. query_params={
  3302. 'site': '$site',
  3303. 'tenant': '$tenant',
  3304. 'rack_id': '$rack_id',
  3305. }
  3306. )
  3307. tag = TagFilterField(model)
  3308. #
  3309. # Connections
  3310. #
  3311. class ConsoleConnectionFilterForm(BootstrapMixin, forms.Form):
  3312. site = DynamicModelMultipleChoiceField(
  3313. queryset=Site.objects.all(),
  3314. to_field_name='slug',
  3315. required=False
  3316. )
  3317. device_id = DynamicModelMultipleChoiceField(
  3318. queryset=Device.objects.all(),
  3319. required=False,
  3320. label='Device',
  3321. query_params={
  3322. 'site': '$site'
  3323. }
  3324. )
  3325. class PowerConnectionFilterForm(BootstrapMixin, forms.Form):
  3326. site = DynamicModelMultipleChoiceField(
  3327. queryset=Site.objects.all(),
  3328. to_field_name='slug',
  3329. required=False
  3330. )
  3331. device_id = DynamicModelMultipleChoiceField(
  3332. queryset=Device.objects.all(),
  3333. required=False,
  3334. label='Device',
  3335. query_params={
  3336. 'site': '$site'
  3337. }
  3338. )
  3339. class InterfaceConnectionFilterForm(BootstrapMixin, forms.Form):
  3340. site = DynamicModelMultipleChoiceField(
  3341. queryset=Site.objects.all(),
  3342. to_field_name='slug',
  3343. required=False
  3344. )
  3345. device_id = DynamicModelMultipleChoiceField(
  3346. queryset=Device.objects.all(),
  3347. required=False,
  3348. label='Device',
  3349. query_params={
  3350. 'site': '$site'
  3351. }
  3352. )
  3353. #
  3354. # Virtual chassis
  3355. #
  3356. class DeviceSelectionForm(forms.Form):
  3357. pk = forms.ModelMultipleChoiceField(
  3358. queryset=Device.objects.all(),
  3359. widget=forms.MultipleHiddenInput()
  3360. )
  3361. class VirtualChassisCreateForm(BootstrapMixin, forms.ModelForm):
  3362. site = DynamicModelChoiceField(
  3363. queryset=Site.objects.all(),
  3364. required=False
  3365. )
  3366. rack = DynamicModelChoiceField(
  3367. queryset=Rack.objects.all(),
  3368. required=False,
  3369. null_option='None',
  3370. display_field='display_name',
  3371. query_params={
  3372. 'site_id': '$site'
  3373. }
  3374. )
  3375. members = DynamicModelMultipleChoiceField(
  3376. queryset=Device.objects.all(),
  3377. required=False,
  3378. display_field='display_name',
  3379. query_params={
  3380. 'site_id': '$site',
  3381. 'rack_id': '$rack',
  3382. }
  3383. )
  3384. initial_position = forms.IntegerField(
  3385. initial=1,
  3386. required=False,
  3387. help_text='Position of the first member device. Increases by one for each additional member.'
  3388. )
  3389. tags = DynamicModelMultipleChoiceField(
  3390. queryset=Tag.objects.all(),
  3391. required=False
  3392. )
  3393. class Meta:
  3394. model = VirtualChassis
  3395. fields = [
  3396. 'name', 'domain', 'site', 'rack', 'members', 'initial_position', 'tags',
  3397. ]
  3398. def save(self, *args, **kwargs):
  3399. instance = super().save(*args, **kwargs)
  3400. # Assign VC members
  3401. if instance.pk:
  3402. initial_position = self.cleaned_data.get('initial_position') or 1
  3403. for i, member in enumerate(self.cleaned_data['members'], start=initial_position):
  3404. member.virtual_chassis = instance
  3405. member.vc_position = i
  3406. member.save()
  3407. return instance
  3408. class VirtualChassisForm(BootstrapMixin, forms.ModelForm):
  3409. master = forms.ModelChoiceField(
  3410. queryset=Device.objects.all(),
  3411. required=False,
  3412. )
  3413. tags = DynamicModelMultipleChoiceField(
  3414. queryset=Tag.objects.all(),
  3415. required=False
  3416. )
  3417. class Meta:
  3418. model = VirtualChassis
  3419. fields = [
  3420. 'name', 'domain', 'master', 'tags',
  3421. ]
  3422. widgets = {
  3423. 'master': SelectWithPK(),
  3424. }
  3425. def __init__(self, *args, **kwargs):
  3426. super().__init__(*args, **kwargs)
  3427. self.fields['master'].queryset = Device.objects.filter(virtual_chassis=self.instance)
  3428. class BaseVCMemberFormSet(forms.BaseModelFormSet):
  3429. def clean(self):
  3430. super().clean()
  3431. # Check for duplicate VC position values
  3432. vc_position_list = []
  3433. for form in self.forms:
  3434. vc_position = form.cleaned_data.get('vc_position')
  3435. if vc_position:
  3436. if vc_position in vc_position_list:
  3437. error_msg = 'A virtual chassis member already exists in position {}.'.format(vc_position)
  3438. form.add_error('vc_position', error_msg)
  3439. vc_position_list.append(vc_position)
  3440. class DeviceVCMembershipForm(forms.ModelForm):
  3441. class Meta:
  3442. model = Device
  3443. fields = [
  3444. 'vc_position', 'vc_priority',
  3445. ]
  3446. labels = {
  3447. 'vc_position': 'Position',
  3448. 'vc_priority': 'Priority',
  3449. }
  3450. def __init__(self, validate_vc_position=False, *args, **kwargs):
  3451. super().__init__(*args, **kwargs)
  3452. # Require VC position (only required when the Device is a VirtualChassis member)
  3453. self.fields['vc_position'].required = True
  3454. # Validation of vc_position is optional. This is only required when adding a new member to an existing
  3455. # VirtualChassis. Otherwise, vc_position validation is handled by BaseVCMemberFormSet.
  3456. self.validate_vc_position = validate_vc_position
  3457. def clean_vc_position(self):
  3458. vc_position = self.cleaned_data['vc_position']
  3459. if self.validate_vc_position:
  3460. conflicting_members = Device.objects.filter(
  3461. virtual_chassis=self.instance.virtual_chassis,
  3462. vc_position=vc_position
  3463. )
  3464. if conflicting_members.exists():
  3465. raise forms.ValidationError(
  3466. 'A virtual chassis member already exists in position {}.'.format(vc_position)
  3467. )
  3468. return vc_position
  3469. class VCMemberSelectForm(BootstrapMixin, forms.Form):
  3470. site = DynamicModelChoiceField(
  3471. queryset=Site.objects.all(),
  3472. required=False
  3473. )
  3474. rack = DynamicModelChoiceField(
  3475. queryset=Rack.objects.all(),
  3476. required=False,
  3477. null_option='None',
  3478. display_field='display_name',
  3479. query_params={
  3480. 'site_id': '$site'
  3481. }
  3482. )
  3483. device = DynamicModelChoiceField(
  3484. queryset=Device.objects.all(),
  3485. display_field='display_name',
  3486. query_params={
  3487. 'site_id': '$site',
  3488. 'rack_id': '$rack',
  3489. 'virtual_chassis_id': 'null',
  3490. }
  3491. )
  3492. def clean_device(self):
  3493. device = self.cleaned_data['device']
  3494. if device.virtual_chassis is not None:
  3495. raise forms.ValidationError(
  3496. f"Device {device} is already assigned to a virtual chassis."
  3497. )
  3498. return device
  3499. class VirtualChassisBulkEditForm(BootstrapMixin, AddRemoveTagsForm, BulkEditForm):
  3500. pk = forms.ModelMultipleChoiceField(
  3501. queryset=VirtualChassis.objects.all(),
  3502. widget=forms.MultipleHiddenInput()
  3503. )
  3504. domain = forms.CharField(
  3505. max_length=30,
  3506. required=False
  3507. )
  3508. class Meta:
  3509. nullable_fields = ['domain']
  3510. class VirtualChassisCSVForm(CSVModelForm):
  3511. master = CSVModelChoiceField(
  3512. queryset=Device.objects.all(),
  3513. to_field_name='name',
  3514. required=False,
  3515. help_text='Master device'
  3516. )
  3517. class Meta:
  3518. model = VirtualChassis
  3519. fields = VirtualChassis.csv_headers
  3520. class VirtualChassisFilterForm(BootstrapMixin, CustomFieldFilterForm):
  3521. model = VirtualChassis
  3522. q = forms.CharField(
  3523. required=False,
  3524. label='Search'
  3525. )
  3526. region = DynamicModelMultipleChoiceField(
  3527. queryset=Region.objects.all(),
  3528. to_field_name='slug',
  3529. required=False
  3530. )
  3531. site = DynamicModelMultipleChoiceField(
  3532. queryset=Site.objects.all(),
  3533. to_field_name='slug',
  3534. required=False,
  3535. query_params={
  3536. 'region': '$region'
  3537. }
  3538. )
  3539. tenant_group = DynamicModelMultipleChoiceField(
  3540. queryset=TenantGroup.objects.all(),
  3541. to_field_name='slug',
  3542. required=False,
  3543. null_option='None'
  3544. )
  3545. tenant = DynamicModelMultipleChoiceField(
  3546. queryset=Tenant.objects.all(),
  3547. to_field_name='slug',
  3548. required=False,
  3549. null_option='None',
  3550. query_params={
  3551. 'group': '$tenant_group'
  3552. }
  3553. )
  3554. tag = TagFilterField(model)
  3555. #
  3556. # Power panels
  3557. #
  3558. class PowerPanelForm(BootstrapMixin, forms.ModelForm):
  3559. site = DynamicModelChoiceField(
  3560. queryset=Site.objects.all()
  3561. )
  3562. rack_group = DynamicModelChoiceField(
  3563. queryset=RackGroup.objects.all(),
  3564. required=False,
  3565. query_params={
  3566. 'site_id': '$site'
  3567. }
  3568. )
  3569. tags = DynamicModelMultipleChoiceField(
  3570. queryset=Tag.objects.all(),
  3571. required=False
  3572. )
  3573. class Meta:
  3574. model = PowerPanel
  3575. fields = [
  3576. 'site', 'rack_group', 'name', 'tags',
  3577. ]
  3578. class PowerPanelCSVForm(CSVModelForm):
  3579. site = CSVModelChoiceField(
  3580. queryset=Site.objects.all(),
  3581. to_field_name='name',
  3582. help_text='Name of parent site'
  3583. )
  3584. rack_group = CSVModelChoiceField(
  3585. queryset=RackGroup.objects.all(),
  3586. required=False,
  3587. to_field_name='name'
  3588. )
  3589. class Meta:
  3590. model = PowerPanel
  3591. fields = PowerPanel.csv_headers
  3592. def __init__(self, data=None, *args, **kwargs):
  3593. super().__init__(data, *args, **kwargs)
  3594. if data:
  3595. # Limit group queryset by assigned site
  3596. params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
  3597. self.fields['rack_group'].queryset = self.fields['rack_group'].queryset.filter(**params)
  3598. class PowerPanelBulkEditForm(BootstrapMixin, AddRemoveTagsForm, BulkEditForm):
  3599. pk = forms.ModelMultipleChoiceField(
  3600. queryset=PowerPanel.objects.all(),
  3601. widget=forms.MultipleHiddenInput
  3602. )
  3603. site = DynamicModelChoiceField(
  3604. queryset=Site.objects.all(),
  3605. required=False
  3606. )
  3607. rack_group = DynamicModelChoiceField(
  3608. queryset=RackGroup.objects.all(),
  3609. required=False,
  3610. query_params={
  3611. 'site_id': '$site'
  3612. }
  3613. )
  3614. class Meta:
  3615. nullable_fields = (
  3616. 'rack_group',
  3617. )
  3618. class PowerPanelFilterForm(BootstrapMixin, CustomFieldFilterForm):
  3619. model = PowerPanel
  3620. q = forms.CharField(
  3621. required=False,
  3622. label='Search'
  3623. )
  3624. region = DynamicModelMultipleChoiceField(
  3625. queryset=Region.objects.all(),
  3626. to_field_name='slug',
  3627. required=False
  3628. )
  3629. site = DynamicModelMultipleChoiceField(
  3630. queryset=Site.objects.all(),
  3631. to_field_name='slug',
  3632. required=False,
  3633. query_params={
  3634. 'region': '$region'
  3635. }
  3636. )
  3637. rack_group_id = DynamicModelMultipleChoiceField(
  3638. queryset=RackGroup.objects.all(),
  3639. required=False,
  3640. label='Rack group (ID)',
  3641. null_option='None',
  3642. query_params={
  3643. 'site': '$site'
  3644. }
  3645. )
  3646. tag = TagFilterField(model)
  3647. #
  3648. # Power feeds
  3649. #
  3650. class PowerFeedForm(BootstrapMixin, CustomFieldModelForm):
  3651. site = DynamicModelChoiceField(
  3652. queryset=Site.objects.all(),
  3653. required=False
  3654. )
  3655. power_panel = DynamicModelChoiceField(
  3656. queryset=PowerPanel.objects.all(),
  3657. query_params={
  3658. 'site_id': '$site'
  3659. }
  3660. )
  3661. rack = DynamicModelChoiceField(
  3662. queryset=Rack.objects.all(),
  3663. required=False,
  3664. display_field='display_name',
  3665. query_params={
  3666. 'site_id': '$site'
  3667. }
  3668. )
  3669. comments = CommentField()
  3670. tags = DynamicModelMultipleChoiceField(
  3671. queryset=Tag.objects.all(),
  3672. required=False
  3673. )
  3674. class Meta:
  3675. model = PowerFeed
  3676. fields = [
  3677. 'site', 'power_panel', 'rack', 'name', 'status', 'type', 'supply', 'phase', 'voltage', 'amperage',
  3678. 'max_utilization', 'comments', 'tags',
  3679. ]
  3680. widgets = {
  3681. 'status': StaticSelect2(),
  3682. 'type': StaticSelect2(),
  3683. 'supply': StaticSelect2(),
  3684. 'phase': StaticSelect2(),
  3685. }
  3686. def __init__(self, *args, **kwargs):
  3687. super().__init__(*args, **kwargs)
  3688. # Initialize site field
  3689. if self.instance and hasattr(self.instance, 'power_panel'):
  3690. self.initial['site'] = self.instance.power_panel.site
  3691. class PowerFeedCSVForm(CustomFieldModelCSVForm):
  3692. site = CSVModelChoiceField(
  3693. queryset=Site.objects.all(),
  3694. to_field_name='name',
  3695. help_text='Assigned site'
  3696. )
  3697. power_panel = CSVModelChoiceField(
  3698. queryset=PowerPanel.objects.all(),
  3699. to_field_name='name',
  3700. help_text='Upstream power panel'
  3701. )
  3702. rack_group = CSVModelChoiceField(
  3703. queryset=RackGroup.objects.all(),
  3704. to_field_name='name',
  3705. required=False,
  3706. help_text="Rack's group (if any)"
  3707. )
  3708. rack = CSVModelChoiceField(
  3709. queryset=Rack.objects.all(),
  3710. to_field_name='name',
  3711. required=False,
  3712. help_text='Rack'
  3713. )
  3714. status = CSVChoiceField(
  3715. choices=PowerFeedStatusChoices,
  3716. required=False,
  3717. help_text='Operational status'
  3718. )
  3719. type = CSVChoiceField(
  3720. choices=PowerFeedTypeChoices,
  3721. required=False,
  3722. help_text='Primary or redundant'
  3723. )
  3724. supply = CSVChoiceField(
  3725. choices=PowerFeedSupplyChoices,
  3726. required=False,
  3727. help_text='Supply type (AC/DC)'
  3728. )
  3729. phase = CSVChoiceField(
  3730. choices=PowerFeedPhaseChoices,
  3731. required=False,
  3732. help_text='Single or three-phase'
  3733. )
  3734. class Meta:
  3735. model = PowerFeed
  3736. fields = PowerFeed.csv_headers
  3737. def __init__(self, data=None, *args, **kwargs):
  3738. super().__init__(data, *args, **kwargs)
  3739. if data:
  3740. # Limit power_panel queryset by site
  3741. params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
  3742. self.fields['power_panel'].queryset = self.fields['power_panel'].queryset.filter(**params)
  3743. # Limit rack_group queryset by site
  3744. params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
  3745. self.fields['rack_group'].queryset = self.fields['rack_group'].queryset.filter(**params)
  3746. # Limit rack queryset by site and group
  3747. params = {
  3748. f"site__{self.fields['site'].to_field_name}": data.get('site'),
  3749. f"group__{self.fields['rack_group'].to_field_name}": data.get('rack_group'),
  3750. }
  3751. self.fields['rack'].queryset = self.fields['rack'].queryset.filter(**params)
  3752. class PowerFeedBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldBulkEditForm):
  3753. pk = forms.ModelMultipleChoiceField(
  3754. queryset=PowerFeed.objects.all(),
  3755. widget=forms.MultipleHiddenInput
  3756. )
  3757. power_panel = DynamicModelChoiceField(
  3758. queryset=PowerPanel.objects.all(),
  3759. required=False
  3760. )
  3761. rack = DynamicModelChoiceField(
  3762. queryset=Rack.objects.all(),
  3763. required=False,
  3764. display_field='display_name'
  3765. )
  3766. status = forms.ChoiceField(
  3767. choices=add_blank_choice(PowerFeedStatusChoices),
  3768. required=False,
  3769. initial='',
  3770. widget=StaticSelect2()
  3771. )
  3772. type = forms.ChoiceField(
  3773. choices=add_blank_choice(PowerFeedTypeChoices),
  3774. required=False,
  3775. initial='',
  3776. widget=StaticSelect2()
  3777. )
  3778. supply = forms.ChoiceField(
  3779. choices=add_blank_choice(PowerFeedSupplyChoices),
  3780. required=False,
  3781. initial='',
  3782. widget=StaticSelect2()
  3783. )
  3784. phase = forms.ChoiceField(
  3785. choices=add_blank_choice(PowerFeedPhaseChoices),
  3786. required=False,
  3787. initial='',
  3788. widget=StaticSelect2()
  3789. )
  3790. voltage = forms.IntegerField(
  3791. required=False
  3792. )
  3793. amperage = forms.IntegerField(
  3794. required=False
  3795. )
  3796. max_utilization = forms.IntegerField(
  3797. required=False
  3798. )
  3799. comments = CommentField(
  3800. widget=SmallTextarea,
  3801. label='Comments'
  3802. )
  3803. class Meta:
  3804. nullable_fields = [
  3805. 'rackgroup', 'comments',
  3806. ]
  3807. class PowerFeedFilterForm(BootstrapMixin, CustomFieldFilterForm):
  3808. model = PowerFeed
  3809. q = forms.CharField(
  3810. required=False,
  3811. label='Search'
  3812. )
  3813. region = DynamicModelMultipleChoiceField(
  3814. queryset=Region.objects.all(),
  3815. to_field_name='slug',
  3816. required=False
  3817. )
  3818. site = DynamicModelMultipleChoiceField(
  3819. queryset=Site.objects.all(),
  3820. to_field_name='slug',
  3821. required=False,
  3822. query_params={
  3823. 'region': '$region'
  3824. }
  3825. )
  3826. power_panel_id = DynamicModelMultipleChoiceField(
  3827. queryset=PowerPanel.objects.all(),
  3828. required=False,
  3829. label='Power panel',
  3830. null_option='None',
  3831. query_params={
  3832. 'site': '$site'
  3833. }
  3834. )
  3835. rack_id = DynamicModelMultipleChoiceField(
  3836. queryset=Rack.objects.all(),
  3837. required=False,
  3838. label='Rack',
  3839. null_option='None',
  3840. query_params={
  3841. 'site': '$site'
  3842. }
  3843. )
  3844. status = forms.MultipleChoiceField(
  3845. choices=PowerFeedStatusChoices,
  3846. required=False,
  3847. widget=StaticSelect2Multiple()
  3848. )
  3849. type = forms.ChoiceField(
  3850. choices=add_blank_choice(PowerFeedTypeChoices),
  3851. required=False,
  3852. widget=StaticSelect2()
  3853. )
  3854. supply = forms.ChoiceField(
  3855. choices=add_blank_choice(PowerFeedSupplyChoices),
  3856. required=False,
  3857. widget=StaticSelect2()
  3858. )
  3859. phase = forms.ChoiceField(
  3860. choices=add_blank_choice(PowerFeedPhaseChoices),
  3861. required=False,
  3862. widget=StaticSelect2()
  3863. )
  3864. voltage = forms.IntegerField(
  3865. required=False
  3866. )
  3867. amperage = forms.IntegerField(
  3868. required=False
  3869. )
  3870. max_utilization = forms.IntegerField(
  3871. required=False
  3872. )
  3873. tag = TagFilterField(model)