model_forms.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1. from django import forms
  2. from django.contrib.contenttypes.models import ContentType
  3. from django.core.exceptions import ObjectDoesNotExist, ValidationError
  4. from django.utils.translation import gettext_lazy as _
  5. from dcim.models import Device, Interface, Site
  6. from dcim.forms.mixins import ScopedForm
  7. from ipam.choices import *
  8. from ipam.constants import *
  9. from ipam.formfields import IPNetworkFormField
  10. from ipam.models import *
  11. from netbox.forms import NetBoxModelForm
  12. from tenancy.forms import TenancyForm
  13. from utilities.exceptions import PermissionsViolation
  14. from utilities.forms import add_blank_choice
  15. from utilities.forms.fields import (
  16. CommentField, ContentTypeChoiceField, DynamicModelChoiceField, DynamicModelMultipleChoiceField, NumericArrayField,
  17. NumericRangeArrayField, SlugField
  18. )
  19. from utilities.forms.rendering import FieldSet, InlineFields, ObjectAttribute, TabbedGroups
  20. from utilities.forms.utils import get_field_value
  21. from utilities.forms.widgets import DatePicker, HTMXSelect
  22. from utilities.templatetags.builtins.filters import bettertitle
  23. from virtualization.models import VirtualMachine, VMInterface
  24. __all__ = (
  25. 'AggregateForm',
  26. 'ASNForm',
  27. 'ASNRangeForm',
  28. 'FHRPGroupForm',
  29. 'FHRPGroupAssignmentForm',
  30. 'IPAddressAssignForm',
  31. 'IPAddressBulkAddForm',
  32. 'IPAddressForm',
  33. 'IPRangeForm',
  34. 'PrefixForm',
  35. 'RIRForm',
  36. 'RoleForm',
  37. 'RouteTargetForm',
  38. 'ServiceForm',
  39. 'ServiceCreateForm',
  40. 'ServiceTemplateForm',
  41. 'VLANForm',
  42. 'VLANGroupForm',
  43. 'VLANTranslationPolicyForm',
  44. 'VLANTranslationRuleForm',
  45. 'VRFForm',
  46. )
  47. class VRFForm(TenancyForm, NetBoxModelForm):
  48. import_targets = DynamicModelMultipleChoiceField(
  49. label=_('Import targets'),
  50. queryset=RouteTarget.objects.all(),
  51. required=False
  52. )
  53. export_targets = DynamicModelMultipleChoiceField(
  54. label=_('Export targets'),
  55. queryset=RouteTarget.objects.all(),
  56. required=False
  57. )
  58. comments = CommentField()
  59. fieldsets = (
  60. FieldSet('name', 'rd', 'enforce_unique', 'description', 'tags', name=_('VRF')),
  61. FieldSet('import_targets', 'export_targets', name=_('Route Targets')),
  62. FieldSet('tenant_group', 'tenant', name=_('Tenancy')),
  63. )
  64. class Meta:
  65. model = VRF
  66. fields = [
  67. 'name', 'rd', 'enforce_unique', 'import_targets', 'export_targets', 'tenant_group', 'tenant', 'description',
  68. 'comments', 'tags',
  69. ]
  70. labels = {
  71. 'rd': "RD",
  72. }
  73. class RouteTargetForm(TenancyForm, NetBoxModelForm):
  74. fieldsets = (
  75. FieldSet('name', 'description', 'tags', name=_('Route Target')),
  76. FieldSet('tenant_group', 'tenant', name=_('Tenancy')),
  77. )
  78. comments = CommentField()
  79. class Meta:
  80. model = RouteTarget
  81. fields = [
  82. 'name', 'tenant_group', 'tenant', 'description', 'comments', 'tags',
  83. ]
  84. class RIRForm(NetBoxModelForm):
  85. slug = SlugField()
  86. fieldsets = (
  87. FieldSet('name', 'slug', 'is_private', 'description', 'tags', name=_('RIR')),
  88. )
  89. class Meta:
  90. model = RIR
  91. fields = [
  92. 'name', 'slug', 'is_private', 'description', 'tags',
  93. ]
  94. class AggregateForm(TenancyForm, NetBoxModelForm):
  95. rir = DynamicModelChoiceField(
  96. queryset=RIR.objects.all(),
  97. label=_('RIR'),
  98. quick_add=True
  99. )
  100. comments = CommentField()
  101. fieldsets = (
  102. FieldSet('prefix', 'rir', 'date_added', 'description', 'tags', name=_('Aggregate')),
  103. FieldSet('tenant_group', 'tenant', name=_('Tenancy')),
  104. )
  105. class Meta:
  106. model = Aggregate
  107. fields = [
  108. 'prefix', 'rir', 'date_added', 'tenant_group', 'tenant', 'description', 'comments', 'tags',
  109. ]
  110. widgets = {
  111. 'date_added': DatePicker(),
  112. }
  113. class ASNRangeForm(TenancyForm, NetBoxModelForm):
  114. rir = DynamicModelChoiceField(
  115. queryset=RIR.objects.all(),
  116. label=_('RIR'),
  117. quick_add=True
  118. )
  119. slug = SlugField()
  120. fieldsets = (
  121. FieldSet('name', 'slug', 'rir', 'start', 'end', 'description', 'tags', name=_('ASN Range')),
  122. FieldSet('tenant_group', 'tenant', name=_('Tenancy')),
  123. )
  124. class Meta:
  125. model = ASNRange
  126. fields = [
  127. 'name', 'slug', 'rir', 'start', 'end', 'tenant_group', 'tenant', 'description', 'tags'
  128. ]
  129. class ASNForm(TenancyForm, NetBoxModelForm):
  130. rir = DynamicModelChoiceField(
  131. queryset=RIR.objects.all(),
  132. label=_('RIR'),
  133. quick_add=True
  134. )
  135. sites = DynamicModelMultipleChoiceField(
  136. queryset=Site.objects.all(),
  137. label=_('Sites'),
  138. required=False
  139. )
  140. comments = CommentField()
  141. fieldsets = (
  142. FieldSet('asn', 'rir', 'sites', 'description', 'tags', name=_('ASN')),
  143. FieldSet('tenant_group', 'tenant', name=_('Tenancy')),
  144. )
  145. class Meta:
  146. model = ASN
  147. fields = [
  148. 'asn', 'rir', 'sites', 'tenant_group', 'tenant', 'description', 'comments', 'tags'
  149. ]
  150. widgets = {
  151. 'date_added': DatePicker(),
  152. }
  153. def __init__(self, data=None, instance=None, *args, **kwargs):
  154. super().__init__(data=data, instance=instance, *args, **kwargs)
  155. if self.instance and self.instance.pk is not None:
  156. self.fields['sites'].initial = self.instance.sites.all().values_list('id', flat=True)
  157. def save(self, *args, **kwargs):
  158. instance = super().save(*args, **kwargs)
  159. instance.sites.set(self.cleaned_data['sites'])
  160. return instance
  161. class RoleForm(NetBoxModelForm):
  162. slug = SlugField()
  163. fieldsets = (
  164. FieldSet('name', 'slug', 'weight', 'description', 'tags', name=_('Role')),
  165. )
  166. class Meta:
  167. model = Role
  168. fields = [
  169. 'name', 'slug', 'weight', 'description', 'tags',
  170. ]
  171. class PrefixForm(TenancyForm, ScopedForm, NetBoxModelForm):
  172. vrf = DynamicModelChoiceField(
  173. queryset=VRF.objects.all(),
  174. required=False,
  175. label=_('VRF')
  176. )
  177. vlan = DynamicModelChoiceField(
  178. queryset=VLAN.objects.all(),
  179. required=False,
  180. selector=True,
  181. query_params={
  182. 'available_at_site': '$site',
  183. },
  184. label=_('VLAN'),
  185. )
  186. role = DynamicModelChoiceField(
  187. label=_('Role'),
  188. queryset=Role.objects.all(),
  189. required=False,
  190. quick_add=True
  191. )
  192. comments = CommentField()
  193. fieldsets = (
  194. FieldSet(
  195. 'prefix', 'status', 'vrf', 'role', 'is_pool', 'mark_utilized', 'description', 'tags', name=_('Prefix')
  196. ),
  197. FieldSet('scope_type', 'scope', name=_('Scope')),
  198. FieldSet('vlan', name=_('VLAN Assignment')),
  199. FieldSet('tenant_group', 'tenant', name=_('Tenancy')),
  200. )
  201. class Meta:
  202. model = Prefix
  203. fields = [
  204. 'prefix', 'vrf', 'vlan', 'status', 'role', 'is_pool', 'mark_utilized', 'scope_type', 'tenant_group',
  205. 'tenant', 'description', 'comments', 'tags',
  206. ]
  207. class IPRangeForm(TenancyForm, NetBoxModelForm):
  208. vrf = DynamicModelChoiceField(
  209. queryset=VRF.objects.all(),
  210. required=False,
  211. label=_('VRF')
  212. )
  213. role = DynamicModelChoiceField(
  214. label=_('Role'),
  215. queryset=Role.objects.all(),
  216. required=False,
  217. quick_add=True
  218. )
  219. comments = CommentField()
  220. fieldsets = (
  221. FieldSet(
  222. 'vrf', 'start_address', 'end_address', 'role', 'status', 'mark_utilized', 'description', 'tags',
  223. name=_('IP Range')
  224. ),
  225. FieldSet('tenant_group', 'tenant', name=_('Tenancy')),
  226. )
  227. class Meta:
  228. model = IPRange
  229. fields = [
  230. 'vrf', 'start_address', 'end_address', 'status', 'role', 'tenant_group', 'tenant', 'mark_utilized',
  231. 'description', 'comments', 'tags',
  232. ]
  233. class IPAddressForm(TenancyForm, NetBoxModelForm):
  234. interface = DynamicModelChoiceField(
  235. queryset=Interface.objects.all(),
  236. required=False,
  237. context={
  238. 'parent': 'device',
  239. },
  240. selector=True,
  241. label=_('Interface'),
  242. )
  243. vminterface = DynamicModelChoiceField(
  244. queryset=VMInterface.objects.all(),
  245. required=False,
  246. context={
  247. 'parent': 'virtual_machine',
  248. },
  249. selector=True,
  250. label=_('Interface'),
  251. )
  252. fhrpgroup = DynamicModelChoiceField(
  253. queryset=FHRPGroup.objects.all(),
  254. required=False,
  255. selector=True,
  256. label=_('FHRP Group')
  257. )
  258. vrf = DynamicModelChoiceField(
  259. queryset=VRF.objects.all(),
  260. required=False,
  261. label=_('VRF')
  262. )
  263. nat_inside = DynamicModelChoiceField(
  264. queryset=IPAddress.objects.all(),
  265. required=False,
  266. selector=True,
  267. label=_('IP Address'),
  268. )
  269. primary_for_parent = forms.BooleanField(
  270. required=False,
  271. label=_('Make this the primary IP for the device/VM')
  272. )
  273. oob_for_parent = forms.BooleanField(
  274. required=False,
  275. label=_('Make this the out-of-band IP for the device')
  276. )
  277. comments = CommentField()
  278. fieldsets = (
  279. FieldSet('address', 'status', 'role', 'vrf', 'dns_name', 'description', 'tags', name=_('IP Address')),
  280. FieldSet('tenant_group', 'tenant', name=_('Tenancy')),
  281. FieldSet(
  282. TabbedGroups(
  283. FieldSet('interface', name=_('Device')),
  284. FieldSet('vminterface', name=_('Virtual Machine')),
  285. FieldSet('fhrpgroup', name=_('FHRP Group')),
  286. ),
  287. 'primary_for_parent', 'oob_for_parent', name=_('Assignment')
  288. ),
  289. FieldSet('nat_inside', name=_('NAT IP (Inside)')),
  290. )
  291. class Meta:
  292. model = IPAddress
  293. fields = [
  294. 'address', 'vrf', 'status', 'role', 'dns_name', 'primary_for_parent', 'oob_for_parent', 'nat_inside',
  295. 'tenant_group', 'tenant', 'description', 'comments', 'tags',
  296. ]
  297. def __init__(self, *args, **kwargs):
  298. # Initialize helper selectors
  299. instance = kwargs.get('instance')
  300. initial = kwargs.get('initial', {}).copy()
  301. if instance:
  302. if type(instance.assigned_object) is Interface:
  303. initial['interface'] = instance.assigned_object
  304. elif type(instance.assigned_object) is VMInterface:
  305. initial['vminterface'] = instance.assigned_object
  306. elif type(instance.assigned_object) is FHRPGroup:
  307. initial['fhrpgroup'] = instance.assigned_object
  308. kwargs['initial'] = initial
  309. super().__init__(*args, **kwargs)
  310. # Initialize parent object & fields if IP address is already assigned
  311. if self.instance.pk and self.instance.assigned_object:
  312. parent = getattr(self.instance.assigned_object, 'parent_object', None)
  313. if parent and (
  314. self.instance.address.version == 4 and parent.primary_ip4_id == self.instance.pk or
  315. self.instance.address.version == 6 and parent.primary_ip6_id == self.instance.pk
  316. ):
  317. self.initial['primary_for_parent'] = True
  318. if parent and getattr(parent, 'oob_ip_id', None) == self.instance.pk:
  319. self.initial['oob_for_parent'] = True
  320. if type(instance.assigned_object) is Interface:
  321. self.fields['interface'].widget.add_query_params({
  322. 'device_id': instance.assigned_object.device.pk,
  323. })
  324. elif type(instance.assigned_object) is VMInterface:
  325. self.fields['vminterface'].widget.add_query_params({
  326. 'virtual_machine_id': instance.assigned_object.virtual_machine.pk,
  327. })
  328. # Disable object assignment fields if the IP address is designated as primary
  329. if self.initial.get('primary_for_parent'):
  330. self.fields['interface'].disabled = True
  331. self.fields['vminterface'].disabled = True
  332. self.fields['fhrpgroup'].disabled = True
  333. def clean(self):
  334. super().clean()
  335. # Handle object assignment
  336. selected_objects = [
  337. field for field in ('interface', 'vminterface', 'fhrpgroup') if self.cleaned_data[field]
  338. ]
  339. if len(selected_objects) > 1:
  340. raise forms.ValidationError({
  341. selected_objects[1]: _("An IP address can only be assigned to a single object.")
  342. })
  343. elif selected_objects:
  344. assigned_object = self.cleaned_data[selected_objects[0]]
  345. if self.instance.pk and self.instance.assigned_object and assigned_object != self.instance.assigned_object:
  346. if self.cleaned_data['primary_for_parent']:
  347. raise ValidationError(
  348. _("Cannot reassign primary IP address for the parent device/VM")
  349. )
  350. if self.cleaned_data['oob_for_parent']:
  351. raise ValidationError(
  352. _("Cannot reassign out-of-Band IP address for the parent device")
  353. )
  354. self.instance.assigned_object = assigned_object
  355. else:
  356. self.instance.assigned_object = None
  357. # Primary IP assignment is only available if an interface has been assigned.
  358. interface = self.cleaned_data.get('interface') or self.cleaned_data.get('vminterface')
  359. if self.cleaned_data.get('primary_for_parent') and not interface:
  360. self.add_error(
  361. 'primary_for_parent', _("Only IP addresses assigned to an interface can be designated as primary IPs.")
  362. )
  363. # OOB IP assignment is only available if device interface has been assigned.
  364. interface = self.cleaned_data.get('interface')
  365. if self.cleaned_data.get('oob_for_parent') and not interface:
  366. self.add_error(
  367. 'oob_for_parent', _(
  368. "Only IP addresses assigned to a device interface can be designated as the out-of-band IP for a "
  369. "device."
  370. )
  371. )
  372. def save(self, *args, **kwargs):
  373. ipaddress = super().save(*args, **kwargs)
  374. # Assign/clear this IPAddress as the primary for the associated Device/VirtualMachine.
  375. interface = self.instance.assigned_object
  376. if type(interface) in (Interface, VMInterface):
  377. parent = interface.parent_object
  378. parent.snapshot()
  379. if self.cleaned_data['primary_for_parent']:
  380. if ipaddress.address.version == 4:
  381. parent.primary_ip4 = ipaddress
  382. else:
  383. parent.primary_ip6 = ipaddress
  384. parent.save()
  385. elif ipaddress.address.version == 4 and parent.primary_ip4 == ipaddress:
  386. parent.primary_ip4 = None
  387. parent.save()
  388. elif ipaddress.address.version == 6 and parent.primary_ip6 == ipaddress:
  389. parent.primary_ip6 = None
  390. parent.save()
  391. # Assign/clear this IPAddress as the OOB for the associated Device
  392. if type(interface) is Interface:
  393. parent = interface.parent_object
  394. parent.snapshot()
  395. if self.cleaned_data['oob_for_parent']:
  396. parent.oob_ip = ipaddress
  397. parent.save()
  398. elif parent.oob_ip == ipaddress:
  399. parent.oob_ip = None
  400. parent.save()
  401. return ipaddress
  402. class IPAddressBulkAddForm(TenancyForm, NetBoxModelForm):
  403. vrf = DynamicModelChoiceField(
  404. queryset=VRF.objects.all(),
  405. required=False,
  406. label=_('VRF')
  407. )
  408. class Meta:
  409. model = IPAddress
  410. fields = [
  411. 'address', 'vrf', 'status', 'role', 'dns_name', 'description', 'tenant_group', 'tenant', 'tags',
  412. ]
  413. class IPAddressAssignForm(forms.Form):
  414. vrf_id = DynamicModelChoiceField(
  415. queryset=VRF.objects.all(),
  416. required=False,
  417. label=_('VRF')
  418. )
  419. q = forms.CharField(
  420. required=False,
  421. label=_('Search'),
  422. )
  423. class FHRPGroupForm(NetBoxModelForm):
  424. # Optionally create a new IPAddress along with the FHRPGroup
  425. ip_vrf = DynamicModelChoiceField(
  426. queryset=VRF.objects.all(),
  427. required=False,
  428. label=_('VRF')
  429. )
  430. ip_address = IPNetworkFormField(
  431. required=False,
  432. label=_('Address')
  433. )
  434. ip_status = forms.ChoiceField(
  435. choices=add_blank_choice(IPAddressStatusChoices),
  436. required=False,
  437. label=_('Status')
  438. )
  439. comments = CommentField()
  440. fieldsets = (
  441. FieldSet('protocol', 'group_id', 'name', 'description', 'tags', name=_('FHRP Group')),
  442. FieldSet('auth_type', 'auth_key', name=_('Authentication')),
  443. FieldSet('ip_vrf', 'ip_address', 'ip_status', name=_('Virtual IP Address'))
  444. )
  445. class Meta:
  446. model = FHRPGroup
  447. fields = (
  448. 'protocol', 'group_id', 'auth_type', 'auth_key', 'name', 'ip_vrf', 'ip_address', 'ip_status', 'description',
  449. 'comments', 'tags',
  450. )
  451. def save(self, *args, **kwargs):
  452. instance = super().save(*args, **kwargs)
  453. user = getattr(instance, '_user', None) # Set under FHRPGroupEditView.alter_object()
  454. # Check if we need to create a new IPAddress for the group
  455. if self.cleaned_data.get('ip_address'):
  456. ipaddress = IPAddress(
  457. vrf=self.cleaned_data['ip_vrf'],
  458. address=self.cleaned_data['ip_address'],
  459. status=self.cleaned_data['ip_status'],
  460. role=FHRP_PROTOCOL_ROLE_MAPPINGS.get(self.cleaned_data['protocol'], IPAddressRoleChoices.ROLE_VIP),
  461. assigned_object=instance
  462. )
  463. ipaddress.populate_custom_field_defaults()
  464. ipaddress.save()
  465. # Check that the new IPAddress conforms with any assigned object-level permissions
  466. if not IPAddress.objects.restrict(user, 'add').filter(pk=ipaddress.pk).first():
  467. raise PermissionsViolation()
  468. return instance
  469. def clean(self):
  470. super().clean()
  471. ip_vrf = self.cleaned_data.get('ip_vrf')
  472. ip_address = self.cleaned_data.get('ip_address')
  473. ip_status = self.cleaned_data.get('ip_status')
  474. if ip_address:
  475. ip_form = IPAddressForm({
  476. 'address': ip_address,
  477. 'vrf': ip_vrf,
  478. 'status': ip_status,
  479. })
  480. if not ip_form.is_valid():
  481. self.errors.update({
  482. f'ip_{field}': error for field, error in ip_form.errors.items()
  483. })
  484. class FHRPGroupAssignmentForm(forms.ModelForm):
  485. group = DynamicModelChoiceField(
  486. label=_('Group'),
  487. queryset=FHRPGroup.objects.all()
  488. )
  489. fieldsets = (
  490. FieldSet(ObjectAttribute('interface'), 'group', 'priority'),
  491. )
  492. class Meta:
  493. model = FHRPGroupAssignment
  494. fields = ('group', 'priority')
  495. def __init__(self, *args, **kwargs):
  496. super().__init__(*args, **kwargs)
  497. ipaddresses = self.instance.interface.ip_addresses.all()
  498. for ipaddress in ipaddresses:
  499. self.fields['group'].widget.add_query_param('related_ip', ipaddress.pk)
  500. def clean_group(self):
  501. group = self.cleaned_data['group']
  502. conflicting_assignments = FHRPGroupAssignment.objects.filter(
  503. interface_type=self.instance.interface_type,
  504. interface_id=self.instance.interface_id,
  505. group=group
  506. )
  507. if self.instance.id:
  508. conflicting_assignments = conflicting_assignments.exclude(id=self.instance.id)
  509. if conflicting_assignments.exists():
  510. raise forms.ValidationError(
  511. _('Assignment already exists')
  512. )
  513. return group
  514. class VLANGroupForm(NetBoxModelForm):
  515. slug = SlugField()
  516. vid_ranges = NumericRangeArrayField(
  517. label=_('VLAN IDs')
  518. )
  519. scope_type = ContentTypeChoiceField(
  520. queryset=ContentType.objects.filter(model__in=VLANGROUP_SCOPE_TYPES),
  521. widget=HTMXSelect(),
  522. required=False,
  523. label=_('Scope type')
  524. )
  525. scope = DynamicModelChoiceField(
  526. label=_('Scope'),
  527. queryset=Site.objects.none(), # Initial queryset
  528. required=False,
  529. disabled=True,
  530. selector=True
  531. )
  532. fieldsets = (
  533. FieldSet('name', 'slug', 'description', 'tags', name=_('VLAN Group')),
  534. FieldSet('vid_ranges', name=_('Child VLANs')),
  535. FieldSet('scope_type', 'scope', name=_('Scope')),
  536. )
  537. class Meta:
  538. model = VLANGroup
  539. fields = [
  540. 'name', 'slug', 'description', 'vid_ranges', 'scope_type', 'tags',
  541. ]
  542. def __init__(self, *args, **kwargs):
  543. instance = kwargs.get('instance')
  544. initial = kwargs.get('initial', {})
  545. if instance is not None and instance.scope:
  546. initial['scope'] = instance.scope
  547. kwargs['initial'] = initial
  548. super().__init__(*args, **kwargs)
  549. if scope_type_id := get_field_value(self, 'scope_type'):
  550. try:
  551. scope_type = ContentType.objects.get(pk=scope_type_id)
  552. model = scope_type.model_class()
  553. self.fields['scope'].queryset = model.objects.all()
  554. self.fields['scope'].widget.attrs['selector'] = model._meta.label_lower
  555. self.fields['scope'].disabled = False
  556. self.fields['scope'].label = _(bettertitle(model._meta.verbose_name))
  557. except ObjectDoesNotExist:
  558. pass
  559. if self.instance and scope_type_id != self.instance.scope_type_id:
  560. self.initial['scope'] = None
  561. def clean(self):
  562. super().clean()
  563. # Assign the selected scope (if any)
  564. self.instance.scope = self.cleaned_data.get('scope')
  565. class VLANForm(TenancyForm, NetBoxModelForm):
  566. group = DynamicModelChoiceField(
  567. queryset=VLANGroup.objects.all(),
  568. required=False,
  569. selector=True,
  570. label=_('VLAN Group')
  571. )
  572. site = DynamicModelChoiceField(
  573. label=_('Site'),
  574. queryset=Site.objects.all(),
  575. required=False,
  576. null_option='None',
  577. selector=True
  578. )
  579. role = DynamicModelChoiceField(
  580. label=_('Role'),
  581. queryset=Role.objects.all(),
  582. required=False,
  583. quick_add=True
  584. )
  585. qinq_svlan = DynamicModelChoiceField(
  586. label=_('Q-in-Q SVLAN'),
  587. queryset=VLAN.objects.all(),
  588. required=False,
  589. query_params={
  590. 'qinq_role': VLANQinQRoleChoices.ROLE_SERVICE,
  591. }
  592. )
  593. comments = CommentField()
  594. class Meta:
  595. model = VLAN
  596. fields = [
  597. 'site', 'group', 'vid', 'name', 'status', 'role', 'tenant_group', 'tenant', 'qinq_role', 'qinq_svlan',
  598. 'description', 'comments', 'tags',
  599. ]
  600. class VLANTranslationPolicyForm(NetBoxModelForm):
  601. fieldsets = (
  602. FieldSet('name', 'description', 'tags', name=_('VLAN Translation Policy')),
  603. )
  604. class Meta:
  605. model = VLANTranslationPolicy
  606. fields = [
  607. 'name', 'description', 'tags',
  608. ]
  609. class VLANTranslationRuleForm(NetBoxModelForm):
  610. policy = DynamicModelChoiceField(
  611. label=_('Policy'),
  612. queryset=VLANTranslationPolicy.objects.all(),
  613. selector=True
  614. )
  615. fieldsets = (
  616. FieldSet('policy', 'local_vid', 'remote_vid', 'description', 'tags', name=_('VLAN Translation Rule')),
  617. )
  618. class Meta:
  619. model = VLANTranslationRule
  620. fields = [
  621. 'policy', 'local_vid', 'remote_vid', 'description', 'tags',
  622. ]
  623. class ServiceTemplateForm(NetBoxModelForm):
  624. ports = NumericArrayField(
  625. label=_('Ports'),
  626. base_field=forms.IntegerField(
  627. min_value=SERVICE_PORT_MIN,
  628. max_value=SERVICE_PORT_MAX
  629. ),
  630. help_text=_("Comma-separated list of one or more port numbers. A range may be specified using a hyphen.")
  631. )
  632. comments = CommentField()
  633. fieldsets = (
  634. FieldSet('name', 'protocol', 'ports', 'description', 'tags', name=_('Service Template')),
  635. )
  636. class Meta:
  637. model = ServiceTemplate
  638. fields = ('name', 'protocol', 'ports', 'description', 'comments', 'tags')
  639. class ServiceForm(NetBoxModelForm):
  640. device = DynamicModelChoiceField(
  641. label=_('Device'),
  642. queryset=Device.objects.all(),
  643. required=False,
  644. selector=True
  645. )
  646. virtual_machine = DynamicModelChoiceField(
  647. label=_('Virtual machine'),
  648. queryset=VirtualMachine.objects.all(),
  649. required=False,
  650. selector=True
  651. )
  652. ports = NumericArrayField(
  653. label=_('Ports'),
  654. base_field=forms.IntegerField(
  655. min_value=SERVICE_PORT_MIN,
  656. max_value=SERVICE_PORT_MAX
  657. ),
  658. help_text=_("Comma-separated list of one or more port numbers. A range may be specified using a hyphen.")
  659. )
  660. ipaddresses = DynamicModelMultipleChoiceField(
  661. queryset=IPAddress.objects.all(),
  662. required=False,
  663. label=_('IP Addresses'),
  664. query_params={
  665. 'device_id': '$device',
  666. 'virtual_machine_id': '$virtual_machine',
  667. }
  668. )
  669. comments = CommentField()
  670. fieldsets = (
  671. FieldSet(
  672. TabbedGroups(
  673. FieldSet('device', name=_('Device')),
  674. FieldSet('virtual_machine', name=_('Virtual Machine')),
  675. ),
  676. 'name',
  677. InlineFields('protocol', 'ports', label=_('Port(s)')),
  678. 'ipaddresses', 'description', 'tags', name=_('Service')
  679. ),
  680. )
  681. class Meta:
  682. model = Service
  683. fields = [
  684. 'device', 'virtual_machine', 'name', 'protocol', 'ports', 'ipaddresses', 'description', 'comments', 'tags',
  685. ]
  686. class ServiceCreateForm(ServiceForm):
  687. service_template = DynamicModelChoiceField(
  688. label=_('Service template'),
  689. queryset=ServiceTemplate.objects.all(),
  690. required=False
  691. )
  692. fieldsets = (
  693. FieldSet(
  694. TabbedGroups(
  695. FieldSet('device', name=_('Device')),
  696. FieldSet('virtual_machine', name=_('Virtual Machine')),
  697. ),
  698. TabbedGroups(
  699. FieldSet('service_template', name=_('From Template')),
  700. FieldSet('name', 'protocol', 'ports', name=_('Custom')),
  701. ),
  702. 'ipaddresses', 'description', 'tags', name=_('Service')
  703. ),
  704. )
  705. class Meta(ServiceForm.Meta):
  706. fields = [
  707. 'device', 'virtual_machine', 'service_template', 'name', 'protocol', 'ports', 'ipaddresses', 'description',
  708. 'comments', 'tags',
  709. ]
  710. def __init__(self, *args, **kwargs):
  711. super().__init__(*args, **kwargs)
  712. # Fields which may be populated from a ServiceTemplate are not required
  713. for field in ('name', 'protocol', 'ports'):
  714. self.fields[field].required = False
  715. def clean(self):
  716. super().clean()
  717. if self.cleaned_data['service_template']:
  718. # Create a new Service from the specified template
  719. service_template = self.cleaned_data['service_template']
  720. self.cleaned_data['name'] = service_template.name
  721. self.cleaned_data['protocol'] = service_template.protocol
  722. self.cleaned_data['ports'] = service_template.ports
  723. if not self.cleaned_data['description']:
  724. self.cleaned_data['description'] = service_template.description
  725. elif not all(self.cleaned_data[f] for f in ('name', 'protocol', 'ports')):
  726. raise forms.ValidationError(_("Must specify name, protocol, and port(s) if not using a service template."))