forms.py 112 KB

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