forms.py 103 KB

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