common.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. from django import forms
  2. from dcim.choices import *
  3. from dcim.constants import *
  4. __all__ = (
  5. 'InterfaceCommonForm',
  6. )
  7. class InterfaceCommonForm(forms.Form):
  8. mac_address = forms.CharField(
  9. empty_value=None,
  10. required=False,
  11. label='MAC address'
  12. )
  13. mtu = forms.IntegerField(
  14. required=False,
  15. min_value=INTERFACE_MTU_MIN,
  16. max_value=INTERFACE_MTU_MAX,
  17. label='MTU'
  18. )
  19. def clean(self):
  20. super().clean()
  21. parent_field = 'device' if 'device' in self.cleaned_data else 'virtual_machine'
  22. tagged_vlans = self.cleaned_data.get('tagged_vlans')
  23. # Untagged interfaces cannot be assigned tagged VLANs
  24. if self.cleaned_data['mode'] == InterfaceModeChoices.MODE_ACCESS and tagged_vlans:
  25. raise forms.ValidationError({
  26. 'mode': "An access interface cannot have tagged VLANs assigned."
  27. })
  28. # Remove all tagged VLAN assignments from "tagged all" interfaces
  29. elif self.cleaned_data['mode'] == InterfaceModeChoices.MODE_TAGGED_ALL:
  30. self.cleaned_data['tagged_vlans'] = []
  31. # Validate tagged VLANs; must be a global VLAN or in the same site
  32. elif self.cleaned_data['mode'] == InterfaceModeChoices.MODE_TAGGED and tagged_vlans:
  33. valid_sites = [None, self.cleaned_data[parent_field].site]
  34. invalid_vlans = [str(v) for v in tagged_vlans if v.site not in valid_sites]
  35. if invalid_vlans:
  36. raise forms.ValidationError({
  37. 'tagged_vlans': f"The tagged VLANs ({', '.join(invalid_vlans)}) must belong to the same site as "
  38. f"the interface's parent device/VM, or they must be global"
  39. })