forms.py 104 KB

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