forms.py 85 KB

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