class DeviceCSVForm(BaseDeviceCSVForm): site = CSVModelChoiceField(queryset=Site.objects.all(), to_field_name='name', help_text='Assigned site') location = CSVModelChoiceField(queryset=Location.objects.all(), to_field_name='name', required=False, help_text="Assigned location (if any)") rack = CSVModelChoiceField(queryset=Rack.objects.all(), to_field_name='name', required=False, help_text="Assigned rack (if any)") face = CSVChoiceField(choices=DeviceFaceChoices, required=False, help_text='Mounted rack face') class Meta(BaseDeviceCSVForm.Meta): fields = [ 'name', 'device_role', 'tenant', 'manufacturer', 'device_type', 'platform', 'serial', 'asset_tag', 'status', 'site', 'location', 'rack', 'position', 'face', 'virtual_chassis', 'vc_position', 'vc_priority', 'cluster', 'comments', ] def __init__(self, data=None, *args, **kwargs): super().__init__(data, *args, **kwargs) if data: # Limit location queryset by assigned site params = { f"site__{self.fields['site'].to_field_name}": data.get('site') } self.fields['location'].queryset = self.fields[ 'location'].queryset.filter(**params) # Limit rack queryset by assigned site and group params = { f"site__{self.fields['site'].to_field_name}": data.get('site'), f"location__{self.fields['location'].to_field_name}": data.get('location'), } self.fields['rack'].queryset = self.fields['rack'].queryset.filter( **params)
class CircuitCSVForm(CustomFieldModelCSVForm): provider = CSVModelChoiceField(queryset=Provider.objects.all(), to_field_name='name', help_text='Assigned provider') type = CSVModelChoiceField(queryset=CircuitType.objects.all(), to_field_name='name', help_text='Type of circuit') status = CSVChoiceField(choices=CircuitStatusChoices, help_text='Operational status') tenant = CSVModelChoiceField(queryset=Tenant.objects.all(), required=False, to_field_name='name', help_text='Assigned tenant') class Meta: model = Circuit fields = [ 'cid', 'provider', 'type', 'status', 'tenant', 'install_date', 'commit_rate', 'description', 'comments', ]
class CircuitCSVForm(CustomFieldModelCSVForm): provider = forms.ModelChoiceField( queryset=Provider.objects.all(), to_field_name='name', help_text='Name of parent provider', error_messages={'invalid_choice': 'Provider not found.'}) type = forms.ModelChoiceField( queryset=CircuitType.objects.all(), to_field_name='name', help_text='Type of circuit', error_messages={'invalid_choice': 'Invalid circuit type.'}) status = CSVChoiceField(choices=CircuitStatusChoices, required=False, help_text='Operational status') tenant = forms.ModelChoiceField( queryset=Tenant.objects.all(), required=False, to_field_name='name', help_text='Name of assigned tenant', error_messages={'invalid_choice': 'Tenant not found.'}) class Meta: model = Circuit fields = [ 'cid', 'provider', 'type', 'status', 'tenant', 'install_date', 'commit_rate', 'description', 'comments', ]
class VLANCSVForm(CustomFieldModelCSVForm): site = CSVModelChoiceField(queryset=Site.objects.all(), required=False, to_field_name='name', help_text='Assigned site') group = CSVModelChoiceField(queryset=VLANGroup.objects.all(), required=False, to_field_name='name', help_text='Assigned VLAN group') tenant = CSVModelChoiceField(queryset=Tenant.objects.all(), to_field_name='name', required=False, help_text='Assigned tenant') status = CSVChoiceField(choices=VLANStatusChoices, help_text='Operational status') role = CSVModelChoiceField(queryset=Role.objects.all(), required=False, to_field_name='name', help_text='Functional role') class Meta: model = VLAN fields = ('site', 'group', 'vid', 'name', 'tenant', 'status', 'role', 'description') help_texts = { 'vid': 'Numeric VLAN ID (1-4095)', 'name': 'VLAN name', }
class VMInterfaceCSVForm(CustomFieldModelCSVForm): virtual_machine = CSVModelChoiceField( queryset=VirtualMachine.objects.all(), to_field_name='name' ) parent = CSVModelChoiceField( queryset=VMInterface.objects.all(), required=False, to_field_name='name', help_text='Parent interface' ) bridge = CSVModelChoiceField( queryset=VMInterface.objects.all(), required=False, to_field_name='name', help_text='Bridged interface' ) mode = CSVChoiceField( choices=InterfaceModeChoices, required=False, help_text='IEEE 802.1Q operational mode (for L2 interfaces)' ) class Meta: model = VMInterface fields = ( 'virtual_machine', 'name', 'parent', 'bridge', 'enabled', 'mac_address', 'mtu', 'description', 'mode', ) def clean_enabled(self): # Make sure enabled is True when it's not included in the uploaded data if 'enabled' not in self.data: return True else: return self.cleaned_data['enabled']
class VirtualMachineCSVForm(CustomFieldModelCSVForm): status = CSVChoiceField(choices=VirtualMachineStatusChoices, required=False, help_text='Operational status of device') cluster = forms.ModelChoiceField(queryset=Cluster.objects.all(), to_field_name='name', help_text='Name of parent cluster', error_messages={ 'invalid_choice': 'Invalid cluster name.', }) role = forms.ModelChoiceField( queryset=DeviceRole.objects.filter(vm_role=True), required=False, to_field_name='name', help_text='Name of functional role', error_messages={'invalid_choice': 'Invalid role name.'}) tenant = forms.ModelChoiceField( queryset=Tenant.objects.all(), required=False, to_field_name='name', help_text='Name of assigned tenant', error_messages={'invalid_choice': 'Tenant not found.'}) platform = forms.ModelChoiceField(queryset=Platform.objects.all(), required=False, to_field_name='name', help_text='Name of assigned platform', error_messages={ 'invalid_choice': 'Invalid platform.', }) class Meta: model = VirtualMachine fields = VirtualMachine.csv_headers
class IPRangeCSVForm(CustomFieldModelCSVForm): vrf = CSVModelChoiceField(queryset=VRF.objects.all(), to_field_name='name', required=False, help_text='Assigned VRF') tenant = CSVModelChoiceField(queryset=Tenant.objects.all(), required=False, to_field_name='name', help_text='Assigned tenant') status = CSVChoiceField(choices=IPRangeStatusChoices, help_text='Operational status') role = CSVModelChoiceField(queryset=Role.objects.all(), required=False, to_field_name='name', help_text='Functional role') class Meta: model = IPRange fields = ( 'start_address', 'end_address', 'vrf', 'tenant', 'status', 'role', 'description', )
class PrefixCSVForm(CustomFieldModelCSVForm): vrf = CSVModelChoiceField( queryset=VRF.objects.all(), to_field_name='name', required=False, help_text='Assigned VRF' ) tenant = CSVModelChoiceField( queryset=Tenant.objects.all(), required=False, to_field_name='name', help_text='Assigned tenant' ) site = CSVModelChoiceField( queryset=Site.objects.all(), required=False, to_field_name='name', help_text='Assigned site' ) vlan_group = CSVModelChoiceField( queryset=VLANGroup.objects.all(), required=False, to_field_name='name', help_text="VLAN's group (if any)" ) vlan = CSVModelChoiceField( queryset=VLAN.objects.all(), required=False, to_field_name='vid', help_text="Assigned VLAN" ) status = CSVChoiceField( choices=PrefixStatusChoices, help_text='Operational status' ) role = CSVModelChoiceField( queryset=Role.objects.all(), required=False, to_field_name='name', help_text='Functional role' ) class Meta: model = Prefix fields = Prefix.csv_headers def __init__(self, data=None, *args, **kwargs): super().__init__(data, *args, **kwargs) if data: # Limit VLAN queryset by assigned site and/or group (if specified) params = {} if data.get('site'): params[f"site__{self.fields['site'].to_field_name}"] = data.get('site') if data.get('vlan_group'): params[f"group__{self.fields['vlan_group'].to_field_name}"] = data.get('vlan_group') if params: self.fields['vlan'].queryset = self.fields['vlan'].queryset.filter(**params)
class VLANCSVForm(forms.ModelForm): site = forms.ModelChoiceField(queryset=Site.objects.all(), required=False, to_field_name='name', help_text='Name of parent site', error_messages={ 'invalid_choice': 'Site not found.', }) group_name = forms.CharField(help_text='Name of VLAN group', required=False) tenant = forms.ModelChoiceField(queryset=Tenant.objects.all(), to_field_name='name', required=False, help_text='Name of assigned tenant', error_messages={ 'invalid_choice': 'Tenant not found.', }) status = CSVChoiceField(choices=VLAN_STATUS_CHOICES, help_text='Operational status') role = forms.ModelChoiceField(queryset=Role.objects.all(), required=False, to_field_name='name', help_text='Functional role', error_messages={ 'invalid_choice': 'Invalid role.', }) class Meta: model = VLAN fields = [ 'site', 'group_name', 'vid', 'name', 'tenant', 'status', 'role', 'description' ] help_texts = { 'vid': 'Numeric VLAN ID (1-4095)', 'name': 'VLAN name', } def clean(self): super(VLANCSVForm, self).clean() site = self.cleaned_data.get('site') group_name = self.cleaned_data.get('group_name') # Validate VLAN group if group_name: try: self.instance.group = VLANGroup.objects.get(site=site, name=group_name) except VLANGroup.DoesNotExist: if site: raise forms.ValidationError( "VLAN group {} not found for site {}".format( group_name, site)) else: raise forms.ValidationError( "Global VLAN group {} not found".format(group_name))
class WirelessLANCSVForm(CustomFieldModelCSVForm): group = CSVModelChoiceField(queryset=WirelessLANGroup.objects.all(), required=False, to_field_name='name', help_text='Assigned group') vlan = CSVModelChoiceField(queryset=VLAN.objects.all(), required=False, to_field_name='name', help_text='Bridged VLAN') auth_type = CSVChoiceField(choices=WirelessAuthTypeChoices, required=False, help_text='Authentication type') auth_cipher = CSVChoiceField(choices=WirelessAuthCipherChoices, required=False, help_text='Authentication cipher') class Meta: model = WirelessLAN fields = ('ssid', 'group', 'description', 'vlan', 'auth_type', 'auth_cipher', 'auth_psk')
class PowerOutletCSVForm(CustomFieldModelCSVForm): device = CSVModelChoiceField(queryset=Device.objects.all(), to_field_name='name') type = CSVChoiceField(choices=PowerOutletTypeChoices, required=False, help_text='Outlet type') power_port = CSVModelChoiceField( queryset=PowerPort.objects.all(), required=False, to_field_name='name', help_text='Local power port which feeds this outlet') feed_leg = CSVChoiceField( choices=PowerOutletFeedLegChoices, required=False, help_text='Electrical phase (for three-phase circuits)') class Meta: model = PowerOutlet fields = ('device', 'name', 'label', 'type', 'mark_connected', 'power_port', 'feed_leg', 'description') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Limit PowerPort choices to those belonging to this device (or VC master) if self.is_bound: try: device = self.fields['device'].to_python(self.data['device']) except forms.ValidationError: device = None else: try: device = self.instance.device except Device.DoesNotExist: device = None if device: self.fields['power_port'].queryset = PowerPort.objects.filter( device__in=[device, device.get_vc_master()]) else: self.fields['power_port'].queryset = PowerPort.objects.none()
class RearPortCSVForm(CustomFieldModelCSVForm): device = CSVModelChoiceField(queryset=Device.objects.all(), to_field_name='name') type = CSVChoiceField( help_text='Physical medium classification', choices=PortTypeChoices, ) class Meta: model = RearPort fields = ('device', 'name', 'label', 'type', 'color', 'mark_connected', 'positions', 'description') help_texts = {'positions': 'Number of front ports which may be mapped'}
class BaseDeviceCSVForm(CustomFieldModelCSVForm): device_role = CSVModelChoiceField(queryset=DeviceRole.objects.all(), to_field_name='name', help_text='Assigned role') tenant = CSVModelChoiceField(queryset=Tenant.objects.all(), required=False, to_field_name='name', help_text='Assigned tenant') manufacturer = CSVModelChoiceField(queryset=Manufacturer.objects.all(), to_field_name='name', help_text='Device type manufacturer') device_type = CSVModelChoiceField(queryset=DeviceType.objects.all(), to_field_name='model', help_text='Device type model') platform = CSVModelChoiceField(queryset=Platform.objects.all(), required=False, to_field_name='name', help_text='Assigned platform') status = CSVChoiceField(choices=DeviceStatusChoices, help_text='Operational status') virtual_chassis = CSVModelChoiceField( queryset=VirtualChassis.objects.all(), to_field_name='name', required=False, help_text='Virtual chassis') cluster = CSVModelChoiceField(queryset=Cluster.objects.all(), to_field_name='name', required=False, help_text='Virtualization cluster') class Meta: fields = [] model = Device help_texts = { 'vc_position': 'Virtual chassis position', 'vc_priority': 'Virtual chassis priority', } def __init__(self, data=None, *args, **kwargs): super().__init__(data, *args, **kwargs) if data: # Limit device type queryset by manufacturer params = { f"manufacturer__{self.fields['manufacturer'].to_field_name}": data.get('manufacturer') } self.fields['device_type'].queryset = self.fields[ 'device_type'].queryset.filter(**params)
class ServiceCSVForm(CustomFieldModelCSVForm): device = CSVModelChoiceField(queryset=Device.objects.all(), required=False, to_field_name='name', help_text='Required if not assigned to a VM') virtual_machine = CSVModelChoiceField( queryset=VirtualMachine.objects.all(), required=False, to_field_name='name', help_text='Required if not assigned to a device') protocol = CSVChoiceField(choices=ServiceProtocolChoices, help_text='IP protocol') class Meta: model = Service fields = Service.csv_headers
class ConsoleServerPortCSVForm(CustomFieldModelCSVForm): device = CSVModelChoiceField(queryset=Device.objects.all(), to_field_name='name') type = CSVChoiceField(choices=ConsolePortTypeChoices, required=False, help_text='Port type') speed = CSVTypedChoiceField(choices=ConsolePortSpeedChoices, coerce=int, empty_value=None, required=False, help_text='Port speed in bps') class Meta: model = ConsoleServerPort fields = ('device', 'name', 'label', 'type', 'speed', 'mark_connected', 'description')
class FrontPortCSVForm(CustomFieldModelCSVForm): device = CSVModelChoiceField(queryset=Device.objects.all(), to_field_name='name') rear_port = CSVModelChoiceField(queryset=RearPort.objects.all(), to_field_name='name', help_text='Corresponding rear port') type = CSVChoiceField(choices=PortTypeChoices, help_text='Physical medium classification') class Meta: model = FrontPort fields = ( 'device', 'name', 'label', 'type', 'color', 'mark_connected', 'rear_port', 'rear_port_position', 'description', ) help_texts = { 'rear_port_position': 'Mapped position on corresponding rear port', } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Limit RearPort choices to those belonging to this device (or VC master) if self.is_bound: try: device = self.fields['device'].to_python(self.data['device']) except forms.ValidationError: device = None else: try: device = self.instance.device except Device.DoesNotExist: device = None if device: self.fields['rear_port'].queryset = RearPort.objects.filter( device__in=[device, device.get_vc_master()]) else: self.fields['rear_port'].queryset = RearPort.objects.none()
class VLANCSVForm(CustomFieldModelCSVForm): site = CSVModelChoiceField( queryset=Site.objects.all(), required=False, to_field_name='name', help_text='Assigned site' ) group = CSVModelChoiceField( queryset=VLANGroup.objects.all(), required=False, to_field_name='name', help_text='Assigned VLAN group' ) tenant = CSVModelChoiceField( queryset=Tenant.objects.all(), to_field_name='name', required=False, help_text='Assigned tenant' ) status = CSVChoiceField( choices=VLANStatusChoices, help_text='Operational status' ) role = CSVModelChoiceField( queryset=Role.objects.all(), required=False, to_field_name='name', help_text='Functional role' ) class Meta: model = VLAN fields = VLAN.csv_headers help_texts = { 'vid': 'Numeric VLAN ID (1-4095)', 'name': 'VLAN name', } def __init__(self, data=None, *args, **kwargs): super().__init__(data, *args, **kwargs) if data: # Limit vlan queryset by assigned group params = {f"site__{self.fields['site'].to_field_name}": data.get('site')} self.fields['group'].queryset = self.fields['group'].queryset.filter(**params)
class VirtualMachineCSVForm(forms.ModelForm): status = CSVChoiceField( choices=STATUS_CHOICES, required=False, help_text='Operational status of device' ) cluster = forms.ModelChoiceField( queryset=Cluster.objects.all(), to_field_name='name', help_text='Name of parent cluster', error_messages={ 'invalid_choice': 'Invalid cluster name.', } ) role = forms.ModelChoiceField( queryset=DeviceRole.objects.filter(vm_role=True), required=False, to_field_name='name', help_text='Name of functional role', error_messages={ 'invalid_choice': 'Invalid role name.' } ) tenant = forms.ModelChoiceField( queryset=Tenant.objects.all(), required=False, to_field_name='name', help_text='Name of assigned tenant', error_messages={ 'invalid_choice': 'Tenant not found.' } ) platform = forms.ModelChoiceField( queryset=Platform.objects.all(), required=False, to_field_name='name', help_text='Name of assigned platform', error_messages={ 'invalid_choice': 'Invalid platform.', } ) class Meta: model = VirtualMachine fields = ['name', 'status', 'cluster', 'role', 'tenant', 'platform', 'vcpus', 'memory', 'disk', 'comments']
class VMInterfaceCSVForm(CSVModelForm): virtual_machine = CSVModelChoiceField( queryset=VirtualMachine.objects.all(), to_field_name='name') mode = CSVChoiceField( choices=InterfaceModeChoices, required=False, help_text='IEEE 802.1Q operational mode (for L2 interfaces)') class Meta: model = VMInterface fields = VMInterface.csv_headers def clean_enabled(self): # Make sure enabled is True when it's not included in the uploaded data if 'enabled' not in self.data: return True else: return self.cleaned_data['enabled']
class SiteCSVForm(CustomFieldModelCSVForm): status = CSVChoiceField(choices=SiteStatusChoices, help_text='Operational status') region = CSVModelChoiceField(queryset=Region.objects.all(), required=False, to_field_name='name', help_text='Assigned region') group = CSVModelChoiceField(queryset=SiteGroup.objects.all(), required=False, to_field_name='name', help_text='Assigned group') tenant = CSVModelChoiceField(queryset=Tenant.objects.all(), required=False, to_field_name='name', help_text='Assigned tenant') class Meta: model = Site fields = ( 'name', 'slug', 'status', 'region', 'group', 'tenant', 'facility', 'asn', 'time_zone', 'description', 'physical_address', 'shipping_address', 'latitude', 'longitude', 'contact_name', 'contact_phone', 'contact_email', 'comments', ) help_texts = { 'time_zone': mark_safe( 'Time zone (<a href="https://en.wikipedia.org/wiki/List_of_tz_database_time_zones">available options</a>)' ) }
class PowerPortCSVForm(CustomFieldModelCSVForm): device = CSVModelChoiceField(queryset=Device.objects.all(), to_field_name='name') type = CSVChoiceField(choices=PowerPortTypeChoices, required=False, help_text='Port type') class Meta: model = PowerPort fields = ( 'device', 'name', 'label', 'type', 'mark_connected', 'maximum_draw', 'allocated_draw', 'description', )
class VLANCSVForm(CustomFieldModelCSVForm): site = CSVModelChoiceField( label='Адрес', queryset=Site.objects.all(), required=False, to_field_name='name', help_text='Assigned site' ) group = CSVModelChoiceField( label='Группа', queryset=VLANGroup.objects.all(), required=False, to_field_name='name', help_text='Assigned VLAN group' ) tenant = CSVModelChoiceField( label='Учреждение', queryset=Tenant.objects.all(), to_field_name='name', required=False, help_text='Assigned tenant' ) status = CSVChoiceField( label='Статус', choices=VLANStatusChoices, help_text='Operational status' ) role = CSVModelChoiceField( label='Роль', queryset=Role.objects.all(), required=False, to_field_name='name', help_text='Functional role' ) class Meta: model = VLAN fields = VLAN.csv_headers help_texts = { 'vid': 'Numeric VLAN ID (1-4095)', 'name': 'VLAN name', }
class VirtualMachineCSVForm(CustomFieldModelCSVForm): status = CSVChoiceField( choices=VirtualMachineStatusChoices, help_text='Operational status' ) cluster = CSVModelChoiceField( queryset=Cluster.objects.all(), to_field_name='name', help_text='Assigned cluster' ) role = CSVModelChoiceField( queryset=DeviceRole.objects.filter( vm_role=True ), required=False, to_field_name='name', help_text='Functional role' ) tenant = CSVModelChoiceField( queryset=Tenant.objects.all(), required=False, to_field_name='name', help_text='Assigned tenant' ) platform = CSVModelChoiceField( queryset=Platform.objects.all(), required=False, to_field_name='name', help_text='Assigned platform' ) class Meta: model = VirtualMachine fields = ( 'name', 'status', 'role', 'cluster', 'tenant', 'platform', 'vcpus', 'memory', 'disk', 'comments', )
class ServiceCSVForm(CustomFieldModelCSVForm): device = FlexibleModelChoiceField(queryset=Device.objects.all(), required=False, to_field_name='name', help_text='Name or ID of device', error_messages={ 'invalid_choice': 'Device not found.', }) virtual_machine = FlexibleModelChoiceField( queryset=VirtualMachine.objects.all(), required=False, to_field_name='name', help_text='Name or ID of virtual machine', error_messages={ 'invalid_choice': 'Virtual machine not found.', }) protocol = CSVChoiceField(choices=ServiceProtocolChoices, help_text='IP protocol') class Meta: model = Service fields = Service.csv_headers help_texts = {}
class VirtualMachineCSVForm(CustomFieldModelCSVForm): status = CSVChoiceField(choices=VirtualMachineStatusChoices, required=False, help_text='Operational status of device') cluster = CSVModelChoiceField(queryset=Cluster.objects.all(), to_field_name='name', help_text='Assigned cluster') role = CSVModelChoiceField( queryset=DeviceRole.objects.filter(vm_role=True), required=False, to_field_name='name', help_text='Functional role') tenant = CSVModelChoiceField(queryset=Tenant.objects.all(), required=False, to_field_name='name', help_text='Assigned tenant') platform = CSVModelChoiceField(queryset=Platform.objects.all(), required=False, to_field_name='name', help_text='Assigned platform') class Meta: model = VirtualMachine fields = VirtualMachine.csv_headers
class IPAddressCSVForm(forms.ModelForm): vrf = forms.ModelChoiceField( queryset=VRF.objects.all(), required=False, to_field_name='rd', help_text='Route distinguisher of the assigned VRF', error_messages={ 'invalid_choice': 'VRF not found.', }) tenant = forms.ModelChoiceField(queryset=Tenant.objects.all(), to_field_name='name', required=False, help_text='Name of the assigned tenant', error_messages={ 'invalid_choice': 'Tenant not found.', }) status = CSVChoiceField(choices=IPADDRESS_STATUS_CHOICES, help_text='Operational status') role = CSVChoiceField(choices=IPADDRESS_ROLE_CHOICES, required=False, help_text='Functional role') device = FlexibleModelChoiceField( queryset=Device.objects.all(), required=False, to_field_name='name', help_text='Name or ID of assigned device', error_messages={ 'invalid_choice': 'Device not found.', }) virtual_machine = forms.ModelChoiceField( queryset=VirtualMachine.objects.all(), required=False, to_field_name='name', help_text='Name of assigned virtual machine', error_messages={ 'invalid_choice': 'Virtual machine not found.', }) interface_name = forms.CharField(help_text='Name of assigned interface', required=False) is_primary = forms.BooleanField( help_text='Make this the primary IP for the assigned device', required=False) class Meta: model = IPAddress fields = IPAddress.csv_headers def clean(self): super(IPAddressCSVForm, self).clean() device = self.cleaned_data.get('device') virtual_machine = self.cleaned_data.get('virtual_machine') interface_name = self.cleaned_data.get('interface_name') is_primary = self.cleaned_data.get('is_primary') # Validate interface if interface_name and device: try: self.instance.interface = Interface.objects.get( device=device, name=interface_name) except Interface.DoesNotExist: raise forms.ValidationError( "Invalid interface {} for device {}".format( interface_name, device)) elif interface_name and virtual_machine: try: self.instance.interface = Interface.objects.get( virtual_machine=virtual_machine, name=interface_name) except Interface.DoesNotExist: raise forms.ValidationError( "Invalid interface {} for virtual machine {}".format( interface_name, virtual_machine)) elif interface_name: raise forms.ValidationError( "Interface given ({}) but parent device/virtual machine not specified" .format(interface_name)) elif device: raise forms.ValidationError( "Device specified ({}) but interface missing".format(device)) elif virtual_machine: raise forms.ValidationError( "Virtual machine specified ({}) but interface missing".format( virtual_machine)) # Validate is_primary if is_primary and not device and not virtual_machine: raise forms.ValidationError( "No device or virtual machine specified; cannot set as primary IP" ) def save(self, *args, **kwargs): # Set interface if self.cleaned_data['device'] and self.cleaned_data['interface_name']: self.instance.interface = Interface.objects.get( device=self.cleaned_data['device'], name=self.cleaned_data['interface_name']) elif self.cleaned_data['virtual_machine'] and self.cleaned_data[ 'interface_name']: self.instance.interface = Interface.objects.get( virtual_machine=self.cleaned_data['virtual_machine'], name=self.cleaned_data['interface_name']) ipaddress = super(IPAddressCSVForm, self).save(*args, **kwargs) # Set as primary for device/VM if self.cleaned_data['is_primary']: parent = self.cleaned_data['device'] or self.cleaned_data[ 'virtual_machine'] if self.instance.address.version == 4: parent.primary_ip4 = ipaddress elif self.instance.address.version == 6: parent.primary_ip6 = ipaddress parent.save() return ipaddress
class PrefixCSVForm(forms.ModelForm): vrf = forms.ModelChoiceField(queryset=VRF.objects.all(), required=False, to_field_name='rd', help_text='Route distinguisher of parent VRF', error_messages={ 'invalid_choice': 'VRF not found.', }) tenant = forms.ModelChoiceField(queryset=Tenant.objects.all(), required=False, to_field_name='name', help_text='Name of assigned tenant', error_messages={ 'invalid_choice': 'Tenant not found.', }) site = forms.ModelChoiceField(queryset=Site.objects.all(), required=False, to_field_name='name', help_text='Name of parent site', error_messages={ 'invalid_choice': 'Site not found.', }) vlan_group = forms.CharField(help_text='Group name of assigned VLAN', required=False) vlan_vid = forms.IntegerField(help_text='Numeric ID of assigned VLAN', required=False) status = CSVChoiceField(choices=PREFIX_STATUS_CHOICES, help_text='Operational status') role = forms.ModelChoiceField(queryset=Role.objects.all(), required=False, to_field_name='name', help_text='Functional role', error_messages={ 'invalid_choice': 'Invalid role.', }) class Meta: model = Prefix fields = Prefix.csv_headers def clean(self): super(PrefixCSVForm, self).clean() site = self.cleaned_data.get('site') vlan_group = self.cleaned_data.get('vlan_group') vlan_vid = self.cleaned_data.get('vlan_vid') # Validate VLAN if vlan_group and vlan_vid: try: self.instance.vlan = VLAN.objects.get(site=site, group__name=vlan_group, vid=vlan_vid) except VLAN.DoesNotExist: if site: raise forms.ValidationError( "VLAN {} not found in site {} group {}".format( vlan_vid, site, vlan_group)) else: raise forms.ValidationError( "Global VLAN {} not found in group {}".format( vlan_vid, vlan_group)) except MultipleObjectsReturned: raise forms.ValidationError( "Multiple VLANs with VID {} found in group {}".format( vlan_vid, vlan_group)) elif vlan_vid: try: self.instance.vlan = VLAN.objects.get(site=site, group__isnull=True, vid=vlan_vid) except VLAN.DoesNotExist: if site: raise forms.ValidationError( "VLAN {} not found in site {}".format(vlan_vid, site)) else: raise forms.ValidationError( "Global VLAN {} not found".format(vlan_vid)) except MultipleObjectsReturned: raise forms.ValidationError( "Multiple VLANs with VID {} found".format(vlan_vid))
class IPAddressCSVForm(CustomFieldModelCSVForm): vrf = CSVModelChoiceField(queryset=VRF.objects.all(), to_field_name='name', required=False, help_text='Assigned VRF') tenant = CSVModelChoiceField(queryset=Tenant.objects.all(), to_field_name='name', required=False, help_text='Assigned tenant') status = CSVChoiceField(choices=IPAddressStatusChoices, help_text='Operational status') role = CSVChoiceField(choices=IPAddressRoleChoices, required=False, help_text='Functional role') device = CSVModelChoiceField( queryset=Device.objects.all(), required=False, to_field_name='name', help_text='Parent device of assigned interface (if any)') virtual_machine = CSVModelChoiceField( queryset=VirtualMachine.objects.all(), required=False, to_field_name='name', help_text='Parent VM of assigned interface (if any)') interface = CSVModelChoiceField(queryset=Interface.objects.all(), required=False, to_field_name='name', help_text='Assigned interface') is_primary = forms.BooleanField( help_text='Make this the primary IP for the assigned device', required=False) class Meta: model = IPAddress fields = IPAddress.csv_headers def __init__(self, data=None, *args, **kwargs): super().__init__(data, *args, **kwargs) if data: # Limit interface queryset by assigned device or virtual machine if data.get('device'): params = { f"device__{self.fields['device'].to_field_name}": data.get('device') } elif data.get('virtual_machine'): params = { f"virtual_machine__{self.fields['virtual_machine'].to_field_name}": data.get('virtual_machine') } else: params = { 'device': None, 'virtual_machine': None, } self.fields['interface'].queryset = self.fields[ 'interface'].queryset.filter(**params) def clean(self): super().clean() device = self.cleaned_data.get('device') virtual_machine = self.cleaned_data.get('virtual_machine') is_primary = self.cleaned_data.get('is_primary') # Validate is_primary if is_primary and not device and not virtual_machine: raise forms.ValidationError( "No device or virtual machine specified; cannot set as primary IP" ) def save(self, *args, **kwargs): ipaddress = super().save(*args, **kwargs) # Set as primary for device/VM if self.cleaned_data['is_primary']: parent = self.cleaned_data['device'] or self.cleaned_data[ 'virtual_machine'] if self.instance.address.version == 4: parent.primary_ip4 = ipaddress elif self.instance.address.version == 6: parent.primary_ip6 = ipaddress parent.save() return ipaddress
class IPAddressCSVForm(CustomFieldModelCSVForm): vrf = CSVModelChoiceField( label='vrf', queryset=VRF.objects.all(), to_field_name='name', required=False, help_text='Assigned VRF' ) tenant = CSVModelChoiceField( label='Учреждение', queryset=Tenant.objects.all(), to_field_name='name', required=False, help_text='Assigned tenant' ) status = CSVChoiceField( label='Статус', choices=IPAddressStatusChoices, required=False, help_text='Operational status' ) role = CSVChoiceField( label='Роль', choices=IPAddressRoleChoices, required=False, help_text='Functional role' ) device = CSVModelChoiceField( label='Устройство', queryset=Device.objects.all(), required=False, to_field_name='name', help_text='Parent device of assigned interface (if any)' ) virtual_machine = CSVModelChoiceField( label='virtual_machine', queryset=VirtualMachine.objects.all(), required=False, to_field_name='name', help_text='Parent VM of assigned interface (if any)' ) interface = CSVModelChoiceField( label='Интерфейс', queryset=Interface.objects.none(), # Can also refer to VMInterface required=False, to_field_name='name', help_text='Assigned interface' ) is_primary = forms.BooleanField( label='is_primary', help_text='Make this the primary IP for the assigned device', required=False ) class Meta: model = IPAddress fields = [ 'address', 'vrf', 'tenant', 'status', 'role', 'device', 'virtual_machine', 'interface', 'is_primary', 'dns_name', 'description', ] def __init__(self, data=None, *args, **kwargs): super().__init__(data, *args, **kwargs) if data: # Limit interface queryset by assigned device if data.get('device'): self.fields['interface'].queryset = Interface.objects.filter( **{f"device__{self.fields['device'].to_field_name}": data['device']} ) # Limit interface queryset by assigned device elif data.get('virtual_machine'): self.fields['interface'].queryset = VMInterface.objects.filter( **{f"virtual_machine__{self.fields['virtual_machine'].to_field_name}": data['virtual_machine']} ) def clean(self): super().clean() device = self.cleaned_data.get('device') virtual_machine = self.cleaned_data.get('virtual_machine') is_primary = self.cleaned_data.get('is_primary') # Validate is_primary if is_primary and not device and not virtual_machine: raise forms.ValidationError("No device or virtual machine specified; cannot set as primary IP") def save(self, *args, **kwargs): # Set interface assignment if self.cleaned_data['interface']: self.instance.assigned_object = self.cleaned_data['interface'] ipaddress = super().save(*args, **kwargs) # Set as primary for device/VM if self.cleaned_data['is_primary']: parent = self.cleaned_data['device'] or self.cleaned_data['virtual_machine'] if self.instance.address.version == 4: parent.primary_ip4 = ipaddress elif self.instance.address.version == 6: parent.primary_ip6 = ipaddress parent.save() return ipaddress
class IPAddressCSVForm(forms.ModelForm): vrf = forms.ModelChoiceField( queryset=VRF.objects.all(), required=False, to_field_name='rd', help_text='Route distinguisher of the assigned VRF', error_messages={ 'invalid_choice': 'VRF not found.', }) tenant = forms.ModelChoiceField(queryset=Tenant.objects.all(), to_field_name='name', required=False, help_text='Name of the assigned tenant', error_messages={ 'invalid_choice': 'Tenant not found.', }) status = CSVChoiceField(choices=PREFIX_STATUS_CHOICES, help_text='Operational status') device = FlexibleModelChoiceField( queryset=Device.objects.all(), required=False, to_field_name='name', help_text='Name or ID of assigned device', error_messages={ 'invalid_choice': 'Device not found.', }) interface_name = forms.CharField(help_text='Name of assigned interface', required=False) is_primary = forms.BooleanField( help_text='Make this the primary IP for the assigned device', required=False) class Meta: model = IPAddress fields = [ 'address', 'vrf', 'tenant', 'status', 'device', 'interface_name', 'is_primary', 'description' ] def clean(self): super(IPAddressCSVForm, self).clean() device = self.cleaned_data.get('device') interface_name = self.cleaned_data.get('interface_name') is_primary = self.cleaned_data.get('is_primary') # Validate interface if device and interface_name: try: self.instance.interface = Interface.objects.get( device=device, name=interface_name) except Interface.DoesNotExist: raise forms.ValidationError( "Invalid interface {} for device {}".format( interface_name, device)) elif device and not interface_name: raise forms.ValidationError( "Device set ({}) but interface missing".format(device)) elif interface_name and not device: raise forms.ValidationError( "Interface set ({}) but device missing or invalid".format( interface_name)) # Validate is_primary if is_primary and not device: raise forms.ValidationError( "No device specified; cannot set as primary IP") def save(self, *args, **kwargs): # Set interface if self.cleaned_data['device'] and self.cleaned_data['interface_name']: self.instance.interface = Interface.objects.get( device=self.cleaned_data['device'], name=self.cleaned_data['interface_name']) # Set as primary for device if self.cleaned_data['is_primary']: if self.instance.address.version == 4: self.instance.primary_ip4_for = self.cleaned_data['device'] elif self.instance.address.version == 6: self.instance.primary_ip6_for = self.cleaned_data['device'] return super(IPAddressCSVForm, self).save(*args, **kwargs)