forms.py 112 KB

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