forms.py 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327
  1. from __future__ import unicode_literals
  2. import re
  3. from django import forms
  4. from django.contrib.auth.models import User
  5. from django.contrib.postgres.forms.array import SimpleArrayField
  6. from django.db.models import Count, Q
  7. from mptt.forms import TreeNodeChoiceField
  8. from taggit.forms import TagField
  9. from timezone_field import TimeZoneFormField
  10. from extras.forms import AddRemoveTagsForm, CustomFieldForm, CustomFieldBulkEditForm, CustomFieldFilterForm
  11. from ipam.models import IPAddress, VLAN, VLANGroup
  12. from tenancy.forms import TenancyForm
  13. from tenancy.models import Tenant
  14. from utilities.forms import (
  15. AnnotatedMultipleChoiceField, APISelect, add_blank_choice, ArrayFieldSelectMultiple, BootstrapMixin, BulkEditForm,
  16. BulkEditNullBooleanSelect, ChainedFieldsMixin, ChainedModelChoiceField, CommentField, ComponentForm,
  17. ConfirmationForm, CSVChoiceField, ExpandableNameField, FilterChoiceField, FilterTreeNodeMultipleChoiceField,
  18. FlexibleModelChoiceField, Livesearch, SelectWithDisabled, SelectWithPK, SmallTextarea, SlugField,
  19. )
  20. from virtualization.models import Cluster
  21. from .constants import (
  22. CONNECTION_STATUS_CHOICES, CONNECTION_STATUS_CONNECTED, DEVICE_STATUS_CHOICES, IFACE_FF_CHOICES, IFACE_FF_LAG,
  23. IFACE_MODE_ACCESS, IFACE_MODE_CHOICES, IFACE_MODE_TAGGED_ALL, IFACE_ORDERING_CHOICES, RACK_FACE_CHOICES,
  24. RACK_TYPE_CHOICES, RACK_WIDTH_CHOICES, RACK_WIDTH_19IN, RACK_WIDTH_23IN, SITE_STATUS_CHOICES, SUBDEVICE_ROLE_CHILD,
  25. SUBDEVICE_ROLE_PARENT, SUBDEVICE_ROLE_CHOICES,
  26. )
  27. from .formfields import MACAddressFormField
  28. from .models import (
  29. DeviceBay, DeviceBayTemplate, ConsolePort, ConsolePortTemplate, ConsoleServerPort, ConsoleServerPortTemplate,
  30. Device, DeviceRole, DeviceType, Interface, InterfaceConnection, InterfaceTemplate, Manufacturer, InventoryItem,
  31. Platform, PowerOutlet, PowerOutletTemplate, PowerPort, PowerPortTemplate, Rack, RackGroup, RackReservation,
  32. RackRole, Region, Site, VirtualChassis
  33. )
  34. DEVICE_BY_PK_RE = r'{\d+\}'
  35. INTERFACE_MODE_HELP_TEXT = """
  36. Access: One untagged VLAN<br />
  37. Tagged: One untagged VLAN and/or one or more tagged VLANs<br />
  38. Tagged All: Implies all VLANs are available (w/optional untagged VLAN)
  39. """
  40. def get_device_by_name_or_pk(name):
  41. """
  42. Attempt to retrieve a device by either its name or primary key ('{pk}').
  43. """
  44. if re.match(DEVICE_BY_PK_RE, name):
  45. pk = name.strip('{}')
  46. device = Device.objects.get(pk=pk)
  47. else:
  48. device = Device.objects.get(name=name)
  49. return device
  50. class BulkRenameForm(forms.Form):
  51. """
  52. An extendable form to be used for renaming device components in bulk.
  53. """
  54. find = forms.CharField()
  55. replace = forms.CharField()
  56. #
  57. # Regions
  58. #
  59. class RegionForm(BootstrapMixin, forms.ModelForm):
  60. slug = SlugField()
  61. class Meta:
  62. model = Region
  63. fields = ['parent', 'name', 'slug']
  64. class RegionCSVForm(forms.ModelForm):
  65. parent = forms.ModelChoiceField(
  66. queryset=Region.objects.all(),
  67. required=False,
  68. to_field_name='name',
  69. help_text='Name of parent region',
  70. error_messages={
  71. 'invalid_choice': 'Region not found.',
  72. }
  73. )
  74. class Meta:
  75. model = Region
  76. fields = Region.csv_headers
  77. help_texts = {
  78. 'name': 'Region name',
  79. 'slug': 'URL-friendly slug',
  80. }
  81. class RegionFilterForm(BootstrapMixin, forms.Form):
  82. model = Site
  83. q = forms.CharField(required=False, label='Search')
  84. #
  85. # Sites
  86. #
  87. class SiteForm(BootstrapMixin, TenancyForm, CustomFieldForm):
  88. region = TreeNodeChoiceField(queryset=Region.objects.all(), required=False)
  89. slug = SlugField()
  90. comments = CommentField()
  91. tags = TagField(required=False)
  92. class Meta:
  93. model = Site
  94. fields = [
  95. 'name', 'slug', 'status', 'region', 'tenant_group', 'tenant', 'facility', 'asn', 'time_zone', 'description',
  96. 'physical_address', 'shipping_address', 'latitude', 'longitude', 'contact_name', 'contact_phone',
  97. 'contact_email', 'comments', 'tags',
  98. ]
  99. widgets = {
  100. 'physical_address': SmallTextarea(attrs={'rows': 3}),
  101. 'shipping_address': SmallTextarea(attrs={'rows': 3}),
  102. }
  103. help_texts = {
  104. 'name': "Full name of the site",
  105. 'facility': "Data center provider and facility (e.g. Equinix NY7)",
  106. 'asn': "BGP autonomous system number",
  107. 'time_zone': "Local time zone",
  108. 'description': "Short description (will appear in sites list)",
  109. 'physical_address': "Physical location of the building (e.g. for GPS)",
  110. 'shipping_address': "If different from the physical address",
  111. 'latitude': "Latitude in decimal format (xx.yyyyyy)",
  112. 'longitude': "Longitude in decimal format (xx.yyyyyy)"
  113. }
  114. class SiteCSVForm(forms.ModelForm):
  115. status = CSVChoiceField(
  116. choices=SITE_STATUS_CHOICES,
  117. required=False,
  118. help_text='Operational status'
  119. )
  120. region = forms.ModelChoiceField(
  121. queryset=Region.objects.all(),
  122. required=False,
  123. to_field_name='name',
  124. help_text='Name of assigned region',
  125. error_messages={
  126. 'invalid_choice': 'Region not found.',
  127. }
  128. )
  129. tenant = forms.ModelChoiceField(
  130. queryset=Tenant.objects.all(),
  131. required=False,
  132. to_field_name='name',
  133. help_text='Name of assigned tenant',
  134. error_messages={
  135. 'invalid_choice': 'Tenant not found.',
  136. }
  137. )
  138. class Meta:
  139. model = Site
  140. fields = Site.csv_headers
  141. help_texts = {
  142. 'name': 'Site name',
  143. 'slug': 'URL-friendly slug',
  144. 'asn': '32-bit autonomous system number',
  145. }
  146. class SiteBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldBulkEditForm):
  147. pk = forms.ModelMultipleChoiceField(
  148. queryset=Site.objects.all(),
  149. widget=forms.MultipleHiddenInput
  150. )
  151. status = forms.ChoiceField(
  152. choices=add_blank_choice(SITE_STATUS_CHOICES),
  153. required=False,
  154. initial=''
  155. )
  156. region = TreeNodeChoiceField(
  157. queryset=Region.objects.all(),
  158. required=False
  159. )
  160. tenant = forms.ModelChoiceField(
  161. queryset=Tenant.objects.all(),
  162. required=False
  163. )
  164. asn = forms.IntegerField(
  165. min_value=1,
  166. max_value=4294967295,
  167. required=False,
  168. label='ASN'
  169. )
  170. description = forms.CharField(
  171. max_length=100,
  172. required=False
  173. )
  174. time_zone = TimeZoneFormField(
  175. choices=add_blank_choice(TimeZoneFormField().choices),
  176. required=False
  177. )
  178. class Meta:
  179. nullable_fields = ['region', 'tenant', 'asn', 'description', 'time_zone']
  180. class SiteFilterForm(BootstrapMixin, CustomFieldFilterForm):
  181. model = Site
  182. q = forms.CharField(required=False, label='Search')
  183. status = AnnotatedMultipleChoiceField(
  184. choices=SITE_STATUS_CHOICES,
  185. annotate=Site.objects.all(),
  186. annotate_field='status',
  187. required=False
  188. )
  189. region = FilterTreeNodeMultipleChoiceField(
  190. queryset=Region.objects.annotate(filter_count=Count('sites')),
  191. to_field_name='slug',
  192. required=False,
  193. )
  194. tenant = FilterChoiceField(
  195. queryset=Tenant.objects.annotate(filter_count=Count('sites')),
  196. to_field_name='slug',
  197. null_label='-- None --'
  198. )
  199. #
  200. # Rack groups
  201. #
  202. class RackGroupForm(BootstrapMixin, forms.ModelForm):
  203. slug = SlugField()
  204. class Meta:
  205. model = RackGroup
  206. fields = ['site', 'name', 'slug']
  207. class RackGroupCSVForm(forms.ModelForm):
  208. site = forms.ModelChoiceField(
  209. queryset=Site.objects.all(),
  210. to_field_name='name',
  211. help_text='Name of parent site',
  212. error_messages={
  213. 'invalid_choice': 'Site not found.',
  214. }
  215. )
  216. class Meta:
  217. model = RackGroup
  218. fields = RackGroup.csv_headers
  219. help_texts = {
  220. 'name': 'Name of rack group',
  221. 'slug': 'URL-friendly slug',
  222. }
  223. class RackGroupFilterForm(BootstrapMixin, forms.Form):
  224. site = FilterChoiceField(queryset=Site.objects.annotate(filter_count=Count('rack_groups')), to_field_name='slug')
  225. #
  226. # Rack roles
  227. #
  228. class RackRoleForm(BootstrapMixin, forms.ModelForm):
  229. slug = SlugField()
  230. class Meta:
  231. model = RackRole
  232. fields = ['name', 'slug', 'color']
  233. class RackRoleCSVForm(forms.ModelForm):
  234. slug = SlugField()
  235. class Meta:
  236. model = RackRole
  237. fields = RackRole.csv_headers
  238. help_texts = {
  239. 'name': 'Name of rack role',
  240. 'color': 'RGB color in hexadecimal (e.g. 00ff00)'
  241. }
  242. #
  243. # Racks
  244. #
  245. class RackForm(BootstrapMixin, TenancyForm, CustomFieldForm):
  246. group = ChainedModelChoiceField(
  247. queryset=RackGroup.objects.all(),
  248. chains=(
  249. ('site', 'site'),
  250. ),
  251. required=False,
  252. widget=APISelect(
  253. api_url='/api/dcim/rack-groups/?site_id={{site}}',
  254. )
  255. )
  256. comments = CommentField()
  257. tags = TagField(required=False)
  258. class Meta:
  259. model = Rack
  260. fields = [
  261. 'site', 'group', 'name', 'facility_id', 'tenant_group', 'tenant', 'role', 'serial', 'type', 'width',
  262. 'u_height', 'desc_units', 'comments', 'tags',
  263. ]
  264. help_texts = {
  265. 'site': "The site at which the rack exists",
  266. 'name': "Organizational rack name",
  267. 'facility_id': "The unique rack ID assigned by the facility",
  268. 'u_height': "Height in rack units",
  269. }
  270. widgets = {
  271. 'site': forms.Select(attrs={'filter-for': 'group'}),
  272. }
  273. class RackCSVForm(forms.ModelForm):
  274. site = forms.ModelChoiceField(
  275. queryset=Site.objects.all(),
  276. to_field_name='name',
  277. help_text='Name of parent site',
  278. error_messages={
  279. 'invalid_choice': 'Site not found.',
  280. }
  281. )
  282. group_name = forms.CharField(
  283. help_text='Name of rack group',
  284. required=False
  285. )
  286. tenant = forms.ModelChoiceField(
  287. queryset=Tenant.objects.all(),
  288. required=False,
  289. to_field_name='name',
  290. help_text='Name of assigned tenant',
  291. error_messages={
  292. 'invalid_choice': 'Tenant not found.',
  293. }
  294. )
  295. role = forms.ModelChoiceField(
  296. queryset=RackRole.objects.all(),
  297. required=False,
  298. to_field_name='name',
  299. help_text='Name of assigned role',
  300. error_messages={
  301. 'invalid_choice': 'Role not found.',
  302. }
  303. )
  304. type = CSVChoiceField(
  305. choices=RACK_TYPE_CHOICES,
  306. required=False,
  307. help_text='Rack type'
  308. )
  309. width = forms.ChoiceField(
  310. choices=(
  311. (RACK_WIDTH_19IN, '19'),
  312. (RACK_WIDTH_23IN, '23'),
  313. ),
  314. help_text='Rail-to-rail width (in inches)'
  315. )
  316. class Meta:
  317. model = Rack
  318. fields = Rack.csv_headers
  319. help_texts = {
  320. 'name': 'Rack name',
  321. 'u_height': 'Height in rack units',
  322. }
  323. def clean(self):
  324. super(RackCSVForm, self).clean()
  325. site = self.cleaned_data.get('site')
  326. group_name = self.cleaned_data.get('group_name')
  327. name = self.cleaned_data.get('name')
  328. facility_id = self.cleaned_data.get('facility_id')
  329. # Validate rack group
  330. if group_name:
  331. try:
  332. self.instance.group = RackGroup.objects.get(site=site, name=group_name)
  333. except RackGroup.DoesNotExist:
  334. raise forms.ValidationError("Rack group {} not found for site {}".format(group_name, site))
  335. # Validate uniqueness of rack name within group
  336. if Rack.objects.filter(group=self.instance.group, name=name).exists():
  337. raise forms.ValidationError(
  338. "A rack named {} already exists within group {}".format(name, group_name)
  339. )
  340. # Validate uniqueness of facility ID within group
  341. if facility_id and Rack.objects.filter(group=self.instance.group, facility_id=facility_id).exists():
  342. raise forms.ValidationError(
  343. "A rack with the facility ID {} already exists within group {}".format(facility_id, group_name)
  344. )
  345. class RackBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldBulkEditForm):
  346. pk = forms.ModelMultipleChoiceField(queryset=Rack.objects.all(), widget=forms.MultipleHiddenInput)
  347. site = forms.ModelChoiceField(queryset=Site.objects.all(), required=False, label='Site')
  348. group = forms.ModelChoiceField(queryset=RackGroup.objects.all(), required=False, label='Group')
  349. tenant = forms.ModelChoiceField(queryset=Tenant.objects.all(), required=False)
  350. role = forms.ModelChoiceField(queryset=RackRole.objects.all(), required=False)
  351. serial = forms.CharField(max_length=50, required=False, label='Serial Number')
  352. type = forms.ChoiceField(choices=add_blank_choice(RACK_TYPE_CHOICES), required=False, label='Type')
  353. width = forms.ChoiceField(choices=add_blank_choice(RACK_WIDTH_CHOICES), required=False, label='Width')
  354. u_height = forms.IntegerField(required=False, label='Height (U)')
  355. desc_units = forms.NullBooleanField(required=False, widget=BulkEditNullBooleanSelect, label='Descending units')
  356. comments = CommentField(widget=SmallTextarea)
  357. class Meta:
  358. nullable_fields = ['group', 'tenant', 'role', 'serial', 'comments']
  359. class RackFilterForm(BootstrapMixin, CustomFieldFilterForm):
  360. model = Rack
  361. q = forms.CharField(required=False, label='Search')
  362. site = FilterChoiceField(
  363. queryset=Site.objects.annotate(filter_count=Count('racks')),
  364. to_field_name='slug'
  365. )
  366. group_id = FilterChoiceField(
  367. queryset=RackGroup.objects.select_related('site').annotate(filter_count=Count('racks')),
  368. label='Rack group',
  369. null_label='-- None --'
  370. )
  371. tenant = FilterChoiceField(
  372. queryset=Tenant.objects.annotate(filter_count=Count('racks')),
  373. to_field_name='slug',
  374. null_label='-- None --'
  375. )
  376. role = FilterChoiceField(
  377. queryset=RackRole.objects.annotate(filter_count=Count('racks')),
  378. to_field_name='slug',
  379. null_label='-- None --'
  380. )
  381. #
  382. # Rack reservations
  383. #
  384. class RackReservationForm(BootstrapMixin, TenancyForm, forms.ModelForm):
  385. units = SimpleArrayField(forms.IntegerField(), widget=ArrayFieldSelectMultiple(attrs={'size': 10}))
  386. user = forms.ModelChoiceField(queryset=User.objects.order_by('username'))
  387. class Meta:
  388. model = RackReservation
  389. fields = ['units', 'user', 'tenant_group', 'tenant', 'description']
  390. def __init__(self, *args, **kwargs):
  391. super(RackReservationForm, self).__init__(*args, **kwargs)
  392. # Populate rack unit choices
  393. self.fields['units'].widget.choices = self._get_unit_choices()
  394. def _get_unit_choices(self):
  395. rack = self.instance.rack
  396. reserved_units = []
  397. for resv in rack.reservations.exclude(pk=self.instance.pk):
  398. for u in resv.units:
  399. reserved_units.append(u)
  400. unit_choices = [(u, {'label': str(u), 'disabled': u in reserved_units}) for u in rack.units]
  401. return unit_choices
  402. class RackReservationFilterForm(BootstrapMixin, forms.Form):
  403. q = forms.CharField(required=False, label='Search')
  404. site = FilterChoiceField(
  405. queryset=Site.objects.annotate(filter_count=Count('racks__reservations')),
  406. to_field_name='slug'
  407. )
  408. group_id = FilterChoiceField(
  409. queryset=RackGroup.objects.select_related('site').annotate(filter_count=Count('racks__reservations')),
  410. label='Rack group',
  411. null_label='-- None --'
  412. )
  413. tenant = FilterChoiceField(
  414. queryset=Tenant.objects.annotate(filter_count=Count('rackreservations')),
  415. to_field_name='slug',
  416. null_label='-- None --'
  417. )
  418. class RackReservationBulkEditForm(BootstrapMixin, BulkEditForm):
  419. pk = forms.ModelMultipleChoiceField(queryset=RackReservation.objects.all(), widget=forms.MultipleHiddenInput)
  420. user = forms.ModelChoiceField(queryset=User.objects.order_by('username'), required=False)
  421. tenant = forms.ModelChoiceField(queryset=Tenant.objects.all(), required=False)
  422. description = forms.CharField(max_length=100, required=False)
  423. class Meta:
  424. nullable_fields = []
  425. #
  426. # Manufacturers
  427. #
  428. class ManufacturerForm(BootstrapMixin, forms.ModelForm):
  429. slug = SlugField()
  430. class Meta:
  431. model = Manufacturer
  432. fields = ['name', 'slug']
  433. class ManufacturerCSVForm(forms.ModelForm):
  434. class Meta:
  435. model = Manufacturer
  436. fields = Manufacturer.csv_headers
  437. help_texts = {
  438. 'name': 'Manufacturer name',
  439. 'slug': 'URL-friendly slug',
  440. }
  441. #
  442. # Device types
  443. #
  444. class DeviceTypeForm(BootstrapMixin, CustomFieldForm):
  445. slug = SlugField(slug_source='model')
  446. tags = TagField(required=False)
  447. class Meta:
  448. model = DeviceType
  449. fields = [
  450. 'manufacturer', 'model', 'slug', 'part_number', 'u_height', 'is_full_depth', 'is_console_server', 'is_pdu',
  451. 'is_network_device', 'subdevice_role', 'interface_ordering', 'comments', 'tags',
  452. ]
  453. labels = {
  454. 'interface_ordering': 'Order interfaces by',
  455. }
  456. class DeviceTypeCSVForm(forms.ModelForm):
  457. manufacturer = forms.ModelChoiceField(
  458. queryset=Manufacturer.objects.all(),
  459. required=True,
  460. to_field_name='name',
  461. help_text='Manufacturer name',
  462. error_messages={
  463. 'invalid_choice': 'Manufacturer not found.',
  464. }
  465. )
  466. subdevice_role = CSVChoiceField(
  467. choices=SUBDEVICE_ROLE_CHOICES,
  468. required=False,
  469. help_text='Parent/child status'
  470. )
  471. interface_ordering = CSVChoiceField(
  472. choices=IFACE_ORDERING_CHOICES,
  473. required=False,
  474. help_text='Interface ordering'
  475. )
  476. class Meta:
  477. model = DeviceType
  478. fields = DeviceType.csv_headers
  479. help_texts = {
  480. 'model': 'Model name',
  481. 'slug': 'URL-friendly slug',
  482. }
  483. class DeviceTypeBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldBulkEditForm):
  484. pk = forms.ModelMultipleChoiceField(queryset=DeviceType.objects.all(), widget=forms.MultipleHiddenInput)
  485. manufacturer = forms.ModelChoiceField(queryset=Manufacturer.objects.all(), required=False)
  486. u_height = forms.IntegerField(min_value=1, required=False)
  487. is_full_depth = forms.NullBooleanField(required=False, widget=BulkEditNullBooleanSelect, label='Is full depth')
  488. interface_ordering = forms.ChoiceField(choices=add_blank_choice(IFACE_ORDERING_CHOICES), required=False)
  489. is_console_server = forms.NullBooleanField(
  490. required=False, widget=BulkEditNullBooleanSelect, label='Is a console server'
  491. )
  492. is_pdu = forms.NullBooleanField(required=False, widget=BulkEditNullBooleanSelect, label='Is a PDU')
  493. is_network_device = forms.NullBooleanField(
  494. required=False, widget=BulkEditNullBooleanSelect, label='Is a network device'
  495. )
  496. class Meta:
  497. nullable_fields = []
  498. class DeviceTypeFilterForm(BootstrapMixin, CustomFieldFilterForm):
  499. model = DeviceType
  500. q = forms.CharField(required=False, label='Search')
  501. manufacturer = FilterChoiceField(
  502. queryset=Manufacturer.objects.annotate(filter_count=Count('device_types')),
  503. to_field_name='slug'
  504. )
  505. is_console_server = forms.BooleanField(
  506. required=False, label='Is a console server', widget=forms.CheckboxInput(attrs={'value': 'True'}))
  507. is_pdu = forms.BooleanField(
  508. required=False, label='Is a PDU', widget=forms.CheckboxInput(attrs={'value': 'True'})
  509. )
  510. is_network_device = forms.BooleanField(
  511. required=False, label='Is a network device', widget=forms.CheckboxInput(attrs={'value': 'True'})
  512. )
  513. subdevice_role = forms.NullBooleanField(
  514. required=False, label='Subdevice role', widget=forms.Select(choices=(
  515. ('', '---------'),
  516. (SUBDEVICE_ROLE_PARENT, 'Parent'),
  517. (SUBDEVICE_ROLE_CHILD, 'Child'),
  518. ))
  519. )
  520. #
  521. # Device component templates
  522. #
  523. class ConsolePortTemplateForm(BootstrapMixin, forms.ModelForm):
  524. class Meta:
  525. model = ConsolePortTemplate
  526. fields = ['device_type', 'name']
  527. widgets = {
  528. 'device_type': forms.HiddenInput(),
  529. }
  530. class ConsolePortTemplateCreateForm(ComponentForm):
  531. name_pattern = ExpandableNameField(label='Name')
  532. class ConsoleServerPortTemplateForm(BootstrapMixin, forms.ModelForm):
  533. class Meta:
  534. model = ConsoleServerPortTemplate
  535. fields = ['device_type', 'name']
  536. widgets = {
  537. 'device_type': forms.HiddenInput(),
  538. }
  539. class ConsoleServerPortTemplateCreateForm(ComponentForm):
  540. name_pattern = ExpandableNameField(label='Name')
  541. class PowerPortTemplateForm(BootstrapMixin, forms.ModelForm):
  542. class Meta:
  543. model = PowerPortTemplate
  544. fields = ['device_type', 'name']
  545. widgets = {
  546. 'device_type': forms.HiddenInput(),
  547. }
  548. class PowerPortTemplateCreateForm(ComponentForm):
  549. name_pattern = ExpandableNameField(label='Name')
  550. class PowerOutletTemplateForm(BootstrapMixin, forms.ModelForm):
  551. class Meta:
  552. model = PowerOutletTemplate
  553. fields = ['device_type', 'name']
  554. widgets = {
  555. 'device_type': forms.HiddenInput(),
  556. }
  557. class PowerOutletTemplateCreateForm(ComponentForm):
  558. name_pattern = ExpandableNameField(label='Name')
  559. class InterfaceTemplateForm(BootstrapMixin, forms.ModelForm):
  560. class Meta:
  561. model = InterfaceTemplate
  562. fields = ['device_type', 'name', 'form_factor', 'mgmt_only']
  563. widgets = {
  564. 'device_type': forms.HiddenInput(),
  565. }
  566. class InterfaceTemplateCreateForm(ComponentForm):
  567. name_pattern = ExpandableNameField(label='Name')
  568. form_factor = forms.ChoiceField(choices=IFACE_FF_CHOICES)
  569. mgmt_only = forms.BooleanField(required=False, label='OOB Management')
  570. class InterfaceTemplateBulkEditForm(BootstrapMixin, BulkEditForm):
  571. pk = forms.ModelMultipleChoiceField(queryset=InterfaceTemplate.objects.all(), widget=forms.MultipleHiddenInput)
  572. form_factor = forms.ChoiceField(choices=add_blank_choice(IFACE_FF_CHOICES), required=False)
  573. mgmt_only = forms.NullBooleanField(required=False, widget=BulkEditNullBooleanSelect, label='Management only')
  574. class Meta:
  575. nullable_fields = []
  576. class DeviceBayTemplateForm(BootstrapMixin, forms.ModelForm):
  577. class Meta:
  578. model = DeviceBayTemplate
  579. fields = ['device_type', 'name']
  580. widgets = {
  581. 'device_type': forms.HiddenInput(),
  582. }
  583. class DeviceBayTemplateCreateForm(ComponentForm):
  584. name_pattern = ExpandableNameField(label='Name')
  585. #
  586. # Device roles
  587. #
  588. class DeviceRoleForm(BootstrapMixin, forms.ModelForm):
  589. slug = SlugField()
  590. class Meta:
  591. model = DeviceRole
  592. fields = ['name', 'slug', 'color', 'vm_role']
  593. class DeviceRoleCSVForm(forms.ModelForm):
  594. slug = SlugField()
  595. class Meta:
  596. model = DeviceRole
  597. fields = DeviceRole.csv_headers
  598. help_texts = {
  599. 'name': 'Name of device role',
  600. 'color': 'RGB color in hexadecimal (e.g. 00ff00)'
  601. }
  602. #
  603. # Platforms
  604. #
  605. class PlatformForm(BootstrapMixin, forms.ModelForm):
  606. slug = SlugField()
  607. class Meta:
  608. model = Platform
  609. fields = ['name', 'slug', 'manufacturer', 'napalm_driver', 'napalm_args', 'rpc_client']
  610. widgets = {
  611. 'napalm_args': SmallTextarea(),
  612. }
  613. class PlatformCSVForm(forms.ModelForm):
  614. slug = SlugField()
  615. manufacturer = forms.ModelChoiceField(
  616. queryset=Manufacturer.objects.all(),
  617. required=False,
  618. to_field_name='name',
  619. help_text='Manufacturer name',
  620. error_messages={
  621. 'invalid_choice': 'Manufacturer not found.',
  622. }
  623. )
  624. class Meta:
  625. model = Platform
  626. fields = Platform.csv_headers
  627. help_texts = {
  628. 'name': 'Platform name',
  629. }
  630. #
  631. # Devices
  632. #
  633. class DeviceForm(BootstrapMixin, TenancyForm, CustomFieldForm):
  634. site = forms.ModelChoiceField(
  635. queryset=Site.objects.all(),
  636. widget=forms.Select(
  637. attrs={'filter-for': 'rack'}
  638. )
  639. )
  640. rack = ChainedModelChoiceField(
  641. queryset=Rack.objects.all(),
  642. chains=(
  643. ('site', 'site'),
  644. ),
  645. required=False,
  646. widget=APISelect(
  647. api_url='/api/dcim/racks/?site_id={{site}}',
  648. display_field='display_name',
  649. attrs={'filter-for': 'position'}
  650. )
  651. )
  652. position = forms.TypedChoiceField(
  653. required=False,
  654. empty_value=None,
  655. help_text="The lowest-numbered unit occupied by the device",
  656. widget=APISelect(
  657. api_url='/api/dcim/racks/{{rack}}/units/?face={{face}}',
  658. disabled_indicator='device'
  659. )
  660. )
  661. manufacturer = forms.ModelChoiceField(
  662. queryset=Manufacturer.objects.all(),
  663. widget=forms.Select(
  664. attrs={'filter-for': 'device_type'}
  665. )
  666. )
  667. device_type = ChainedModelChoiceField(
  668. queryset=DeviceType.objects.all(),
  669. chains=(
  670. ('manufacturer', 'manufacturer'),
  671. ),
  672. label='Device type',
  673. widget=APISelect(
  674. api_url='/api/dcim/device-types/?manufacturer_id={{manufacturer}}',
  675. display_field='model'
  676. )
  677. )
  678. comments = CommentField()
  679. tags = TagField(required=False)
  680. class Meta:
  681. model = Device
  682. fields = [
  683. 'name', 'device_role', 'device_type', 'serial', 'asset_tag', 'site', 'rack', 'position', 'face',
  684. 'status', 'platform', 'primary_ip4', 'primary_ip6', 'tenant_group', 'tenant', 'comments', 'tags',
  685. ]
  686. help_texts = {
  687. 'device_role': "The function this device serves",
  688. 'serial': "Chassis serial number",
  689. }
  690. widgets = {
  691. 'face': forms.Select(attrs={'filter-for': 'position'}),
  692. }
  693. def __init__(self, *args, **kwargs):
  694. # Initialize helper selectors
  695. instance = kwargs.get('instance')
  696. # Using hasattr() instead of "is not None" to avoid RelatedObjectDoesNotExist on required field
  697. if instance and hasattr(instance, 'device_type'):
  698. initial = kwargs.get('initial', {}).copy()
  699. initial['manufacturer'] = instance.device_type.manufacturer
  700. kwargs['initial'] = initial
  701. super(DeviceForm, self).__init__(*args, **kwargs)
  702. if self.instance.pk:
  703. # Compile list of choices for primary IPv4 and IPv6 addresses
  704. for family in [4, 6]:
  705. ip_choices = [(None, '---------')]
  706. # Gather PKs of all interfaces belonging to this Device or a peer VirtualChassis member
  707. interface_ids = self.instance.vc_interfaces.values('pk')
  708. # Collect interface IPs
  709. interface_ips = IPAddress.objects.select_related('interface').filter(
  710. family=family, interface_id__in=interface_ids
  711. )
  712. if interface_ips:
  713. ip_list = [(ip.id, '{} ({})'.format(ip.address, ip.interface)) for ip in interface_ips]
  714. ip_choices.append(('Interface IPs', ip_list))
  715. # Collect NAT IPs
  716. nat_ips = IPAddress.objects.select_related('nat_inside').filter(
  717. family=family, nat_inside__interface__in=interface_ids
  718. )
  719. if nat_ips:
  720. ip_list = [(ip.id, '{} ({})'.format(ip.address, ip.nat_inside.address)) for ip in nat_ips]
  721. ip_choices.append(('NAT IPs', ip_list))
  722. self.fields['primary_ip{}'.format(family)].choices = ip_choices
  723. # If editing an existing device, exclude it from the list of occupied rack units. This ensures that a device
  724. # can be flipped from one face to another.
  725. self.fields['position'].widget.attrs['api-url'] += '&exclude={}'.format(self.instance.pk)
  726. # Limit platform by manufacturer
  727. self.fields['platform'].queryset = Platform.objects.filter(
  728. Q(manufacturer__isnull=True) | Q(manufacturer=self.instance.device_type.manufacturer)
  729. )
  730. else:
  731. # An object that doesn't exist yet can't have any IPs assigned to it
  732. self.fields['primary_ip4'].choices = []
  733. self.fields['primary_ip4'].widget.attrs['readonly'] = True
  734. self.fields['primary_ip6'].choices = []
  735. self.fields['primary_ip6'].widget.attrs['readonly'] = True
  736. # Rack position
  737. pk = self.instance.pk if self.instance.pk else None
  738. try:
  739. if self.is_bound and self.data.get('rack') and str(self.data.get('face')):
  740. position_choices = Rack.objects.get(pk=self.data['rack']) \
  741. .get_rack_units(face=self.data.get('face'), exclude=pk)
  742. elif self.initial.get('rack') and str(self.initial.get('face')):
  743. position_choices = Rack.objects.get(pk=self.initial['rack']) \
  744. .get_rack_units(face=self.initial.get('face'), exclude=pk)
  745. else:
  746. position_choices = []
  747. except Rack.DoesNotExist:
  748. position_choices = []
  749. self.fields['position'].choices = [('', '---------')] + [
  750. (p['id'], {
  751. 'label': p['name'],
  752. 'disabled': bool(p['device'] and p['id'] != self.initial.get('position')),
  753. }) for p in position_choices
  754. ]
  755. # Disable rack assignment if this is a child device installed in a parent device
  756. if pk and self.instance.device_type.is_child_device and hasattr(self.instance, 'parent_bay'):
  757. self.fields['site'].disabled = True
  758. self.fields['rack'].disabled = True
  759. self.initial['site'] = self.instance.parent_bay.device.site_id
  760. self.initial['rack'] = self.instance.parent_bay.device.rack_id
  761. class BaseDeviceCSVForm(forms.ModelForm):
  762. device_role = forms.ModelChoiceField(
  763. queryset=DeviceRole.objects.all(),
  764. to_field_name='name',
  765. help_text='Name of assigned role',
  766. error_messages={
  767. 'invalid_choice': 'Invalid device role.',
  768. }
  769. )
  770. tenant = forms.ModelChoiceField(
  771. queryset=Tenant.objects.all(),
  772. required=False,
  773. to_field_name='name',
  774. help_text='Name of assigned tenant',
  775. error_messages={
  776. 'invalid_choice': 'Tenant not found.',
  777. }
  778. )
  779. manufacturer = forms.ModelChoiceField(
  780. queryset=Manufacturer.objects.all(),
  781. to_field_name='name',
  782. help_text='Device type manufacturer',
  783. error_messages={
  784. 'invalid_choice': 'Invalid manufacturer.',
  785. }
  786. )
  787. model_name = forms.CharField(
  788. help_text='Device type model name'
  789. )
  790. platform = forms.ModelChoiceField(
  791. queryset=Platform.objects.all(),
  792. required=False,
  793. to_field_name='name',
  794. help_text='Name of assigned platform',
  795. error_messages={
  796. 'invalid_choice': 'Invalid platform.',
  797. }
  798. )
  799. status = CSVChoiceField(
  800. choices=DEVICE_STATUS_CHOICES,
  801. help_text='Operational status'
  802. )
  803. class Meta:
  804. fields = []
  805. model = Device
  806. help_texts = {
  807. 'name': 'Device name',
  808. }
  809. def clean(self):
  810. super(BaseDeviceCSVForm, self).clean()
  811. manufacturer = self.cleaned_data.get('manufacturer')
  812. model_name = self.cleaned_data.get('model_name')
  813. # Validate device type
  814. if manufacturer and model_name:
  815. try:
  816. self.instance.device_type = DeviceType.objects.get(manufacturer=manufacturer, model=model_name)
  817. except DeviceType.DoesNotExist:
  818. raise forms.ValidationError("Device type {} {} not found".format(manufacturer, model_name))
  819. class DeviceCSVForm(BaseDeviceCSVForm):
  820. site = forms.ModelChoiceField(
  821. queryset=Site.objects.all(),
  822. to_field_name='name',
  823. help_text='Name of parent site',
  824. error_messages={
  825. 'invalid_choice': 'Invalid site name.',
  826. }
  827. )
  828. rack_group = forms.CharField(
  829. required=False,
  830. help_text='Parent rack\'s group (if any)'
  831. )
  832. rack_name = forms.CharField(
  833. required=False,
  834. help_text='Name of parent rack'
  835. )
  836. face = CSVChoiceField(
  837. choices=RACK_FACE_CHOICES,
  838. required=False,
  839. help_text='Mounted rack face'
  840. )
  841. cluster = forms.ModelChoiceField(
  842. queryset=Cluster.objects.all(),
  843. to_field_name='name',
  844. required=False,
  845. help_text='Virtualization cluster',
  846. error_messages={
  847. 'invalid_choice': 'Invalid cluster name.',
  848. }
  849. )
  850. class Meta(BaseDeviceCSVForm.Meta):
  851. fields = [
  852. 'name', 'device_role', 'tenant', 'manufacturer', 'model_name', 'platform', 'serial', 'asset_tag', 'status',
  853. 'site', 'rack_group', 'rack_name', 'position', 'face', 'cluster', 'comments',
  854. ]
  855. def clean(self):
  856. super(DeviceCSVForm, self).clean()
  857. site = self.cleaned_data.get('site')
  858. rack_group = self.cleaned_data.get('rack_group')
  859. rack_name = self.cleaned_data.get('rack_name')
  860. # Validate rack
  861. if site and rack_group and rack_name:
  862. try:
  863. self.instance.rack = Rack.objects.get(site=site, group__name=rack_group, name=rack_name)
  864. except Rack.DoesNotExist:
  865. raise forms.ValidationError("Rack {} not found in site {} group {}".format(rack_name, site, rack_group))
  866. elif site and rack_name:
  867. try:
  868. self.instance.rack = Rack.objects.get(site=site, group__isnull=True, name=rack_name)
  869. except Rack.DoesNotExist:
  870. raise forms.ValidationError("Rack {} not found in site {} (no group)".format(rack_name, site))
  871. class ChildDeviceCSVForm(BaseDeviceCSVForm):
  872. parent = FlexibleModelChoiceField(
  873. queryset=Device.objects.all(),
  874. to_field_name='name',
  875. help_text='Name or ID of parent device',
  876. error_messages={
  877. 'invalid_choice': 'Parent device not found.',
  878. }
  879. )
  880. device_bay_name = forms.CharField(
  881. help_text='Name of device bay',
  882. )
  883. cluster = forms.ModelChoiceField(
  884. queryset=Cluster.objects.all(),
  885. to_field_name='name',
  886. required=False,
  887. help_text='Virtualization cluster',
  888. error_messages={
  889. 'invalid_choice': 'Invalid cluster name.',
  890. }
  891. )
  892. class Meta(BaseDeviceCSVForm.Meta):
  893. fields = [
  894. 'name', 'device_role', 'tenant', 'manufacturer', 'model_name', 'platform', 'serial', 'asset_tag', 'status',
  895. 'parent', 'device_bay_name', 'cluster', 'comments',
  896. ]
  897. def clean(self):
  898. super(ChildDeviceCSVForm, self).clean()
  899. parent = self.cleaned_data.get('parent')
  900. device_bay_name = self.cleaned_data.get('device_bay_name')
  901. # Validate device bay
  902. if parent and device_bay_name:
  903. try:
  904. self.instance.parent_bay = DeviceBay.objects.get(device=parent, name=device_bay_name)
  905. # Inherit site and rack from parent device
  906. self.instance.site = parent.site
  907. self.instance.rack = parent.rack
  908. except DeviceBay.DoesNotExist:
  909. raise forms.ValidationError("Parent device/bay ({} {}) not found".format(parent, device_bay_name))
  910. class DeviceBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldBulkEditForm):
  911. pk = forms.ModelMultipleChoiceField(queryset=Device.objects.all(), widget=forms.MultipleHiddenInput)
  912. device_type = forms.ModelChoiceField(queryset=DeviceType.objects.all(), required=False, label='Type')
  913. device_role = forms.ModelChoiceField(queryset=DeviceRole.objects.all(), required=False, label='Role')
  914. tenant = forms.ModelChoiceField(queryset=Tenant.objects.all(), required=False)
  915. platform = forms.ModelChoiceField(queryset=Platform.objects.all(), required=False)
  916. status = forms.ChoiceField(choices=add_blank_choice(DEVICE_STATUS_CHOICES), required=False, initial='')
  917. serial = forms.CharField(max_length=50, required=False, label='Serial Number')
  918. class Meta:
  919. nullable_fields = ['tenant', 'platform', 'serial']
  920. class DeviceFilterForm(BootstrapMixin, CustomFieldFilterForm):
  921. model = Device
  922. q = forms.CharField(required=False, label='Search')
  923. site = FilterChoiceField(
  924. queryset=Site.objects.annotate(filter_count=Count('devices')),
  925. to_field_name='slug',
  926. )
  927. rack_group_id = FilterChoiceField(
  928. queryset=RackGroup.objects.select_related('site').annotate(filter_count=Count('racks__devices')),
  929. label='Rack group',
  930. )
  931. rack_id = FilterChoiceField(
  932. queryset=Rack.objects.annotate(filter_count=Count('devices')),
  933. label='Rack',
  934. null_label='-- None --',
  935. )
  936. role = FilterChoiceField(
  937. queryset=DeviceRole.objects.annotate(filter_count=Count('devices')),
  938. to_field_name='slug',
  939. )
  940. tenant = FilterChoiceField(
  941. queryset=Tenant.objects.annotate(filter_count=Count('devices')),
  942. to_field_name='slug',
  943. null_label='-- None --',
  944. )
  945. manufacturer_id = FilterChoiceField(queryset=Manufacturer.objects.all(), label='Manufacturer')
  946. device_type_id = FilterChoiceField(
  947. queryset=DeviceType.objects.select_related('manufacturer').order_by('model').annotate(
  948. filter_count=Count('instances'),
  949. ),
  950. label='Model',
  951. )
  952. platform = FilterChoiceField(
  953. queryset=Platform.objects.annotate(filter_count=Count('devices')),
  954. to_field_name='slug',
  955. null_label='-- None --',
  956. )
  957. status = AnnotatedMultipleChoiceField(
  958. choices=DEVICE_STATUS_CHOICES,
  959. annotate=Device.objects.all(),
  960. annotate_field='status',
  961. required=False
  962. )
  963. mac_address = forms.CharField(required=False, label='MAC address')
  964. has_primary_ip = forms.NullBooleanField(
  965. required=False,
  966. label='Has a primary IP',
  967. widget=forms.Select(choices=[
  968. ('', '---------'),
  969. ('True', 'Yes'),
  970. ('False', 'No'),
  971. ])
  972. )
  973. #
  974. # Bulk device component creation
  975. #
  976. class DeviceBulkAddComponentForm(BootstrapMixin, forms.Form):
  977. pk = forms.ModelMultipleChoiceField(queryset=Device.objects.all(), widget=forms.MultipleHiddenInput)
  978. name_pattern = ExpandableNameField(label='Name')
  979. class DeviceBulkAddInterfaceForm(DeviceBulkAddComponentForm):
  980. form_factor = forms.ChoiceField(choices=IFACE_FF_CHOICES)
  981. enabled = forms.BooleanField(required=False, initial=True)
  982. mtu = forms.IntegerField(required=False, min_value=1, max_value=32767, label='MTU')
  983. mgmt_only = forms.BooleanField(required=False, label='OOB Management')
  984. description = forms.CharField(max_length=100, required=False)
  985. #
  986. # Console ports
  987. #
  988. class ConsolePortForm(BootstrapMixin, forms.ModelForm):
  989. tags = TagField(required=False)
  990. class Meta:
  991. model = ConsolePort
  992. fields = ['device', 'name', 'tags']
  993. widgets = {
  994. 'device': forms.HiddenInput(),
  995. }
  996. class ConsolePortCreateForm(ComponentForm):
  997. name_pattern = ExpandableNameField(label='Name')
  998. class ConsoleConnectionCSVForm(forms.ModelForm):
  999. console_server = FlexibleModelChoiceField(
  1000. queryset=Device.objects.filter(device_type__is_console_server=True),
  1001. to_field_name='name',
  1002. help_text='Console server name or ID',
  1003. error_messages={
  1004. 'invalid_choice': 'Console server not found',
  1005. }
  1006. )
  1007. cs_port = forms.CharField(
  1008. help_text='Console server port name'
  1009. )
  1010. device = FlexibleModelChoiceField(
  1011. queryset=Device.objects.all(),
  1012. to_field_name='name',
  1013. help_text='Device name or ID',
  1014. error_messages={
  1015. 'invalid_choice': 'Device not found',
  1016. }
  1017. )
  1018. console_port = forms.CharField(
  1019. help_text='Console port name'
  1020. )
  1021. connection_status = CSVChoiceField(
  1022. choices=CONNECTION_STATUS_CHOICES,
  1023. help_text='Connection status'
  1024. )
  1025. class Meta:
  1026. model = ConsolePort
  1027. fields = ['console_server', 'cs_port', 'device', 'console_port', 'connection_status']
  1028. def clean_console_port(self):
  1029. console_port_name = self.cleaned_data.get('console_port')
  1030. if not self.cleaned_data.get('device') or not console_port_name:
  1031. return None
  1032. try:
  1033. # Retrieve console port by name
  1034. consoleport = ConsolePort.objects.get(
  1035. device=self.cleaned_data['device'], name=console_port_name
  1036. )
  1037. # Check if the console port is already connected
  1038. if consoleport.cs_port is not None:
  1039. raise forms.ValidationError("{} {} is already connected".format(
  1040. self.cleaned_data['device'], console_port_name
  1041. ))
  1042. except ConsolePort.DoesNotExist:
  1043. raise forms.ValidationError("Invalid console port ({} {})".format(
  1044. self.cleaned_data['device'], console_port_name
  1045. ))
  1046. self.instance = consoleport
  1047. return consoleport
  1048. def clean_cs_port(self):
  1049. cs_port_name = self.cleaned_data.get('cs_port')
  1050. if not self.cleaned_data.get('console_server') or not cs_port_name:
  1051. return None
  1052. try:
  1053. # Retrieve console server port by name
  1054. cs_port = ConsoleServerPort.objects.get(
  1055. device=self.cleaned_data['console_server'], name=cs_port_name
  1056. )
  1057. # Check if the console server port is already connected
  1058. if ConsolePort.objects.filter(cs_port=cs_port).count():
  1059. raise forms.ValidationError("{} {} is already connected".format(
  1060. self.cleaned_data['console_server'], cs_port_name
  1061. ))
  1062. except ConsoleServerPort.DoesNotExist:
  1063. raise forms.ValidationError("Invalid console server port ({} {})".format(
  1064. self.cleaned_data['console_server'], cs_port_name
  1065. ))
  1066. return cs_port
  1067. class ConsolePortConnectionForm(BootstrapMixin, ChainedFieldsMixin, forms.ModelForm):
  1068. site = forms.ModelChoiceField(
  1069. queryset=Site.objects.all(),
  1070. required=False,
  1071. widget=forms.Select(
  1072. attrs={'filter-for': 'rack'}
  1073. )
  1074. )
  1075. rack = ChainedModelChoiceField(
  1076. queryset=Rack.objects.all(),
  1077. chains=(
  1078. ('site', 'site'),
  1079. ),
  1080. label='Rack',
  1081. required=False,
  1082. widget=APISelect(
  1083. api_url='/api/dcim/racks/?site_id={{site}}',
  1084. attrs={'filter-for': 'console_server', 'nullable': 'true'}
  1085. )
  1086. )
  1087. console_server = ChainedModelChoiceField(
  1088. queryset=Device.objects.filter(device_type__is_console_server=True),
  1089. chains=(
  1090. ('site', 'site'),
  1091. ('rack', 'rack'),
  1092. ),
  1093. label='Console Server',
  1094. required=False,
  1095. widget=APISelect(
  1096. api_url='/api/dcim/devices/?site_id={{site}}&rack_id={{rack}}&is_console_server=True',
  1097. display_field='display_name',
  1098. attrs={'filter-for': 'cs_port'}
  1099. )
  1100. )
  1101. livesearch = forms.CharField(
  1102. required=False,
  1103. label='Console Server',
  1104. widget=Livesearch(
  1105. query_key='q',
  1106. query_url='dcim-api:device-list',
  1107. field_to_update='console_server',
  1108. )
  1109. )
  1110. cs_port = ChainedModelChoiceField(
  1111. queryset=ConsoleServerPort.objects.all(),
  1112. chains=(
  1113. ('device', 'console_server'),
  1114. ),
  1115. label='Port',
  1116. widget=APISelect(
  1117. api_url='/api/dcim/console-server-ports/?device_id={{console_server}}',
  1118. disabled_indicator='connected_console',
  1119. )
  1120. )
  1121. class Meta:
  1122. model = ConsolePort
  1123. fields = ['site', 'rack', 'console_server', 'livesearch', 'cs_port', 'connection_status']
  1124. labels = {
  1125. 'cs_port': 'Port',
  1126. 'connection_status': 'Status',
  1127. }
  1128. def __init__(self, *args, **kwargs):
  1129. super(ConsolePortConnectionForm, self).__init__(*args, **kwargs)
  1130. if not self.instance.pk:
  1131. raise RuntimeError("ConsolePortConnectionForm must be initialized with an existing ConsolePort instance.")
  1132. #
  1133. # Console server ports
  1134. #
  1135. class ConsoleServerPortForm(BootstrapMixin, forms.ModelForm):
  1136. tags = TagField(required=False)
  1137. class Meta:
  1138. model = ConsoleServerPort
  1139. fields = ['device', 'name', 'tags']
  1140. widgets = {
  1141. 'device': forms.HiddenInput(),
  1142. }
  1143. class ConsoleServerPortCreateForm(ComponentForm):
  1144. name_pattern = ExpandableNameField(label='Name')
  1145. class ConsoleServerPortConnectionForm(BootstrapMixin, ChainedFieldsMixin, forms.Form):
  1146. site = forms.ModelChoiceField(
  1147. queryset=Site.objects.all(),
  1148. required=False,
  1149. widget=forms.Select(
  1150. attrs={'filter-for': 'rack'}
  1151. )
  1152. )
  1153. rack = ChainedModelChoiceField(
  1154. queryset=Rack.objects.all(),
  1155. chains=(
  1156. ('site', 'site'),
  1157. ),
  1158. label='Rack',
  1159. required=False,
  1160. widget=APISelect(
  1161. api_url='/api/dcim/racks/?site_id={{site}}',
  1162. attrs={'filter-for': 'device', 'nullable': 'true'}
  1163. )
  1164. )
  1165. device = ChainedModelChoiceField(
  1166. queryset=Device.objects.all(),
  1167. chains=(
  1168. ('site', 'site'),
  1169. ('rack', 'rack'),
  1170. ),
  1171. label='Device',
  1172. required=False,
  1173. widget=APISelect(
  1174. api_url='/api/dcim/devices/?site_id={{site}}&rack_id={{rack}}',
  1175. display_field='display_name',
  1176. attrs={'filter-for': 'port'}
  1177. )
  1178. )
  1179. livesearch = forms.CharField(
  1180. required=False,
  1181. label='Device',
  1182. widget=Livesearch(
  1183. query_key='q',
  1184. query_url='dcim-api:device-list',
  1185. field_to_update='device'
  1186. )
  1187. )
  1188. port = ChainedModelChoiceField(
  1189. queryset=ConsolePort.objects.all(),
  1190. chains=(
  1191. ('device', 'device'),
  1192. ),
  1193. label='Port',
  1194. widget=APISelect(
  1195. api_url='/api/dcim/console-ports/?device_id={{device}}',
  1196. disabled_indicator='cs_port'
  1197. )
  1198. )
  1199. connection_status = forms.BooleanField(
  1200. required=False,
  1201. initial=CONNECTION_STATUS_CONNECTED,
  1202. label='Status',
  1203. widget=forms.Select(
  1204. choices=CONNECTION_STATUS_CHOICES
  1205. )
  1206. )
  1207. class Meta:
  1208. fields = ['site', 'rack', 'device', 'livesearch', 'port', 'connection_status']
  1209. labels = {
  1210. 'connection_status': 'Status',
  1211. }
  1212. class ConsoleServerPortBulkRenameForm(BulkRenameForm):
  1213. pk = forms.ModelMultipleChoiceField(queryset=ConsoleServerPort.objects.all(), widget=forms.MultipleHiddenInput)
  1214. class ConsoleServerPortBulkDisconnectForm(ConfirmationForm):
  1215. pk = forms.ModelMultipleChoiceField(queryset=ConsoleServerPort.objects.all(), widget=forms.MultipleHiddenInput)
  1216. #
  1217. # Power ports
  1218. #
  1219. class PowerPortForm(BootstrapMixin, forms.ModelForm):
  1220. tags = TagField(required=False)
  1221. class Meta:
  1222. model = PowerPort
  1223. fields = ['device', 'name', 'tags']
  1224. widgets = {
  1225. 'device': forms.HiddenInput(),
  1226. }
  1227. class PowerPortCreateForm(ComponentForm):
  1228. name_pattern = ExpandableNameField(label='Name')
  1229. class PowerConnectionCSVForm(forms.ModelForm):
  1230. pdu = FlexibleModelChoiceField(
  1231. queryset=Device.objects.filter(device_type__is_pdu=True),
  1232. to_field_name='name',
  1233. help_text='PDU name or ID',
  1234. error_messages={
  1235. 'invalid_choice': 'PDU not found.',
  1236. }
  1237. )
  1238. power_outlet = forms.CharField(
  1239. help_text='Power outlet name'
  1240. )
  1241. device = FlexibleModelChoiceField(
  1242. queryset=Device.objects.all(),
  1243. to_field_name='name',
  1244. help_text='Device name or ID',
  1245. error_messages={
  1246. 'invalid_choice': 'Device not found',
  1247. }
  1248. )
  1249. power_port = forms.CharField(
  1250. help_text='Power port name'
  1251. )
  1252. connection_status = CSVChoiceField(
  1253. choices=CONNECTION_STATUS_CHOICES,
  1254. help_text='Connection status'
  1255. )
  1256. class Meta:
  1257. model = PowerPort
  1258. fields = ['pdu', 'power_outlet', 'device', 'power_port', 'connection_status']
  1259. def clean_power_port(self):
  1260. power_port_name = self.cleaned_data.get('power_port')
  1261. if not self.cleaned_data.get('device') or not power_port_name:
  1262. return None
  1263. try:
  1264. # Retrieve power port by name
  1265. powerport = PowerPort.objects.get(
  1266. device=self.cleaned_data['device'], name=power_port_name
  1267. )
  1268. # Check if the power port is already connected
  1269. if powerport.power_outlet is not None:
  1270. raise forms.ValidationError("{} {} is already connected".format(
  1271. self.cleaned_data['device'], power_port_name
  1272. ))
  1273. except PowerPort.DoesNotExist:
  1274. raise forms.ValidationError("Invalid power port ({} {})".format(
  1275. self.cleaned_data['device'], power_port_name
  1276. ))
  1277. self.instance = powerport
  1278. return powerport
  1279. def clean_power_outlet(self):
  1280. power_outlet_name = self.cleaned_data.get('power_outlet')
  1281. if not self.cleaned_data.get('pdu') or not power_outlet_name:
  1282. return None
  1283. try:
  1284. # Retrieve power outlet by name
  1285. power_outlet = PowerOutlet.objects.get(
  1286. device=self.cleaned_data['pdu'], name=power_outlet_name
  1287. )
  1288. # Check if the power outlet is already connected
  1289. if PowerPort.objects.filter(power_outlet=power_outlet).count():
  1290. raise forms.ValidationError("{} {} is already connected".format(
  1291. self.cleaned_data['pdu'], power_outlet_name
  1292. ))
  1293. except PowerOutlet.DoesNotExist:
  1294. raise forms.ValidationError("Invalid power outlet ({} {})".format(
  1295. self.cleaned_data['pdu'], power_outlet_name
  1296. ))
  1297. return power_outlet
  1298. class PowerPortConnectionForm(BootstrapMixin, ChainedFieldsMixin, forms.ModelForm):
  1299. site = forms.ModelChoiceField(
  1300. queryset=Site.objects.all(),
  1301. required=False,
  1302. widget=forms.Select(
  1303. attrs={'filter-for': 'rack'}
  1304. )
  1305. )
  1306. rack = ChainedModelChoiceField(
  1307. queryset=Rack.objects.all(),
  1308. chains=(
  1309. ('site', 'site'),
  1310. ),
  1311. label='Rack',
  1312. required=False,
  1313. widget=APISelect(
  1314. api_url='/api/dcim/racks/?site_id={{site}}',
  1315. attrs={'filter-for': 'pdu', 'nullable': 'true'}
  1316. )
  1317. )
  1318. pdu = ChainedModelChoiceField(
  1319. queryset=Device.objects.all(),
  1320. chains=(
  1321. ('site', 'site'),
  1322. ('rack', 'rack'),
  1323. ),
  1324. label='PDU',
  1325. required=False,
  1326. widget=APISelect(
  1327. api_url='/api/dcim/devices/?site_id={{site}}&rack_id={{rack}}&is_pdu=True',
  1328. display_field='display_name',
  1329. attrs={'filter-for': 'power_outlet'}
  1330. )
  1331. )
  1332. livesearch = forms.CharField(
  1333. required=False,
  1334. label='PDU',
  1335. widget=Livesearch(
  1336. query_key='q',
  1337. query_url='dcim-api:device-list',
  1338. field_to_update='pdu'
  1339. )
  1340. )
  1341. power_outlet = ChainedModelChoiceField(
  1342. queryset=PowerOutlet.objects.all(),
  1343. chains=(
  1344. ('device', 'pdu'),
  1345. ),
  1346. label='Outlet',
  1347. widget=APISelect(
  1348. api_url='/api/dcim/power-outlets/?device_id={{pdu}}',
  1349. disabled_indicator='connected_port'
  1350. )
  1351. )
  1352. class Meta:
  1353. model = PowerPort
  1354. fields = ['site', 'rack', 'pdu', 'livesearch', 'power_outlet', 'connection_status']
  1355. labels = {
  1356. 'power_outlet': 'Outlet',
  1357. 'connection_status': 'Status',
  1358. }
  1359. def __init__(self, *args, **kwargs):
  1360. super(PowerPortConnectionForm, self).__init__(*args, **kwargs)
  1361. if not self.instance.pk:
  1362. raise RuntimeError("PowerPortConnectionForm must be initialized with an existing PowerPort instance.")
  1363. #
  1364. # Power outlets
  1365. #
  1366. class PowerOutletForm(BootstrapMixin, forms.ModelForm):
  1367. tags = TagField(required=False)
  1368. class Meta:
  1369. model = PowerOutlet
  1370. fields = ['device', 'name', 'tags']
  1371. widgets = {
  1372. 'device': forms.HiddenInput(),
  1373. }
  1374. class PowerOutletCreateForm(ComponentForm):
  1375. name_pattern = ExpandableNameField(label='Name')
  1376. class PowerOutletConnectionForm(BootstrapMixin, ChainedFieldsMixin, forms.Form):
  1377. site = forms.ModelChoiceField(
  1378. queryset=Site.objects.all(),
  1379. required=False,
  1380. widget=forms.Select(
  1381. attrs={'filter-for': 'rack'}
  1382. )
  1383. )
  1384. rack = ChainedModelChoiceField(
  1385. queryset=Rack.objects.all(),
  1386. chains=(
  1387. ('site', 'site'),
  1388. ),
  1389. label='Rack',
  1390. required=False,
  1391. widget=APISelect(
  1392. api_url='/api/dcim/racks/?site_id={{site}}',
  1393. attrs={'filter-for': 'device', 'nullable': 'true'}
  1394. )
  1395. )
  1396. device = ChainedModelChoiceField(
  1397. queryset=Device.objects.all(),
  1398. chains=(
  1399. ('site', 'site'),
  1400. ('rack', 'rack'),
  1401. ),
  1402. label='Device',
  1403. required=False,
  1404. widget=APISelect(
  1405. api_url='/api/dcim/devices/?site_id={{site}}&rack_id={{rack}}',
  1406. display_field='display_name',
  1407. attrs={'filter-for': 'port'}
  1408. )
  1409. )
  1410. livesearch = forms.CharField(
  1411. required=False,
  1412. label='Device',
  1413. widget=Livesearch(
  1414. query_key='q',
  1415. query_url='dcim-api:device-list',
  1416. field_to_update='device'
  1417. )
  1418. )
  1419. port = ChainedModelChoiceField(
  1420. queryset=PowerPort.objects.all(),
  1421. chains=(
  1422. ('device', 'device'),
  1423. ),
  1424. label='Port',
  1425. widget=APISelect(
  1426. api_url='/api/dcim/power-ports/?device_id={{device}}',
  1427. disabled_indicator='power_outlet'
  1428. )
  1429. )
  1430. connection_status = forms.BooleanField(
  1431. required=False,
  1432. initial=CONNECTION_STATUS_CONNECTED,
  1433. label='Status',
  1434. widget=forms.Select(
  1435. choices=CONNECTION_STATUS_CHOICES
  1436. )
  1437. )
  1438. class Meta:
  1439. fields = ['site', 'rack', 'device', 'livesearch', 'port', 'connection_status']
  1440. labels = {
  1441. 'connection_status': 'Status',
  1442. }
  1443. class PowerOutletBulkRenameForm(BulkRenameForm):
  1444. pk = forms.ModelMultipleChoiceField(queryset=PowerOutlet.objects.all(), widget=forms.MultipleHiddenInput)
  1445. class PowerOutletBulkDisconnectForm(ConfirmationForm):
  1446. pk = forms.ModelMultipleChoiceField(queryset=PowerOutlet.objects.all(), widget=forms.MultipleHiddenInput)
  1447. #
  1448. # Interfaces
  1449. #
  1450. class InterfaceForm(BootstrapMixin, forms.ModelForm):
  1451. tags = TagField(required=False)
  1452. class Meta:
  1453. model = Interface
  1454. fields = [
  1455. 'device', 'name', 'form_factor', 'enabled', 'lag', 'mac_address', 'mtu', 'mgmt_only', 'description',
  1456. 'mode', 'untagged_vlan', 'tagged_vlans', 'tags',
  1457. ]
  1458. widgets = {
  1459. 'device': forms.HiddenInput(),
  1460. }
  1461. labels = {
  1462. 'mode': '802.1Q Mode',
  1463. }
  1464. help_texts = {
  1465. 'mode': INTERFACE_MODE_HELP_TEXT,
  1466. }
  1467. def __init__(self, *args, **kwargs):
  1468. super(InterfaceForm, self).__init__(*args, **kwargs)
  1469. # Limit LAG choices to interfaces belonging to this device (or VC master)
  1470. if self.is_bound:
  1471. device = Device.objects.get(pk=self.data['device'])
  1472. self.fields['lag'].queryset = Interface.objects.order_naturally().filter(
  1473. device__in=[device, device.get_vc_master()], form_factor=IFACE_FF_LAG
  1474. )
  1475. else:
  1476. device = self.instance.device
  1477. self.fields['lag'].queryset = Interface.objects.order_naturally().filter(
  1478. device__in=[self.instance.device, self.instance.device.get_vc_master()], form_factor=IFACE_FF_LAG
  1479. )
  1480. def clean(self):
  1481. super(InterfaceForm, self).clean()
  1482. # Validate VLAN assignments
  1483. tagged_vlans = self.cleaned_data['tagged_vlans']
  1484. # Untagged interfaces cannot be assigned tagged VLANs
  1485. if self.cleaned_data['mode'] == IFACE_MODE_ACCESS and tagged_vlans:
  1486. raise forms.ValidationError({
  1487. 'mode': "An access interface cannot have tagged VLANs assigned."
  1488. })
  1489. # Remove all tagged VLAN assignments from "tagged all" interfaces
  1490. elif self.cleaned_data['mode'] == IFACE_MODE_TAGGED_ALL:
  1491. self.cleaned_data['tagged_vlans'] = []
  1492. class InterfaceAssignVLANsForm(BootstrapMixin, forms.ModelForm):
  1493. vlans = forms.MultipleChoiceField(
  1494. choices=[],
  1495. label='VLANs',
  1496. widget=forms.SelectMultiple(attrs={'size': 20})
  1497. )
  1498. tagged = forms.BooleanField(
  1499. required=False,
  1500. initial=True
  1501. )
  1502. class Meta:
  1503. model = Interface
  1504. fields = []
  1505. def __init__(self, *args, **kwargs):
  1506. super(InterfaceAssignVLANsForm, self).__init__(*args, **kwargs)
  1507. if self.instance.mode == IFACE_MODE_ACCESS:
  1508. self.initial['tagged'] = False
  1509. # Find all VLANs already assigned to the interface for exclusion from the list
  1510. assigned_vlans = [v.pk for v in self.instance.tagged_vlans.all()]
  1511. if self.instance.untagged_vlan is not None:
  1512. assigned_vlans.append(self.instance.untagged_vlan.pk)
  1513. # Compile VLAN choices
  1514. vlan_choices = []
  1515. # Add non-grouped global VLANs
  1516. global_vlans = VLAN.objects.filter(site=None, group=None).exclude(pk__in=assigned_vlans)
  1517. vlan_choices.append((
  1518. 'Global', [(vlan.pk, vlan) for vlan in global_vlans])
  1519. )
  1520. # Add grouped global VLANs
  1521. for group in VLANGroup.objects.filter(site=None):
  1522. global_group_vlans = VLAN.objects.filter(group=group).exclude(pk__in=assigned_vlans)
  1523. vlan_choices.append(
  1524. (group.name, [(vlan.pk, vlan) for vlan in global_group_vlans])
  1525. )
  1526. site = getattr(self.instance.parent, 'site', None)
  1527. if site is not None:
  1528. # Add non-grouped site VLANs
  1529. site_vlans = VLAN.objects.filter(site=site, group=None).exclude(pk__in=assigned_vlans)
  1530. vlan_choices.append((site.name, [(vlan.pk, vlan) for vlan in site_vlans]))
  1531. # Add grouped site VLANs
  1532. for group in VLANGroup.objects.filter(site=site):
  1533. site_group_vlans = VLAN.objects.filter(group=group).exclude(pk__in=assigned_vlans)
  1534. vlan_choices.append((
  1535. '{} / {}'.format(group.site.name, group.name),
  1536. [(vlan.pk, vlan) for vlan in site_group_vlans]
  1537. ))
  1538. self.fields['vlans'].choices = vlan_choices
  1539. def clean(self):
  1540. super(InterfaceAssignVLANsForm, self).clean()
  1541. # Only untagged VLANs permitted on an access interface
  1542. if self.instance.mode == IFACE_MODE_ACCESS and len(self.cleaned_data['vlans']) > 1:
  1543. raise forms.ValidationError("Only one VLAN may be assigned to an access interface.")
  1544. # 'tagged' is required if more than one VLAN is selected
  1545. if not self.cleaned_data['tagged'] and len(self.cleaned_data['vlans']) > 1:
  1546. raise forms.ValidationError("Only one untagged VLAN may be selected.")
  1547. def save(self, *args, **kwargs):
  1548. if self.cleaned_data['tagged']:
  1549. for vlan in self.cleaned_data['vlans']:
  1550. self.instance.tagged_vlans.add(vlan)
  1551. else:
  1552. self.instance.untagged_vlan_id = self.cleaned_data['vlans'][0]
  1553. return super(InterfaceAssignVLANsForm, self).save(*args, **kwargs)
  1554. class InterfaceCreateForm(ComponentForm, forms.Form):
  1555. name_pattern = ExpandableNameField(label='Name')
  1556. form_factor = forms.ChoiceField(choices=IFACE_FF_CHOICES)
  1557. enabled = forms.BooleanField(required=False)
  1558. lag = forms.ModelChoiceField(queryset=Interface.objects.all(), required=False, label='Parent LAG')
  1559. mtu = forms.IntegerField(required=False, min_value=1, max_value=32767, label='MTU')
  1560. mac_address = MACAddressFormField(required=False, label='MAC Address')
  1561. mgmt_only = forms.BooleanField(
  1562. required=False,
  1563. label='OOB Management',
  1564. help_text='This interface is used only for out-of-band management'
  1565. )
  1566. description = forms.CharField(max_length=100, required=False)
  1567. mode = forms.ChoiceField(choices=add_blank_choice(IFACE_MODE_CHOICES), required=False)
  1568. def __init__(self, *args, **kwargs):
  1569. # Set interfaces enabled by default
  1570. kwargs['initial'] = kwargs.get('initial', {}).copy()
  1571. kwargs['initial'].update({'enabled': True})
  1572. super(InterfaceCreateForm, self).__init__(*args, **kwargs)
  1573. # Limit LAG choices to interfaces belonging to this device (or its VC master)
  1574. if self.parent is not None:
  1575. self.fields['lag'].queryset = Interface.objects.order_naturally().filter(
  1576. device__in=[self.parent, self.parent.get_vc_master()], form_factor=IFACE_FF_LAG
  1577. )
  1578. else:
  1579. self.fields['lag'].queryset = Interface.objects.none()
  1580. class InterfaceBulkEditForm(BootstrapMixin, AddRemoveTagsForm, BulkEditForm):
  1581. pk = forms.ModelMultipleChoiceField(queryset=Interface.objects.all(), widget=forms.MultipleHiddenInput)
  1582. form_factor = forms.ChoiceField(choices=add_blank_choice(IFACE_FF_CHOICES), required=False)
  1583. enabled = forms.NullBooleanField(required=False, widget=BulkEditNullBooleanSelect)
  1584. lag = forms.ModelChoiceField(queryset=Interface.objects.all(), required=False, label='Parent LAG')
  1585. mtu = forms.IntegerField(required=False, min_value=1, max_value=32767, label='MTU')
  1586. mgmt_only = forms.NullBooleanField(required=False, widget=BulkEditNullBooleanSelect, label='Management only')
  1587. description = forms.CharField(max_length=100, required=False)
  1588. mode = forms.ChoiceField(choices=add_blank_choice(IFACE_MODE_CHOICES), required=False)
  1589. class Meta:
  1590. nullable_fields = ['lag', 'mtu', 'description', 'mode']
  1591. def __init__(self, *args, **kwargs):
  1592. super(InterfaceBulkEditForm, self).__init__(*args, **kwargs)
  1593. # Limit LAG choices to interfaces which belong to the parent device (or VC master)
  1594. device = self.parent_obj
  1595. if device is not None:
  1596. interface_ordering = device.device_type.interface_ordering
  1597. self.fields['lag'].queryset = Interface.objects.order_naturally(method=interface_ordering).filter(
  1598. device__in=[device, device.get_vc_master()], form_factor=IFACE_FF_LAG
  1599. )
  1600. else:
  1601. self.fields['lag'].choices = []
  1602. class InterfaceBulkRenameForm(BulkRenameForm):
  1603. pk = forms.ModelMultipleChoiceField(queryset=Interface.objects.all(), widget=forms.MultipleHiddenInput)
  1604. class InterfaceBulkDisconnectForm(ConfirmationForm):
  1605. pk = forms.ModelMultipleChoiceField(queryset=Interface.objects.all(), widget=forms.MultipleHiddenInput)
  1606. #
  1607. # Interface connections
  1608. #
  1609. class InterfaceConnectionForm(BootstrapMixin, ChainedFieldsMixin, forms.ModelForm):
  1610. interface_a = forms.ChoiceField(
  1611. choices=[],
  1612. widget=SelectWithDisabled,
  1613. label='Interface'
  1614. )
  1615. site_b = forms.ModelChoiceField(
  1616. queryset=Site.objects.all(),
  1617. label='Site',
  1618. required=False,
  1619. widget=forms.Select(
  1620. attrs={'filter-for': 'rack_b'}
  1621. )
  1622. )
  1623. rack_b = ChainedModelChoiceField(
  1624. queryset=Rack.objects.all(),
  1625. chains=(
  1626. ('site', 'site_b'),
  1627. ),
  1628. label='Rack',
  1629. required=False,
  1630. widget=APISelect(
  1631. api_url='/api/dcim/racks/?site_id={{site_b}}',
  1632. attrs={'filter-for': 'device_b', 'nullable': 'true'}
  1633. )
  1634. )
  1635. device_b = ChainedModelChoiceField(
  1636. queryset=Device.objects.all(),
  1637. chains=(
  1638. ('site', 'site_b'),
  1639. ('rack', 'rack_b'),
  1640. ),
  1641. label='Device',
  1642. required=False,
  1643. widget=APISelect(
  1644. api_url='/api/dcim/devices/?site_id={{site_b}}&rack_id={{rack_b}}',
  1645. display_field='display_name',
  1646. attrs={'filter-for': 'interface_b'}
  1647. )
  1648. )
  1649. livesearch = forms.CharField(
  1650. required=False,
  1651. label='Device',
  1652. widget=Livesearch(
  1653. query_key='q',
  1654. query_url='dcim-api:device-list',
  1655. field_to_update='device_b'
  1656. )
  1657. )
  1658. interface_b = ChainedModelChoiceField(
  1659. queryset=Interface.objects.connectable().select_related(
  1660. 'circuit_termination', 'connected_as_a', 'connected_as_b'
  1661. ),
  1662. chains=(
  1663. ('device', 'device_b'),
  1664. ),
  1665. label='Interface',
  1666. widget=APISelect(
  1667. api_url='/api/dcim/interfaces/?device_id={{device_b}}&type=physical',
  1668. disabled_indicator='is_connected'
  1669. )
  1670. )
  1671. class Meta:
  1672. model = InterfaceConnection
  1673. fields = ['interface_a', 'site_b', 'rack_b', 'device_b', 'interface_b', 'livesearch', 'connection_status']
  1674. def __init__(self, device_a, *args, **kwargs):
  1675. super(InterfaceConnectionForm, self).__init__(*args, **kwargs)
  1676. # Initialize interface A choices
  1677. device_a_interfaces = device_a.vc_interfaces.connectable().order_naturally().select_related(
  1678. 'circuit_termination', 'connected_as_a', 'connected_as_b'
  1679. )
  1680. self.fields['interface_a'].choices = [
  1681. (iface.id, {'label': iface.name, 'disabled': iface.is_connected}) for iface in device_a_interfaces
  1682. ]
  1683. # Mark connected interfaces as disabled
  1684. if self.data.get('device_b'):
  1685. self.fields['interface_b'].choices = []
  1686. for iface in self.fields['interface_b'].queryset:
  1687. self.fields['interface_b'].choices.append(
  1688. (iface.id, {'label': iface.name, 'disabled': iface.is_connected})
  1689. )
  1690. class InterfaceConnectionCSVForm(forms.ModelForm):
  1691. device_a = FlexibleModelChoiceField(
  1692. queryset=Device.objects.all(),
  1693. to_field_name='name',
  1694. help_text='Name or ID of device A',
  1695. error_messages={'invalid_choice': 'Device A not found.'}
  1696. )
  1697. interface_a = forms.CharField(
  1698. help_text='Name of interface A'
  1699. )
  1700. device_b = FlexibleModelChoiceField(
  1701. queryset=Device.objects.all(),
  1702. to_field_name='name',
  1703. help_text='Name or ID of device B',
  1704. error_messages={'invalid_choice': 'Device B not found.'}
  1705. )
  1706. interface_b = forms.CharField(
  1707. help_text='Name of interface B'
  1708. )
  1709. connection_status = CSVChoiceField(
  1710. choices=CONNECTION_STATUS_CHOICES,
  1711. help_text='Connection status'
  1712. )
  1713. class Meta:
  1714. model = InterfaceConnection
  1715. fields = InterfaceConnection.csv_headers
  1716. def clean_interface_a(self):
  1717. interface_name = self.cleaned_data.get('interface_a')
  1718. if not interface_name:
  1719. return None
  1720. try:
  1721. # Retrieve interface by name
  1722. interface = Interface.objects.get(
  1723. device=self.cleaned_data['device_a'], name=interface_name
  1724. )
  1725. # Check for an existing connection to this interface
  1726. if InterfaceConnection.objects.filter(Q(interface_a=interface) | Q(interface_b=interface)).count():
  1727. raise forms.ValidationError("{} {} is already connected".format(
  1728. self.cleaned_data['device_a'], interface_name
  1729. ))
  1730. except Interface.DoesNotExist:
  1731. raise forms.ValidationError("Invalid interface ({} {})".format(
  1732. self.cleaned_data['device_a'], interface_name
  1733. ))
  1734. return interface
  1735. def clean_interface_b(self):
  1736. interface_name = self.cleaned_data.get('interface_b')
  1737. if not interface_name:
  1738. return None
  1739. try:
  1740. # Retrieve interface by name
  1741. interface = Interface.objects.get(
  1742. device=self.cleaned_data['device_b'], name=interface_name
  1743. )
  1744. # Check for an existing connection to this interface
  1745. if InterfaceConnection.objects.filter(Q(interface_a=interface) | Q(interface_b=interface)).count():
  1746. raise forms.ValidationError("{} {} is already connected".format(
  1747. self.cleaned_data['device_b'], interface_name
  1748. ))
  1749. except Interface.DoesNotExist:
  1750. raise forms.ValidationError("Invalid interface ({} {})".format(
  1751. self.cleaned_data['device_b'], interface_name
  1752. ))
  1753. return interface
  1754. #
  1755. # Device bays
  1756. #
  1757. class DeviceBayForm(BootstrapMixin, forms.ModelForm):
  1758. tags = TagField(required=False)
  1759. class Meta:
  1760. model = DeviceBay
  1761. fields = ['device', 'name', 'tags']
  1762. widgets = {
  1763. 'device': forms.HiddenInput(),
  1764. }
  1765. class DeviceBayCreateForm(ComponentForm):
  1766. name_pattern = ExpandableNameField(label='Name')
  1767. class PopulateDeviceBayForm(BootstrapMixin, forms.Form):
  1768. installed_device = forms.ModelChoiceField(
  1769. queryset=Device.objects.all(),
  1770. label='Child Device',
  1771. help_text="Child devices must first be created and assigned to the site/rack of the parent device."
  1772. )
  1773. def __init__(self, device_bay, *args, **kwargs):
  1774. super(PopulateDeviceBayForm, self).__init__(*args, **kwargs)
  1775. self.fields['installed_device'].queryset = Device.objects.filter(
  1776. site=device_bay.device.site,
  1777. rack=device_bay.device.rack,
  1778. parent_bay__isnull=True,
  1779. device_type__u_height=0,
  1780. device_type__subdevice_role=SUBDEVICE_ROLE_CHILD
  1781. ).exclude(pk=device_bay.device.pk)
  1782. class DeviceBayBulkRenameForm(BulkRenameForm):
  1783. pk = forms.ModelMultipleChoiceField(queryset=DeviceBay.objects.all(), widget=forms.MultipleHiddenInput)
  1784. #
  1785. # Connections
  1786. #
  1787. class ConsoleConnectionFilterForm(BootstrapMixin, forms.Form):
  1788. site = forms.ModelChoiceField(required=False, queryset=Site.objects.all(), to_field_name='slug')
  1789. device = forms.CharField(required=False, label='Device name')
  1790. class PowerConnectionFilterForm(BootstrapMixin, forms.Form):
  1791. site = forms.ModelChoiceField(required=False, queryset=Site.objects.all(), to_field_name='slug')
  1792. device = forms.CharField(required=False, label='Device name')
  1793. class InterfaceConnectionFilterForm(BootstrapMixin, forms.Form):
  1794. site = forms.ModelChoiceField(required=False, queryset=Site.objects.all(), to_field_name='slug')
  1795. device = forms.CharField(required=False, label='Device name')
  1796. #
  1797. # Inventory items
  1798. #
  1799. class InventoryItemForm(BootstrapMixin, forms.ModelForm):
  1800. tags = TagField(required=False)
  1801. class Meta:
  1802. model = InventoryItem
  1803. fields = ['name', 'manufacturer', 'part_id', 'serial', 'asset_tag', 'description', 'tags']
  1804. class InventoryItemCSVForm(forms.ModelForm):
  1805. device = FlexibleModelChoiceField(
  1806. queryset=Device.objects.all(),
  1807. to_field_name='name',
  1808. help_text='Device name or ID',
  1809. error_messages={
  1810. 'invalid_choice': 'Device not found.',
  1811. }
  1812. )
  1813. manufacturer = forms.ModelChoiceField(
  1814. queryset=Manufacturer.objects.all(),
  1815. to_field_name='name',
  1816. required=False,
  1817. help_text='Manufacturer name',
  1818. error_messages={
  1819. 'invalid_choice': 'Invalid manufacturer.',
  1820. }
  1821. )
  1822. class Meta:
  1823. model = InventoryItem
  1824. fields = InventoryItem.csv_headers
  1825. class InventoryItemBulkEditForm(BootstrapMixin, BulkEditForm):
  1826. pk = forms.ModelMultipleChoiceField(queryset=InventoryItem.objects.all(), widget=forms.MultipleHiddenInput)
  1827. manufacturer = forms.ModelChoiceField(queryset=Manufacturer.objects.all(), required=False)
  1828. part_id = forms.CharField(max_length=50, required=False, label='Part ID')
  1829. description = forms.CharField(max_length=100, required=False)
  1830. class Meta:
  1831. nullable_fields = ['manufacturer', 'part_id', 'description']
  1832. class InventoryItemFilterForm(BootstrapMixin, forms.Form):
  1833. model = InventoryItem
  1834. q = forms.CharField(required=False, label='Search')
  1835. manufacturer = FilterChoiceField(
  1836. queryset=Manufacturer.objects.annotate(filter_count=Count('inventory_items')),
  1837. to_field_name='slug',
  1838. null_label='-- None --'
  1839. )
  1840. #
  1841. # Virtual chassis
  1842. #
  1843. class DeviceSelectionForm(forms.Form):
  1844. pk = forms.ModelMultipleChoiceField(queryset=Device.objects.all(), widget=forms.MultipleHiddenInput)
  1845. class VirtualChassisForm(BootstrapMixin, forms.ModelForm):
  1846. tags = TagField(required=False)
  1847. class Meta:
  1848. model = VirtualChassis
  1849. fields = ['master', 'domain', 'tags']
  1850. widgets = {
  1851. 'master': SelectWithPK,
  1852. }
  1853. class BaseVCMemberFormSet(forms.BaseModelFormSet):
  1854. def clean(self):
  1855. super(BaseVCMemberFormSet, self).clean()
  1856. # Check for duplicate VC position values
  1857. vc_position_list = []
  1858. for form in self.forms:
  1859. vc_position = form.cleaned_data.get('vc_position')
  1860. if vc_position:
  1861. if vc_position in vc_position_list:
  1862. error_msg = 'A virtual chassis member already exists in position {}.'.format(vc_position)
  1863. form.add_error('vc_position', error_msg)
  1864. vc_position_list.append(vc_position)
  1865. class DeviceVCMembershipForm(forms.ModelForm):
  1866. class Meta:
  1867. model = Device
  1868. fields = ['vc_position', 'vc_priority']
  1869. labels = {
  1870. 'vc_position': 'Position',
  1871. 'vc_priority': 'Priority',
  1872. }
  1873. def __init__(self, validate_vc_position=False, *args, **kwargs):
  1874. super(DeviceVCMembershipForm, self).__init__(*args, **kwargs)
  1875. # Require VC position (only required when the Device is a VirtualChassis member)
  1876. self.fields['vc_position'].required = True
  1877. # Validation of vc_position is optional. This is only required when adding a new member to an existing
  1878. # VirtualChassis. Otherwise, vc_position validation is handled by BaseVCMemberFormSet.
  1879. self.validate_vc_position = validate_vc_position
  1880. def clean_vc_position(self):
  1881. vc_position = self.cleaned_data['vc_position']
  1882. if self.validate_vc_position:
  1883. conflicting_members = Device.objects.filter(
  1884. virtual_chassis=self.instance.virtual_chassis,
  1885. vc_position=vc_position
  1886. )
  1887. if conflicting_members.exists():
  1888. raise forms.ValidationError(
  1889. 'A virtual chassis member already exists in position {}.'.format(vc_position)
  1890. )
  1891. return vc_position
  1892. class VCMemberSelectForm(BootstrapMixin, ChainedFieldsMixin, forms.Form):
  1893. site = forms.ModelChoiceField(
  1894. queryset=Site.objects.all(),
  1895. label='Site',
  1896. required=False,
  1897. widget=forms.Select(
  1898. attrs={'filter-for': 'rack'}
  1899. )
  1900. )
  1901. rack = ChainedModelChoiceField(
  1902. queryset=Rack.objects.all(),
  1903. chains=(
  1904. ('site', 'site'),
  1905. ),
  1906. label='Rack',
  1907. required=False,
  1908. widget=APISelect(
  1909. api_url='/api/dcim/racks/?site_id={{site}}',
  1910. attrs={'filter-for': 'device', 'nullable': 'true'}
  1911. )
  1912. )
  1913. device = ChainedModelChoiceField(
  1914. queryset=Device.objects.filter(virtual_chassis__isnull=True),
  1915. chains=(
  1916. ('site', 'site'),
  1917. ('rack', 'rack'),
  1918. ),
  1919. label='Device',
  1920. widget=APISelect(
  1921. api_url='/api/dcim/devices/?site_id={{site}}&rack_id={{rack}}',
  1922. display_field='display_name',
  1923. disabled_indicator='virtual_chassis'
  1924. )
  1925. )
  1926. def clean_device(self):
  1927. device = self.cleaned_data['device']
  1928. if device.virtual_chassis is not None:
  1929. raise forms.ValidationError("Device {} is already assigned to a virtual chassis.".format(device))
  1930. return device
  1931. class VirtualChassisFilterForm(BootstrapMixin, CustomFieldFilterForm):
  1932. model = VirtualChassis
  1933. q = forms.CharField(required=False, label='Search')
  1934. site = FilterChoiceField(
  1935. queryset=Site.objects.all(),
  1936. to_field_name='slug',
  1937. )
  1938. tenant = FilterChoiceField(
  1939. queryset=Tenant.objects.all(),
  1940. to_field_name='slug',
  1941. null_label='-- None --',
  1942. )