forms.py 88 KB

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