forms.py 86 KB

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