Esempio n. 1
0
class InterfaceFilter(django_filters.FilterSet):
    """
    Not using DeviceComponentFilterSet for Interfaces because we need to check for VirtualChassis membership.
    """
    device = django_filters.CharFilter(
        method='filter_device',
        field_name='name',
        label='Device',
    )
    device_id = django_filters.NumberFilter(
        method='filter_device',
        field_name='pk',
        label='Device (ID)',
    )
    cabled = django_filters.BooleanFilter(field_name='cable',
                                          lookup_expr='isnull',
                                          exclude=True)
    type = django_filters.CharFilter(
        method='filter_type',
        label='Interface type',
    )
    lag_id = django_filters.ModelMultipleChoiceFilter(
        field_name='lag',
        queryset=Interface.objects.all(),
        label='LAG interface (ID)',
    )
    mac_address = django_filters.CharFilter(
        method='_mac_address',
        label='MAC address',
    )
    tag = TagFilter()
    vlan_id = django_filters.CharFilter(method='filter_vlan_id',
                                        label='Assigned VLAN')
    vlan = django_filters.CharFilter(method='filter_vlan',
                                     label='Assigned VID')
    form_factor = django_filters.MultipleChoiceFilter(choices=IFACE_FF_CHOICES,
                                                      null_value=None)

    class Meta:
        model = Interface
        fields = [
            'name', 'connection_status', 'form_factor', 'enabled', 'mtu',
            'mgmt_only'
        ]

    def filter_device(self, queryset, name, value):
        try:
            device = Device.objects.get(**{name: value})
            vc_interface_ids = device.vc_interfaces.values_list('id',
                                                                flat=True)
            return queryset.filter(pk__in=vc_interface_ids)
        except Device.DoesNotExist:
            return queryset.none()

    def filter_vlan_id(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        return queryset.filter(
            Q(untagged_vlan_id=value) | Q(tagged_vlans=value))

    def filter_vlan(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        return queryset.filter(
            Q(untagged_vlan_id__vid=value) | Q(tagged_vlans__vid=value))

    def filter_type(self, queryset, name, value):
        value = value.strip().lower()
        return {
            'physical':
            queryset.exclude(form_factor__in=NONCONNECTABLE_IFACE_TYPES),
            'virtual':
            queryset.filter(form_factor__in=VIRTUAL_IFACE_TYPES),
            'wireless':
            queryset.filter(form_factor__in=WIRELESS_IFACE_TYPES),
            'lag':
            queryset.filter(form_factor=IFACE_FF_LAG),
        }.get(value, queryset.none())

    def _mac_address(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        try:
            mac = EUI(value.strip())
            return queryset.filter(mac_address=mac)
        except AddrFormatError:
            return queryset.none()
Esempio n. 2
0
class IPAddressFilter(TenancyFilterSet, CustomFieldFilterSet):
    id__in = NumericInFilter(
        field_name='id',
        lookup_expr='in'
    )
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    parent = django_filters.CharFilter(
        method='search_by_parent',
        label='Parent prefix',
    )
    address = django_filters.CharFilter(
        method='filter_address',
        label='Address',
    )
    mask_length = django_filters.NumberFilter(
        method='filter_mask_length',
        label='Mask length',
    )
    vrf_id = django_filters.ModelMultipleChoiceFilter(
        queryset=VRF.objects.all(),
        label='VRF',
    )
    vrf = django_filters.ModelMultipleChoiceFilter(
        field_name='vrf__rd',
        queryset=VRF.objects.all(),
        to_field_name='rd',
        label='VRF (RD)',
    )
    device = django_filters.CharFilter(
        method='filter_device',
        field_name='name',
        label='Device',
    )
    device_id = django_filters.NumberFilter(
        method='filter_device',
        field_name='pk',
        label='Device (ID)',
    )
    virtual_machine_id = django_filters.ModelMultipleChoiceFilter(
        field_name='interface__virtual_machine',
        queryset=VirtualMachine.objects.all(),
        label='Virtual machine (ID)',
    )
    virtual_machine = django_filters.ModelMultipleChoiceFilter(
        field_name='interface__virtual_machine__name',
        queryset=VirtualMachine.objects.all(),
        to_field_name='name',
        label='Virtual machine (name)',
    )
    interface = django_filters.ModelMultipleChoiceFilter(
        field_name='interface__name',
        queryset=Interface.objects.all(),
        to_field_name='name',
        label='Interface (ID)',
    )
    interface_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Interface.objects.all(),
        label='Interface (ID)',
    )
    status = django_filters.MultipleChoiceFilter(
        choices=IPADDRESS_STATUS_CHOICES,
        null_value=None
    )
    role = django_filters.MultipleChoiceFilter(
        choices=IPADDRESS_ROLE_CHOICES
    )
    tag = TagFilter()

    class Meta:
        model = IPAddress
        fields = ['family', 'dns_name']

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        qs_filter = (
            Q(dns_name__icontains=value) |
            Q(description__icontains=value) |
            Q(address__istartswith=value)
        )
        return queryset.filter(qs_filter)

    def search_by_parent(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        try:
            query = str(netaddr.IPNetwork(value.strip()).cidr)
            return queryset.filter(address__net_host_contained=query)
        except (AddrFormatError, ValueError):
            return queryset.none()

    def filter_address(self, queryset, name, value):
        if not value.strip():
            return queryset
        try:
            # Match address and subnet mask
            if '/' in value:
                return queryset.filter(address=value)
            return queryset.filter(address__net_host=value)
        except ValidationError:
            return queryset.none()

    def filter_mask_length(self, queryset, name, value):
        if not value:
            return queryset
        return queryset.filter(address__net_mask_length=value)

    def filter_device(self, queryset, name, value):
        try:
            device = Device.objects.prefetch_related('device_type').get(**{name: value})
            vc_interface_ids = [i['id'] for i in device.vc_interfaces.values('id')]
            return queryset.filter(interface_id__in=vc_interface_ids)
        except Device.DoesNotExist:
            return queryset.none()
Esempio n. 3
0
class DeviceFilter(CustomFieldFilterSet, django_filters.FilterSet):
    id__in = NumericInFilter(name='id', lookup_expr='in')
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    manufacturer_id = django_filters.ModelMultipleChoiceFilter(
        name='device_type__manufacturer',
        queryset=Manufacturer.objects.all(),
        label='Manufacturer (ID)',
    )
    manufacturer = django_filters.ModelMultipleChoiceFilter(
        name='device_type__manufacturer__slug',
        queryset=Manufacturer.objects.all(),
        to_field_name='slug',
        label='Manufacturer (slug)',
    )
    device_type_id = django_filters.ModelMultipleChoiceFilter(
        queryset=DeviceType.objects.all(),
        label='Device type (ID)',
    )
    role_id = django_filters.ModelMultipleChoiceFilter(
        name='device_role_id',
        queryset=DeviceRole.objects.all(),
        label='Role (ID)',
    )
    role = django_filters.ModelMultipleChoiceFilter(
        name='device_role__slug',
        queryset=DeviceRole.objects.all(),
        to_field_name='slug',
        label='Role (slug)',
    )
    tenant_id = NullableModelMultipleChoiceFilter(
        queryset=Tenant.objects.all(),
        label='Tenant (ID)',
    )
    tenant = NullableModelMultipleChoiceFilter(
        name='tenant',
        queryset=Tenant.objects.all(),
        to_field_name='slug',
        label='Tenant (slug)',
    )
    platform_id = NullableModelMultipleChoiceFilter(
        queryset=Platform.objects.all(),
        label='Platform (ID)',
    )
    platform = NullableModelMultipleChoiceFilter(
        name='platform',
        queryset=Platform.objects.all(),
        to_field_name='slug',
        label='Platform (slug)',
    )
    name = NullableCharFieldFilter()
    asset_tag = NullableCharFieldFilter()
    site_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Site.objects.all(),
        label='Site (ID)',
    )
    site = django_filters.ModelMultipleChoiceFilter(
        name='site__slug',
        queryset=Site.objects.all(),
        to_field_name='slug',
        label='Site name (slug)',
    )
    rack_group_id = django_filters.ModelMultipleChoiceFilter(
        name='rack__group',
        queryset=RackGroup.objects.all(),
        label='Rack group (ID)',
    )
    rack_id = NullableModelMultipleChoiceFilter(
        name='rack',
        queryset=Rack.objects.all(),
        label='Rack (ID)',
    )
    model = django_filters.ModelMultipleChoiceFilter(
        name='device_type__slug',
        queryset=DeviceType.objects.all(),
        to_field_name='slug',
        label='Device model (slug)',
    )
    status = django_filters.MultipleChoiceFilter(
        choices=STATUS_CHOICES
    )
    is_full_depth = django_filters.BooleanFilter(
        name='device_type__is_full_depth',
        label='Is full depth',
    )
    is_console_server = django_filters.BooleanFilter(
        name='device_type__is_console_server',
        label='Is a console server',
    )
    is_pdu = django_filters.BooleanFilter(
        name='device_type__is_pdu',
        label='Is a PDU',
    )
    is_network_device = django_filters.BooleanFilter(
        name='device_type__is_network_device',
        label='Is a network device',
    )
    mac_address = django_filters.CharFilter(
        method='_mac_address',
        label='MAC address',
    )
    has_primary_ip = django_filters.BooleanFilter(
        method='_has_primary_ip',
        label='Has a primary IP',
    )

    class Meta:
        model = Device
        fields = ['serial']

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        return queryset.filter(
            Q(name__icontains=value) |
            Q(serial__icontains=value.strip()) |
            Q(inventory_items__serial__icontains=value.strip()) |
            Q(asset_tag=value.strip()) |
            Q(comments__icontains=value)
        ).distinct()

    def _mac_address(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        try:
            mac = EUI(value.strip())
            return queryset.filter(interfaces__mac_address=mac).distinct()
        except AddrFormatError:
            return queryset.none()

    def _has_primary_ip(self, queryset, name, value):
        if value:
            return queryset.filter(
                Q(primary_ip4__isnull=False) |
                Q(primary_ip6__isnull=False)
            )
        else:
            return queryset.exclude(
                Q(primary_ip4__isnull=False) |
                Q(primary_ip6__isnull=False)
            )
Esempio n. 4
0
class WorkshopStaffFilter(AMYFilterSet):
    """Form for this filter is never showed up, instead a custom form
    (.forms.WorkshopStaffForm) is used. So there's no need to specify widgets
    here.
    """
    country = django_filters.MultipleChoiceFilter(
        choices=list(Countries()),
        method="filter_country",
    )
    continent = ContinentFilter(label="Continent")
    lessons = django_filters.ModelMultipleChoiceFilter(
        label='Lessons',
        queryset=Lesson.objects.all(),
        conjoined=True,  # `AND`
    )
    badges = django_filters.ModelMultipleChoiceFilter(
        label='Badges',
        queryset=Badge.objects.instructor_badges(),
        conjoined=False,  # `OR`
    )
    is_trainer = django_filters.BooleanFilter(
        widget=widgets.CheckboxInput,
        method='filter_trainer',
    )
    languages = django_filters.ModelMultipleChoiceFilter(
        label='Languages',
        queryset=Language.objects.all(),
        conjoined=True,  # `AND`
    )
    gender = django_filters.ChoiceFilter(
        label='Gender',
        choices=Person.GENDER_CHOICES,
    )
    was_helper = django_filters.BooleanFilter(
        widget=widgets.CheckboxInput,
        method='filter_helper',
    )
    was_organizer = django_filters.BooleanFilter(
        widget=widgets.CheckboxInput,
        method='filter_organizer',
    )
    is_in_progress_trainee = django_filters.BooleanFilter(
        widget=widgets.CheckboxInput,
        method='filter_in_progress_trainee',
    )

    def filter_country(self, qs, n, v):
        if v:
            return qs.filter(
                Q(airport__country__in=v) | Q(country__in=v)
            )
        return qs

    def filter_trainer(self, qs, n, v):
        if v:
            return qs.filter(is_trainer__gte=1)
        return qs

    def filter_helper(self, qs, n, v):
        if v:
            return qs.filter(num_helper__gte=1)
        return qs

    def filter_organizer(self, qs, n, v):
        if v:
            return qs.filter(num_organizer__gte=1)
        return qs

    def filter_in_progress_trainee(self, qs, n, v):
        if v:
            return qs.filter(is_trainee__gte=1)
        return qs
Esempio n. 5
0
class InterfaceFilterSet(
        BaseFilterSet,
        DeviceComponentFilterSet,
        CableTerminationFilterSet,
        PathEndpointFilterSet,
):
    q = django_filters.CharFilter(
        method="search",
        label="Search",
    )
    # Override device and device_id filters from DeviceComponentFilterSet to match against any peer virtual chassis
    # members
    device = MultiValueCharFilter(
        method="filter_device",
        field_name="name",
        label="Device (name)",
    )
    device_id = MultiValueUUIDFilter(
        method="filter_device_id",
        field_name="pk",
        label="Device (ID)",
    )
    kind = django_filters.CharFilter(
        method="filter_kind",
        label="Kind of interface",
    )
    lag_id = django_filters.ModelMultipleChoiceFilter(
        field_name="lag",
        queryset=Interface.objects.all(),
        label="LAG interface (ID)",
    )
    mac_address = MultiValueMACAddressFilter()
    tag = TagFilter()
    vlan_id = django_filters.CharFilter(method="filter_vlan_id",
                                        label="Assigned VLAN")
    vlan = django_filters.NumberFilter(method="filter_vlan",
                                       label="Assigned VID")
    type = django_filters.MultipleChoiceFilter(choices=InterfaceTypeChoices,
                                               null_value=None)

    class Meta:
        model = Interface
        fields = [
            "id",
            "name",
            "type",
            "enabled",
            "mtu",
            "mgmt_only",
            "mode",
            "description",
        ]

    def filter_device(self, queryset, name, value):
        try:
            devices = Device.objects.filter(**{"{}__in".format(name): value})
            vc_interface_ids = []
            for device in devices:
                vc_interface_ids.extend(
                    device.vc_interfaces.values_list("id", flat=True))
            return queryset.filter(pk__in=vc_interface_ids)
        except Device.DoesNotExist:
            return queryset.none()

    def filter_device_id(self, queryset, name, id_list):
        # Include interfaces belonging to peer virtual chassis members
        vc_interface_ids = []
        try:
            devices = Device.objects.filter(pk__in=id_list)
            for device in devices:
                vc_interface_ids += device.vc_interfaces.values_list("id",
                                                                     flat=True)
            return queryset.filter(pk__in=vc_interface_ids)
        except Device.DoesNotExist:
            return queryset.none()

    def filter_vlan_id(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        return queryset.filter(
            Q(untagged_vlan_id=value) | Q(tagged_vlans=value))

    def filter_vlan(self, queryset, name, value):
        value = str(value).strip()
        if not value:
            return queryset
        return queryset.filter(
            Q(untagged_vlan_id__vid=value) | Q(tagged_vlans__vid=value))

    def filter_kind(self, queryset, name, value):
        value = value.strip().lower()
        return {
            "physical": queryset.exclude(type__in=NONCONNECTABLE_IFACE_TYPES),
            "virtual": queryset.filter(type__in=VIRTUAL_IFACE_TYPES),
            "wireless": queryset.filter(type__in=WIRELESS_IFACE_TYPES),
        }.get(value, queryset.none())
Esempio n. 6
0
class VLANFilter(CustomFieldFilterSet, django_filters.FilterSet):
    id__in = NumericInFilter(name='id', lookup_expr='in')
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    site_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Site.objects.all(),
        label='Site (ID)',
    )
    site = django_filters.ModelMultipleChoiceFilter(
        name='site__slug',
        queryset=Site.objects.all(),
        to_field_name='slug',
        label='Site (slug)',
    )
    group_id = django_filters.ModelMultipleChoiceFilter(
        queryset=VLANGroup.objects.all(),
        label='Group (ID)',
    )
    group = django_filters.ModelMultipleChoiceFilter(
        name='group__slug',
        queryset=VLANGroup.objects.all(),
        to_field_name='slug',
        label='Group',
    )
    tenant_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Tenant.objects.all(),
        label='Tenant (ID)',
    )
    tenant = django_filters.ModelMultipleChoiceFilter(
        name='tenant__slug',
        queryset=Tenant.objects.all(),
        to_field_name='slug',
        label='Tenant (slug)',
    )
    role_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Role.objects.all(),
        label='Role (ID)',
    )
    role = django_filters.ModelMultipleChoiceFilter(
        name='role__slug',
        queryset=Role.objects.all(),
        to_field_name='slug',
        label='Role (slug)',
    )
    status = django_filters.MultipleChoiceFilter(
        choices=VLAN_STATUS_CHOICES,
        null_value=None
    )

    class Meta:
        model = VLAN
        fields = ['vid', 'name']

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        qs_filter = Q(name__icontains=value) | Q(description__icontains=value)
        try:
            qs_filter |= Q(vid=int(value.strip()))
        except ValueError:
            pass
        return queryset.filter(qs_filter)
Esempio n. 7
0
class VirtualMachineFilter(CustomFieldFilterSet):
    id__in = NumericInFilter(name='id', lookup_expr='in')
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    status = django_filters.MultipleChoiceFilter(
        choices=VM_STATUS_CHOICES,
        null_value=None
    )
    cluster_group_id = django_filters.ModelMultipleChoiceFilter(
        name='cluster__group',
        queryset=ClusterGroup.objects.all(),
        label='Cluster group (ID)',
    )
    cluster_group = django_filters.ModelMultipleChoiceFilter(
        name='cluster__group__slug',
        queryset=ClusterGroup.objects.all(),
        to_field_name='slug',
        label='Cluster group (slug)',
    )
    cluster_type_id = django_filters.ModelMultipleChoiceFilter(
        name='cluster__type',
        queryset=ClusterType.objects.all(),
        label='Cluster type (ID)',
    )
    cluster_type = django_filters.ModelMultipleChoiceFilter(
        name='cluster__type__slug',
        queryset=ClusterType.objects.all(),
        to_field_name='slug',
        label='Cluster type (slug)',
    )
    cluster_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Cluster.objects.all(),
        label='Cluster (ID)',
    )
    region_id = django_filters.NumberFilter(
        method='filter_region',
        name='pk',
        label='Region (ID)',
    )
    region = django_filters.CharFilter(
        method='filter_region',
        name='slug',
        label='Region (slug)',
    )
    site_id = django_filters.ModelMultipleChoiceFilter(
        name='cluster__site',
        queryset=Site.objects.all(),
        label='Site (ID)',
    )
    site = django_filters.ModelMultipleChoiceFilter(
        name='cluster__site__slug',
        queryset=Site.objects.all(),
        to_field_name='slug',
        label='Site (slug)',
    )
    role_id = django_filters.ModelMultipleChoiceFilter(
        queryset=DeviceRole.objects.all(),
        label='Role (ID)',
    )
    role = django_filters.ModelMultipleChoiceFilter(
        name='role__slug',
        queryset=DeviceRole.objects.all(),
        to_field_name='slug',
        label='Role (slug)',
    )
    tenant_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Tenant.objects.all(),
        label='Tenant (ID)',
    )
    tenant = django_filters.ModelMultipleChoiceFilter(
        name='tenant__slug',
        queryset=Tenant.objects.all(),
        to_field_name='slug',
        label='Tenant (slug)',
    )
    platform_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Platform.objects.all(),
        label='Platform (ID)',
    )
    platform = django_filters.ModelMultipleChoiceFilter(
        name='platform__slug',
        queryset=Platform.objects.all(),
        to_field_name='slug',
        label='Platform (slug)',
    )
    tag = django_filters.CharFilter(
        name='tags__slug',
    )

    class Meta:
        model = VirtualMachine
        fields = ['name', 'cluster']

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        return queryset.filter(
            Q(name__icontains=value) |
            Q(comments__icontains=value)
        )

    def filter_region(self, queryset, name, value):
        try:
            region = Region.objects.get(**{name: value})
        except ObjectDoesNotExist:
            return queryset.none()
        return queryset.filter(
            Q(cluster__site__region=region) |
            Q(cluster__site__region__in=region.get_descendants())
        )
Esempio n. 8
0
class CircuitFilterSet(PrimaryModelFilterSet, TenancyFilterSet):
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    provider_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Provider.objects.all(),
        label='Provider (ID)',
    )
    provider = django_filters.ModelMultipleChoiceFilter(
        field_name='provider__slug',
        queryset=Provider.objects.all(),
        to_field_name='slug',
        label='Provider (slug)',
    )
    provider_network_id = django_filters.ModelMultipleChoiceFilter(
        field_name='terminations__provider_network',
        queryset=ProviderNetwork.objects.all(),
        label='ProviderNetwork (ID)',
    )
    type_id = django_filters.ModelMultipleChoiceFilter(
        queryset=CircuitType.objects.all(),
        label='Circuit type (ID)',
    )
    type = django_filters.ModelMultipleChoiceFilter(
        field_name='type__slug',
        queryset=CircuitType.objects.all(),
        to_field_name='slug',
        label='Circuit type (slug)',
    )
    status = django_filters.MultipleChoiceFilter(choices=CircuitStatusChoices,
                                                 null_value=None)
    region_id = TreeNodeMultipleChoiceFilter(
        queryset=Region.objects.all(),
        field_name='terminations__site__region',
        lookup_expr='in',
        label='Region (ID)',
    )
    region = TreeNodeMultipleChoiceFilter(
        queryset=Region.objects.all(),
        field_name='terminations__site__region',
        lookup_expr='in',
        to_field_name='slug',
        label='Region (slug)',
    )
    site_group_id = TreeNodeMultipleChoiceFilter(
        queryset=SiteGroup.objects.all(),
        field_name='terminations__site__group',
        lookup_expr='in',
        label='Site group (ID)',
    )
    site_group = TreeNodeMultipleChoiceFilter(
        queryset=SiteGroup.objects.all(),
        field_name='terminations__site__group',
        lookup_expr='in',
        to_field_name='slug',
        label='Site group (slug)',
    )
    site_id = django_filters.ModelMultipleChoiceFilter(
        field_name='terminations__site',
        queryset=Site.objects.all(),
        label='Site (ID)',
    )
    site = django_filters.ModelMultipleChoiceFilter(
        field_name='terminations__site__slug',
        queryset=Site.objects.all(),
        to_field_name='slug',
        label='Site (slug)',
    )
    tag = TagFilter()

    class Meta:
        model = Circuit
        fields = ['id', 'cid', 'install_date', 'commit_rate']

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        return queryset.filter(
            Q(cid__icontains=value)
            | Q(terminations__xconnect_id__icontains=value)
            | Q(terminations__pp_info__icontains=value)
            | Q(terminations__description__icontains=value)
            | Q(description__icontains=value)
            | Q(comments__icontains=value)).distinct()
Esempio n. 9
0
class IPAddressFilterSet(BaseFilterSet, TenancyFilterSet, CustomFieldFilterSet,
                         CreatedUpdatedFilterSet):
    id__in = NumericInFilter(field_name='id', lookup_expr='in')
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    parent = django_filters.CharFilter(
        method='search_by_parent',
        label='Parent prefix',
    )
    address = MultiValueCharFilter(
        method='filter_address',
        label='Address',
    )
    mask_length = django_filters.NumberFilter(
        method='filter_mask_length',
        label='Mask length',
    )
    vrf_id = django_filters.ModelMultipleChoiceFilter(
        queryset=VRF.objects.all(),
        label='VRF',
    )
    vrf = django_filters.ModelMultipleChoiceFilter(
        field_name='vrf__rd',
        queryset=VRF.objects.all(),
        to_field_name='rd',
        label='VRF (RD)',
    )
    device = MultiValueCharFilter(
        method='filter_device',
        field_name='name',
        label='Device (name)',
    )
    device_id = MultiValueNumberFilter(
        method='filter_device',
        field_name='pk',
        label='Device (ID)',
    )
    virtual_machine_id = django_filters.ModelMultipleChoiceFilter(
        field_name='interface__virtual_machine',
        queryset=VirtualMachine.objects.all(),
        label='Virtual machine (ID)',
    )
    virtual_machine = django_filters.ModelMultipleChoiceFilter(
        field_name='interface__virtual_machine__name',
        queryset=VirtualMachine.objects.all(),
        to_field_name='name',
        label='Virtual machine (name)',
    )
    interface = django_filters.ModelMultipleChoiceFilter(
        field_name='interface__name',
        queryset=Interface.objects.all(),
        to_field_name='name',
        label='Interface (ID)',
    )
    interface_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Interface.objects.all(),
        label='Interface (ID)',
    )
    assigned_to_interface = django_filters.BooleanFilter(
        method='_assigned_to_interface',
        label='Is assigned to an interface',
    )
    status = django_filters.MultipleChoiceFilter(
        choices=IPAddressStatusChoices, null_value=None)
    role = django_filters.MultipleChoiceFilter(choices=IPAddressRoleChoices)
    tag = TagFilter()

    class Meta:
        model = IPAddress
        fields = ['family', 'dns_name']

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        qs_filter = (Q(dns_name__icontains=value)
                     | Q(description__icontains=value)
                     | Q(address__istartswith=value))
        return queryset.filter(qs_filter)

    def search_by_parent(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        try:
            query = str(netaddr.IPNetwork(value.strip()).cidr)
            return queryset.filter(address__net_host_contained=query)
        except (AddrFormatError, ValueError):
            return queryset.none()

    def filter_address(self, queryset, name, value):
        try:
            return queryset.filter(address__net_in=value)
        except ValidationError:
            return queryset.none()

    def filter_mask_length(self, queryset, name, value):
        if not value:
            return queryset
        return queryset.filter(address__net_mask_length=value)

    def filter_device(self, queryset, name, value):
        try:
            devices = Device.objects.prefetch_related('device_type').filter(
                **{'{}__in'.format(name): value})
            vc_interface_ids = []
            for device in devices:
                vc_interface_ids.extend(
                    [i['id'] for i in device.vc_interfaces.values('id')])
            return queryset.filter(interface_id__in=vc_interface_ids)
        except Device.DoesNotExist:
            return queryset.none()

    def _assigned_to_interface(self, queryset, name, value):
        return queryset.exclude(interface__isnull=value)
Esempio n. 10
0
class InterfaceFilterSet(BaseFilterSet, DeviceComponentFilterSet,
                         CableTerminationFilterSet, PathEndpointFilterSet):
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    # Override device and device_id filters from DeviceComponentFilterSet to match against any peer virtual chassis
    # members
    device = MultiValueCharFilter(
        method='filter_device',
        field_name='name',
        label='Device',
    )
    device_id = MultiValueNumberFilter(
        method='filter_device_id',
        field_name='pk',
        label='Device (ID)',
    )
    kind = django_filters.CharFilter(
        method='filter_kind',
        label='Kind of interface',
    )
    lag_id = django_filters.ModelMultipleChoiceFilter(
        field_name='lag',
        queryset=Interface.objects.all(),
        label='LAG interface (ID)',
    )
    mac_address = MultiValueMACAddressFilter()
    tag = TagFilter()
    vlan_id = django_filters.CharFilter(method='filter_vlan_id',
                                        label='Assigned VLAN')
    vlan = django_filters.CharFilter(method='filter_vlan',
                                     label='Assigned VID')
    type = django_filters.MultipleChoiceFilter(choices=InterfaceTypeChoices,
                                               null_value=None)

    class Meta:
        model = Interface
        fields = [
            'id', 'name', 'label', 'type', 'enabled', 'mtu', 'mgmt_only',
            'mode', 'description'
        ]

    def filter_device(self, queryset, name, value):
        try:
            devices = Device.objects.filter(**{'{}__in'.format(name): value})
            vc_interface_ids = []
            for device in devices:
                vc_interface_ids.extend(
                    device.vc_interfaces.values_list('id', flat=True))
            return queryset.filter(pk__in=vc_interface_ids)
        except Device.DoesNotExist:
            return queryset.none()

    def filter_device_id(self, queryset, name, id_list):
        # Include interfaces belonging to peer virtual chassis members
        vc_interface_ids = []
        try:
            devices = Device.objects.filter(pk__in=id_list)
            for device in devices:
                vc_interface_ids += device.vc_interfaces.values_list('id',
                                                                     flat=True)
            return queryset.filter(pk__in=vc_interface_ids)
        except Device.DoesNotExist:
            return queryset.none()

    def filter_vlan_id(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        return queryset.filter(
            Q(untagged_vlan_id=value) | Q(tagged_vlans=value))

    def filter_vlan(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        return queryset.filter(
            Q(untagged_vlan_id__vid=value) | Q(tagged_vlans__vid=value))

    def filter_kind(self, queryset, name, value):
        value = value.strip().lower()
        return {
            'physical': queryset.exclude(type__in=NONCONNECTABLE_IFACE_TYPES),
            'virtual': queryset.filter(type__in=VIRTUAL_IFACE_TYPES),
            'wireless': queryset.filter(type__in=WIRELESS_IFACE_TYPES),
        }.get(value, queryset.none())
Esempio n. 11
0
class ResourceContainerFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(method='lookup_using_name_index')
    content = django_filters.CharFilter(name='primary__indexable_content',
                                        lookup_expr='icontains')
    part_of = django_filters.ModelChoiceFilter(name='part_of', queryset=Collection.objects.all())

    # FIXME: The following statement results in a very expensive Postgres query.
    # entity_type = django_filters.ModelChoiceFilter(
    #     name='primary__entity_type',
    #     queryset=Type.objects.annotate(num_instances=Count('resource'))\
    #                          .filter(num_instances__gt=0)
    # )
    # As a temporary workaround, use a static list for choices.
    entity_type = django_filters.ModelChoiceFilter(
        name='primary__entity_type',
        queryset=Type.objects.all(),
    )

    # FIXME: The following statement results in a very expensive Postgres query.
    # As a temporary workaround, use a static list for choices.
    # content_type = django_filters.MultipleChoiceFilter(choices=[(val, val) for val in ContentRelation.objects.values_list('content_type', flat=True).distinct('content_type')], method='filter_content_type')

    content_type_choices = [
        'application/java-archive',
        'application/javascript',
        'application/json',
        'application/msword',
        'application/octet-stream',
        'application/pdf',
        'application/rtf',
        'application/vnd.apple.pages',
        'application/vnd.ms-excel',
        'application/vnd.oasis.opendocument.text',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/x-bibtex-text-file',
        'application/xhtml+xml',
        'application/x-java-archive',
        'application/xml',
        'application/x-msdownload',
        'application/x-msdownload; format=pe32',
        'application/x-sh',
        'application/x-sqlite3',
        'application/x-tika-msoffice',
        'application/zip',
        'image/gif',
        'image/png',
        'image/tiff',
        'image/vnd.microsoft.icon',
        'message/news',
        'multipart/appledouble',
        'text/css',
        'text/csv',
        'text/html',
        'text/html; charset=utf-8',
        'text/plain',
        'text/tab-separated-values',
        'text/x-matlab',
        'text/xml',
        'text/x-python',
        'video/quicktime',
    ]
    content_type = django_filters.MultipleChoiceFilter(
        choices=zip(content_type_choices, content_type_choices), method='filter_content_type')

    tag = django_filters.CharFilter(method='filter_tag')

    def filter_tag(self, queryset, value):
        if not value:
            return queryset
        return queryset.filter(primary__tags__tag__id=value)

    def filter_content_type(self, queryset, name, value):
        if not value:
            return queryset
        return queryset.filter(Q(content_relations__content_type__in=value)).distinct('id')

    def lookup_name_in_parts(self, queryset, name, value):
        q = Q()
        for part in value.split():
            q &= Q(primary__name__icontains=part)
        return queryset.filter(q)

    def lookup_using_name_index(self, queryset, name, value):
        return queryset.filter(primary__name_index__plain_tsquery=value)

    o = django_filters.OrderingFilter(
        # tuple-mapping retains order
        fields=(
            ('primary__name', 'name'),
            ('primary__entity_type', 'type'),
        ),

        field_labels={
            'name': 'Name',
            'type': 'Type',
        }
    )

    class Meta:
        model = Resource
        fields = ['name', 'entity_type', 'content', 'created_by', 'part_of']
        strict = 'STRICTNESS.IGNORE'
Esempio n. 12
0
class IPAddressFilterSet(
    BaseFilterSet,
    TenancyFilterSet,
    StatusModelFilterSetMixin,
    CustomFieldModelFilterSet,
    CreatedUpdatedFilterSet,
):
    q = django_filters.CharFilter(
        method="search",
        label="Search",
    )
    family = django_filters.NumberFilter(
        method="filter_ip_family",
        label="Family",
    )
    parent = django_filters.CharFilter(
        method="search_by_parent",
        label="Parent prefix",
    )
    address = MultiValueCharFilter(
        method="filter_address",
        label="Address",
    )
    mask_length = django_filters.NumberFilter(
        method="filter_mask_length",
        label="Mask length",
    )
    vrf_id = django_filters.ModelMultipleChoiceFilter(
        queryset=VRF.objects.all(),
        label="VRF",
    )
    vrf = django_filters.ModelMultipleChoiceFilter(
        field_name="vrf__rd",
        queryset=VRF.objects.all(),
        to_field_name="rd",
        label="VRF (RD)",
    )
    present_in_vrf_id = django_filters.ModelChoiceFilter(
        queryset=VRF.objects.all(), method="filter_present_in_vrf", label="VRF"
    )
    present_in_vrf = django_filters.ModelChoiceFilter(
        queryset=VRF.objects.all(),
        method="filter_present_in_vrf",
        to_field_name="rd",
        label="VRF (RD)",
    )
    device = MultiValueCharFilter(
        method="filter_device",
        field_name="name",
        label="Device (name)",
    )
    device_id = MultiValueCharFilter(
        method="filter_device",
        field_name="pk",
        label="Device (ID)",
    )
    virtual_machine = MultiValueCharFilter(
        method="filter_virtual_machine",
        field_name="name",
        label="Virtual machine (name)",
    )
    virtual_machine_id = MultiValueCharFilter(
        method="filter_virtual_machine",
        field_name="pk",
        label="Virtual machine (ID)",
    )
    interface = django_filters.ModelMultipleChoiceFilter(
        field_name="interface__name",
        queryset=Interface.objects.all(),
        to_field_name="name",
        label="Interface (name)",
    )
    interface_id = django_filters.ModelMultipleChoiceFilter(
        field_name="interface",
        queryset=Interface.objects.all(),
        label="Interface (ID)",
    )
    vminterface = django_filters.ModelMultipleChoiceFilter(
        field_name="vminterface__name",
        queryset=VMInterface.objects.all(),
        to_field_name="name",
        label="VM interface (name)",
    )
    vminterface_id = django_filters.ModelMultipleChoiceFilter(
        field_name="vminterface",
        queryset=VMInterface.objects.all(),
        label="VM interface (ID)",
    )
    assigned_to_interface = django_filters.BooleanFilter(
        method="_assigned_to_interface",
        label="Is assigned to an interface",
    )
    role = django_filters.MultipleChoiceFilter(choices=IPAddressRoleChoices)
    tag = TagFilter()

    class Meta:
        model = IPAddress
        fields = ["id", "dns_name"]

    def search(self, queryset, name, value):
        return queryset.string_search(value)

    def search_by_parent(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        try:
            query = netaddr.IPNetwork(value.strip()).cidr
            return queryset.net_host_contained(query)
        except (AddrFormatError, ValueError):
            return queryset.none()

    def filter_address(self, queryset, name, value):
        try:
            return queryset.net_in(value)
        except ValidationError:
            return queryset.none()

    def filter_mask_length(self, queryset, name, value):
        if not value:
            return queryset
        return queryset.filter(prefix_length=value)

    def filter_present_in_vrf(self, queryset, name, vrf):
        if vrf is None:
            return queryset.none
        return queryset.filter(Q(vrf=vrf) | Q(vrf__export_targets__in=vrf.import_targets.all()))

    def filter_ip_family(self, queryset, name, value):
        return queryset.ip_family(value)

    def filter_device(self, queryset, name, value):
        devices = Device.objects.filter(**{"{}__in".format(name): value})
        if not devices.exists():
            return queryset.none()
        interface_ids = []
        for device in devices:
            interface_ids.extend(device.vc_interfaces.values_list("id", flat=True))
        return queryset.filter(interface__in=interface_ids)

    def filter_virtual_machine(self, queryset, name, value):
        virtual_machines = VirtualMachine.objects.filter(**{"{}__in".format(name): value})
        if not virtual_machines.exists():
            return queryset.none()
        interface_ids = []
        for vm in virtual_machines:
            interface_ids.extend(vm.interfaces.values_list("id", flat=True))
        return queryset.filter(vminterface__in=interface_ids)

    def _assigned_to_interface(self, queryset, name, value):
        return queryset.exclude(assigned_object_id__isnull=value)
Esempio n. 13
0
class Reg02MaininfoFilter(filters.FilterSet):
    regdate = filters.DateFromToRangeFilter(widget=filters.widgets.RangeWidget(
        attrs={'class': 'datepicker'}))
    farmername = filters.CharFilter(label='Farmername Auto Search',
                                    lookup_expr='icontains')
    farmermobile = filters.CharFilter(lookup_expr='icontains')
    hhhname = filters.CharFilter(lookup_expr='icontains')
    hhhmobile = filters.CharFilter(lookup_expr='icontains')
    #nmale0to5 = filters.NumberFilter(
    #    widget=widgets.NumberInput(
    #        attrs={'min':0,'max':5}
    #    )
    #)
    animcatowned = filters.MultipleChoiceFilter(
        label='Animal categories owned at farm',
        choices=constants.ANIMAL_CATEGORIES,
        method='filter_animal_categories',
        help_text='Hold CTRL button to select multiple entries')
    hhproblems = filters.MultipleChoiceFilter(
        label='House Hold Problem',
        choices=constants.HOUSE_HOLD_PROBLEMS,
        method='filter_household_problems',
        help_text='Hold CTRL button to select multiple entriess')
    hhproblemsoth = filters.CharFilter(
        label='Other House Hold Problem',
        lookup_expr='icontains',
    )

    #animcatowned_exact = filters.MultipleChoiceFilter(
    #    label='Animal categories exactly owned at farm',
    #    choices=constants.ANIMAL_CATEGORIES,
    #    method='filter_exact_animal_categories',
    #    help_text='Hold CTRL button to select multiple entries'
    #)

    class Meta:
        model = Reg02Maininfo
        #fields = ('regdate', 'farmername', 'farmermobile', 'hhhname', 'hhhmobile','hhhgender',
        #          'hh_district', 'farmerhhhead',
        #         )
        exclude = ('surveyid', 'deviceid', 'originid', 'icow', 'rowuuid',
                   'start_time', 'end_time', 'farmerhhhead', 'nmale0to5',
                   'nfem0to5', 'nmale6to14', 'nfem6to14', 'nmale15to64',
                   'nmaleo65', 'nfemo65', 'nfem15to64', 'gpsloc',
                   'welcomesent', 'apologysent', 'inpaidbundle',
                   'inadggbundle')
        form = OptionsForm

    def filter_animal_categories(self, queryset, name, value):
        option = self.data['options']
        if option == 'e':
            items = [
                item.pk for item in queryset
                if set(value) == set(item.animals_categories_numbers)
            ]
        elif option == 'a':
            items = [
                item.pk for item in queryset
                if set(value).issubset(item.animals_categories_numbers)
            ]
        elif option == 'o':
            items = []
            for item in queryset:
                for el in value:
                    if el in item.animals_categories_numbers:
                        items.append(item.pk)
        return queryset.filter(pk__in=items)

    def filter_household_problems(self, queryset, name, value):
        option = self.data['options']
        if option == 'e':
            items = [
                item.pk for item in queryset
                if set(value) == set(item.house_hold_problem_numbers)
            ]
        elif option == 'a':
            items = [
                item.pk for item in queryset
                if set(value).issubset(item.house_hold_problem_numbers)
            ]
        elif option == 'o':
            items = []
            for item in queryset:
                for el in value:
                    if el in item.house_hold_problem_numbers:
                        items.append(item.pk)
        return queryset.filter(pk__in=items)
Esempio n. 14
0
class VirtualMachineFilter(CustomFieldFilterSet):
    id__in = NumericInFilter(name='id', lookup_expr='in')
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    status = django_filters.MultipleChoiceFilter(choices=STATUS_CHOICES)
    cluster_group_id = django_filters.ModelMultipleChoiceFilter(
        name='cluster__group',
        queryset=ClusterGroup.objects.all(),
        label='Cluster group (ID)',
    )
    cluster_group = django_filters.ModelMultipleChoiceFilter(
        name='cluster__group__slug',
        queryset=ClusterGroup.objects.all(),
        to_field_name='slug',
        label='Cluster group (slug)',
    )
    cluster_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Cluster.objects.all(),
        label='Cluster (ID)',
    )
    role_id = django_filters.ModelMultipleChoiceFilter(
        queryset=DeviceRole.objects.all(),
        label='Role (ID)',
    )
    role = django_filters.ModelMultipleChoiceFilter(
        name='role__slug',
        queryset=DeviceRole.objects.all(),
        to_field_name='slug',
        label='Role (slug)',
    )
    tenant_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Tenant.objects.all(),
        label='Tenant (ID)',
    )
    tenant = django_filters.ModelMultipleChoiceFilter(
        name='tenant__slug',
        queryset=Tenant.objects.all(),
        to_field_name='slug',
        label='Tenant (slug)',
    )
    platform_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Platform.objects.all(),
        label='Platform (ID)',
    )
    platform = django_filters.ModelMultipleChoiceFilter(
        name='platform__slug',
        queryset=Platform.objects.all(),
        to_field_name='slug',
        label='Platform (slug)',
    )

    class Meta:
        model = VirtualMachine
        fields = ['name', 'cluster']

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        return queryset.filter(
            Q(name__icontains=value) | Q(comments__icontains=value))
Esempio n. 15
0
class InterfaceFilter(django_filters.FilterSet):
    """
    Not using DeviceComponentFilterSet for Interfaces because we need to check for VirtualChassis membership.
    """
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    device = MultiValueCharFilter(
        method='filter_device',
        field_name='name',
        label='Device',
    )
    device_id = MultiValueNumberFilter(
        method='filter_device_id',
        field_name='pk',
        label='Device (ID)',
    )
    cabled = django_filters.BooleanFilter(field_name='cable',
                                          lookup_expr='isnull',
                                          exclude=True)
    kind = django_filters.CharFilter(
        method='filter_kind',
        label='Kind of interface',
    )
    lag_id = django_filters.ModelMultipleChoiceFilter(
        field_name='lag',
        queryset=Interface.objects.all(),
        label='LAG interface (ID)',
    )
    mac_address = MultiValueMACAddressFilter()
    tag = TagFilter()
    vlan_id = django_filters.CharFilter(method='filter_vlan_id',
                                        label='Assigned VLAN')
    vlan = django_filters.CharFilter(method='filter_vlan',
                                     label='Assigned VID')
    type = django_filters.MultipleChoiceFilter(choices=IFACE_TYPE_CHOICES,
                                               null_value=None)

    class Meta:
        model = Interface
        fields = [
            'id', 'name', 'connection_status', 'type', 'enabled', 'mtu',
            'mgmt_only', 'mode', 'description'
        ]

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        return queryset.filter(
            Q(name__icontains=value)
            | Q(description__icontains=value)).distinct()

    def filter_device(self, queryset, name, value):
        try:
            devices = Device.objects.filter(**{'{}__in'.format(name): value})
            vc_interface_ids = []
            for device in devices:
                vc_interface_ids.extend(
                    device.vc_interfaces.values_list('id', flat=True))
            return queryset.filter(pk__in=vc_interface_ids)
        except Device.DoesNotExist:
            return queryset.none()

    def filter_device_id(self, queryset, name, id_list):
        # Include interfaces belonging to peer virtual chassis members
        vc_interface_ids = []
        try:
            devices = Device.objects.filter(pk__in=id_list)
            for device in devices:
                vc_interface_ids += device.vc_interfaces.values_list('id',
                                                                     flat=True)
            return queryset.filter(pk__in=vc_interface_ids)
        except Device.DoesNotExist:
            return queryset.none()

    def filter_vlan_id(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        return queryset.filter(
            Q(untagged_vlan_id=value) | Q(tagged_vlans=value))

    def filter_vlan(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        return queryset.filter(
            Q(untagged_vlan_id__vid=value) | Q(tagged_vlans__vid=value))

    def filter_kind(self, queryset, name, value):
        value = value.strip().lower()
        return {
            'physical': queryset.exclude(type__in=NONCONNECTABLE_IFACE_TYPES),
            'virtual': queryset.filter(type__in=VIRTUAL_IFACE_TYPES),
            'wireless': queryset.filter(type__in=WIRELESS_IFACE_TYPES),
        }.get(value, queryset.none())
Esempio n. 16
0
class VLANFilterSet(BaseFilterSet, TenancyFilterSet, CustomFieldFilterSet,
                    CreatedUpdatedFilterSet):
    id__in = NumericInFilter(field_name='id', lookup_expr='in')
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    region_id = TreeNodeMultipleChoiceFilter(
        queryset=Region.objects.all(),
        field_name='site__region',
        lookup_expr='in',
        label='Region (ID)',
    )
    region = TreeNodeMultipleChoiceFilter(
        queryset=Region.objects.all(),
        field_name='site__region',
        lookup_expr='in',
        to_field_name='slug',
        label='Region (slug)',
    )
    site_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Site.objects.all(),
        label='Site (ID)',
    )
    site = django_filters.ModelMultipleChoiceFilter(
        field_name='site__slug',
        queryset=Site.objects.all(),
        to_field_name='slug',
        label='Site (slug)',
    )
    group_id = django_filters.ModelMultipleChoiceFilter(
        queryset=VLANGroup.objects.all(),
        label='Group (ID)',
    )
    group = django_filters.ModelMultipleChoiceFilter(
        field_name='group__slug',
        queryset=VLANGroup.objects.all(),
        to_field_name='slug',
        label='Group',
    )
    role_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Role.objects.all(),
        label='Role (ID)',
    )
    role = django_filters.ModelMultipleChoiceFilter(
        field_name='role__slug',
        queryset=Role.objects.all(),
        to_field_name='slug',
        label='Role (slug)',
    )
    status = django_filters.MultipleChoiceFilter(choices=VLANStatusChoices,
                                                 null_value=None)
    tag = TagFilter()

    class Meta:
        model = VLAN
        fields = ['vid', 'name']

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        qs_filter = Q(name__icontains=value) | Q(description__icontains=value)
        try:
            qs_filter |= Q(vid=int(value.strip()))
        except ValueError:
            pass
        return queryset.filter(qs_filter)
Esempio n. 17
0
class IPAddressFilter(CustomFieldFilterSet, django_filters.FilterSet):
    id__in = NumericInFilter(name='id', lookup_expr='in')
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    parent = django_filters.CharFilter(
        method='search_by_parent',
        label='Parent prefix',
    )
    mask_length = django_filters.NumberFilter(
        method='filter_mask_length',
        label='Mask length',
    )
    vrf_id = django_filters.ModelMultipleChoiceFilter(
        queryset=VRF.objects.all(),
        label='VRF',
    )
    vrf = django_filters.ModelMultipleChoiceFilter(
        name='vrf__rd',
        queryset=VRF.objects.all(),
        to_field_name='rd',
        label='VRF (RD)',
    )
    tenant_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Tenant.objects.all(),
        label='Tenant (ID)',
    )
    tenant = django_filters.ModelMultipleChoiceFilter(
        name='tenant__slug',
        queryset=Tenant.objects.all(),
        to_field_name='slug',
        label='Tenant (slug)',
    )
    device_id = django_filters.ModelMultipleChoiceFilter(
        name='interface__device',
        queryset=Device.objects.all(),
        label='Device (ID)',
    )
    device = django_filters.ModelMultipleChoiceFilter(
        name='interface__device__name',
        queryset=Device.objects.all(),
        to_field_name='name',
        label='Device (name)',
    )
    virtual_machine_id = django_filters.ModelMultipleChoiceFilter(
        name='interface__virtual_machine',
        queryset=VirtualMachine.objects.all(),
        label='Virtual machine (ID)',
    )
    virtual_machine = django_filters.ModelMultipleChoiceFilter(
        name='interface__virtual_machine__name',
        queryset=VirtualMachine.objects.all(),
        to_field_name='name',
        label='Virtual machine (name)',
    )
    interface_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Interface.objects.all(),
        label='Interface (ID)',
    )
    status = django_filters.MultipleChoiceFilter(
        choices=IPADDRESS_STATUS_CHOICES,
        null_value=None
    )
    role = django_filters.MultipleChoiceFilter(
        choices=IPADDRESS_ROLE_CHOICES
    )

    class Meta:
        model = IPAddress
        fields = ['family']

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        qs_filter = (
            Q(description__icontains=value) |
            Q(address__istartswith=value)
        )
        return queryset.filter(qs_filter)

    def search_by_parent(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        try:
            query = str(netaddr.IPNetwork(value.strip()).cidr)
            return queryset.filter(address__net_host_contained=query)
        except (AddrFormatError, ValueError):
            return queryset.none()

    def filter_mask_length(self, queryset, name, value):
        if not value:
            return queryset
        return queryset.filter(address__net_mask_length=value)
class LastChangedFilter(django_filters.FilterSet):
    telescope_class = django_filters.MultipleChoiceFilter(
        choices=configdb.get_telescope_class_tuples())
Esempio n. 19
0
class MultipleChoiceFieldFilterSet(django_filters.FilterSet):
    is_featured = django_filters.MultipleChoiceFilter(
        label="Is featured", choices=[(0, "Featured"), (1, "Not featured")]
    )
Esempio n. 20
0
class DriverRecordFilter(RecordFilter):
    """Extend RecordFilter to allow filtering on created date."""
    created_min = django_filters.IsoDateTimeFilter(name="created",
                                                   lookup_expr='gte')
    created_max = django_filters.IsoDateTimeFilter(name="created",
                                                   lookup_expr='lte')
    created_by = django_filters.Filter(field_name='created_by',
                                       method='filter_created_by')
    weather = django_filters.MultipleChoiceFilter(choices=WEATHER_CHOICES)
    archived = django_filters.BooleanFilter(name='archived')
    outside_boundary = django_filters.Filter(field_name='geom',
                                             method='filter_outside_boundary')

    def __init__(self, data=None, *args, **kwargs):
        # if filterset is bound, use initial values as defaults
        if data is not None:
            # get a mutable copy of the QueryDict
            data = data.copy()

            if not data.get('archived'):
                data['archived'] = "False"

        super(DriverRecordFilter, self).__init__(data, *args, **kwargs)

    def filter_outside_boundary(self, queryset, field_name, boundary_uuid):
        """Filter records that fall outside the specified boundary."""
        redis_conn = get_redis_connection('boundaries')
        bounds_hexewkb = redis_conn.get(boundary_uuid)
        one_month_seconds = 30 * 24 * 60 * 60
        if bounds_hexewkb is None:
            try:
                boundary = Boundary.objects.get(pk=boundary_uuid)
            except ValidationError:
                raise ParseError('outside_boundary was passed an invalid UUID')
            except Boundary.DoesNotExist:
                raise NotFound('Boundary not found')
            unioned_bounds = boundary.polygons.aggregate(
                all_polys=Union('geom'))['all_polys']
            # Full resolution is very slow, so simplify down to roughly 100m (DRIVER is in lat/lon).
            unioned_bounds = unioned_bounds.simplify(tolerance=0.001,
                                                     preserve_topology=True)
            redis_conn.set(boundary_uuid, str(unioned_bounds.hexewkb),
                           one_month_seconds)
        else:
            redis_conn.expire(boundary_uuid, one_month_seconds)
            unioned_bounds = GEOSGeometry(bounds_hexewkb)
        return queryset.exclude(geom__intersects=unioned_bounds)

    def filter_created_by(self, queryset, name, value):
        """ Filter records by the email or username of the creating user."""
        if not is_admin_or_writer(self.request.user):
            # Public users cannot filter by creating user
            return queryset

        return queryset.filter(
            Q(recordauditlogentry__action=RecordAuditLogEntry.ActionTypes.
              CREATE) & (Q(recordauditlogentry__username=value)
                         | Q(recordauditlogentry__user__email=value)))

    class Meta:
        model = DriverRecord
        fields = ['created_min', 'created_max']
Esempio n. 21
0
class VirtualMachineFilter(TenancyFilterSet, CustomFieldFilterSet):
    id__in = NumericInFilter(field_name='id', lookup_expr='in')
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    status = django_filters.MultipleChoiceFilter(choices=VM_STATUS_CHOICES,
                                                 null_value=None)
    cluster_group_id = django_filters.ModelMultipleChoiceFilter(
        field_name='cluster__group',
        queryset=ClusterGroup.objects.all(),
        label='Cluster group (ID)',
    )
    cluster_group = django_filters.ModelMultipleChoiceFilter(
        field_name='cluster__group__slug',
        queryset=ClusterGroup.objects.all(),
        to_field_name='slug',
        label='Cluster group (slug)',
    )
    cluster_type_id = django_filters.ModelMultipleChoiceFilter(
        field_name='cluster__type',
        queryset=ClusterType.objects.all(),
        label='Cluster type (ID)',
    )
    cluster_type = django_filters.ModelMultipleChoiceFilter(
        field_name='cluster__type__slug',
        queryset=ClusterType.objects.all(),
        to_field_name='slug',
        label='Cluster type (slug)',
    )
    cluster_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Cluster.objects.all(),
        label='Cluster (ID)',
    )
    region_id = TreeNodeMultipleChoiceFilter(
        queryset=Region.objects.all(),
        field_name='cluster__site__region__in',
        label='Region (ID)',
    )
    region = TreeNodeMultipleChoiceFilter(
        queryset=Region.objects.all(),
        field_name='cluster__site__region__in',
        to_field_name='slug',
        label='Region (slug)',
    )
    site_id = django_filters.ModelMultipleChoiceFilter(
        field_name='cluster__site',
        queryset=Site.objects.all(),
        label='Site (ID)',
    )
    site = django_filters.ModelMultipleChoiceFilter(
        field_name='cluster__site__slug',
        queryset=Site.objects.all(),
        to_field_name='slug',
        label='Site (slug)',
    )
    role_id = django_filters.ModelMultipleChoiceFilter(
        queryset=DeviceRole.objects.all(),
        label='Role (ID)',
    )
    role = django_filters.ModelMultipleChoiceFilter(
        field_name='role__slug',
        queryset=DeviceRole.objects.all(),
        to_field_name='slug',
        label='Role (slug)',
    )
    platform_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Platform.objects.all(),
        label='Platform (ID)',
    )
    platform = django_filters.ModelMultipleChoiceFilter(
        field_name='platform__slug',
        queryset=Platform.objects.all(),
        to_field_name='slug',
        label='Platform (slug)',
    )
    mac_address = MultiValueMACAddressFilter(
        field_name='interfaces__mac_address',
        label='MAC address',
    )
    tag = TagFilter()

    class Meta:
        model = VirtualMachine
        fields = ['id', 'name', 'cluster', 'vcpus', 'memory', 'disk']

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        return queryset.filter(
            Q(name__icontains=value) | Q(comments__icontains=value))
Esempio n. 22
0
class MonsterInstanceFilter(django_filters.FilterSet):
    monster = django_filters.NumberFilter()
    monster__name = django_filters.CharFilter(method='filter_monster__name')
    tags__pk = django_filters.ModelMultipleChoiceFilter(
        queryset=MonsterTag.objects.all(), to_field_name='pk', conjoined=True)
    monster__element = django_filters.MultipleChoiceFilter(
        choices=Monster.ELEMENT_CHOICES)
    monster__archetype = django_filters.MultipleChoiceFilter(
        choices=Monster.TYPE_CHOICES)
    monster__awaken_level = django_filters.MultipleChoiceFilter(
        choices=Monster.AWAKEN_CHOICES)
    priority = django_filters.MultipleChoiceFilter(
        choices=MonsterInstance.PRIORITY_CHOICES)
    monster__leader_skill__attribute = django_filters.MultipleChoiceFilter(
        choices=LeaderSkill.ATTRIBUTE_CHOICES)
    monster__leader_skill__area = django_filters.MultipleChoiceFilter(
        choices=LeaderSkill.AREA_CHOICES)
    monster__skills__scaling_stats__pk = django_filters.ModelMultipleChoiceFilter(
        queryset=ScalingStat.objects.all(), to_field_name='pk', conjoined=True)
    monster__skills__skill_effect__pk = django_filters.ModelMultipleChoiceFilter(
        queryset=SkillEffect.objects.all(),
        method='filter_monster__skills__skill_effect__pk')
    effects_logic = django_filters.BooleanFilter(method='filter_effects_logic')
    monster__fusion_food = django_filters.BooleanFilter(
        method='filter_monster__fusion_food')

    class Meta:
        model = MonsterInstance
        fields = {
            'monster': ['exact'],
            'monster__name': ['exact'],
            'tags__pk': ['exact'],
            'stars': ['gte', 'lte'],
            'level': ['gte', 'lte'],
            'monster__element': ['exact'],
            'monster__archetype': ['exact'],
            'priority': ['exact'],
            'monster__awaken_level': ['exact'],
            'monster__leader_skill__attribute': ['exact'],
            'monster__leader_skill__area': ['exact'],
            'monster__skills__skill_effect__pk': ['exact'],
            'monster__skills__scaling_stats__pk': ['exact'],
            'effects_logic': ['exact'],
            'fodder': ['exact'],
            'in_storage': ['exact'],
            'monster__fusion_food': ['exact'],
        }

    def filter_monster__name(self, queryset, name, value):
        if value:
            return queryset.filter(monster__name__istartswith=value)
        else:
            return queryset

    def filter_monster__fusion_food(self, queryset, name, value):
        if value:
            return queryset.filter(monster__fusion_food=True).exclude(
                ignore_for_fusion=True)
        else:
            return queryset.filter(
                Q(monster__fusion_food=False) | Q(ignore_for_fusion=True))

    def filter_monster__skills__skill_effect__pk(self, queryset, name, value):
        old_filtering = self.form.cleaned_data.get('effects_logic', False)
        stat_scaling = self.form.cleaned_data.get(
            'monster__skills__scaling_stats__pk', [])

        if old_filtering:
            # Filter if any skill on the monster has the designated fields
            for effect in value:
                queryset = queryset.filter(
                    monster__skills__skill_effect=effect)

            for pk in stat_scaling:
                queryset = queryset.filter(monster__skills__scaling_stats=pk)

            return queryset.distinct()

        else:
            # Filter effects based on effects of each individual skill. This ensures a monster will not show up unless it has
            # the desired effects on the same skill rather than across any skills.

            skills = Skill.objects.all()

            for effect in value:
                skills = skills.filter(skill_effect=effect)

            for pk in stat_scaling:
                skills = skills.filter(scaling_stats=pk)

            return queryset.filter(monster__skills__in=skills).distinct()

    def filter_effects_logic(self, queryset, name, value):
        # This field is just used to alter the logic of skill effect filter and is used in filter_monster__skills__skill_effect__pk()
        return queryset
Esempio n. 23
0
class RackFilterSet(NautobotFilterSet, TenancyFilterSet,
                    StatusModelFilterSetMixin):
    q = django_filters.CharFilter(
        method="search",
        label="Search",
    )
    region_id = TreeNodeMultipleChoiceFilter(
        queryset=Region.objects.all(),
        field_name="site__region",
        lookup_expr="in",
        label="Region (ID)",
    )
    region = TreeNodeMultipleChoiceFilter(
        queryset=Region.objects.all(),
        field_name="site__region",
        lookup_expr="in",
        to_field_name="slug",
        label="Region (slug)",
    )
    site_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Site.objects.all(),
        label="Site (ID)",
    )
    site = django_filters.ModelMultipleChoiceFilter(
        field_name="site__slug",
        queryset=Site.objects.all(),
        to_field_name="slug",
        label="Site (slug)",
    )
    group_id = TreeNodeMultipleChoiceFilter(
        queryset=RackGroup.objects.all(),
        field_name="group",
        lookup_expr="in",
        label="Rack group (ID)",
    )
    group = TreeNodeMultipleChoiceFilter(
        queryset=RackGroup.objects.all(),
        field_name="group",
        lookup_expr="in",
        to_field_name="slug",
        label="Rack group (slug)",
    )
    type = django_filters.MultipleChoiceFilter(choices=RackTypeChoices)
    width = django_filters.MultipleChoiceFilter(choices=RackWidthChoices)
    role_id = django_filters.ModelMultipleChoiceFilter(
        queryset=RackRole.objects.all(),
        label="Role (ID)",
    )
    role = django_filters.ModelMultipleChoiceFilter(
        field_name="role__slug",
        queryset=RackRole.objects.all(),
        to_field_name="slug",
        label="Role (slug)",
    )
    serial = django_filters.CharFilter(lookup_expr="iexact")
    tag = TagFilter()

    class Meta:
        model = Rack
        fields = [
            "id",
            "name",
            "facility_id",
            "asset_tag",
            "u_height",
            "desc_units",
            "outer_width",
            "outer_depth",
            "outer_unit",
        ]

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        return queryset.filter(
            Q(name__icontains=value)
            | Q(facility_id__icontains=value)
            | Q(serial__icontains=value.strip())
            | Q(asset_tag__icontains=value.strip())
            | Q(comments__icontains=value))
Esempio n. 24
0
class PersonFilter(django_filters.FilterSet):
    city_of_birth_text = 'city of birth'
    city_of_death_text = 'city of death'
    city_of_residence_text = 'city of residence'
    place_help = ' <span class="glyphicon glyphicon-question-sign" ' \
                 'title="When known, the MEDIATE database lists the {} of Persons. ' \
                 'In other cases, it lists a region, county, or other geographic entity."></span>'

    short_name = django_filters.Filter(method='short_name_filter')
    surname = django_filters.Filter(method='surname_filter')
    sex = django_filters.MultipleChoiceFilter(
        choices=Person.SEX_CHOICES,
        widget=Select2MultipleWidget(
            attrs={'data-placeholder': "Select multiple"}, ))
    city_of_birth = django_filters.ModelMultipleChoiceFilter(
        label=mark_safe(
            _("Place of birth") + place_help.format(city_of_birth_text)),
        queryset=Place.objects.all(),
        widget=Select2MultipleWidget(
            attrs={'data-placeholder': "Select multiple"}, ))
    country_of_birth = django_filters.ModelMultipleChoiceFilter(
        label="Country of birth",
        queryset=Country.objects.all(),
        widget=Select2MultipleWidget(
            attrs={'data-placeholder': "Select multiple"}, ),
        field_name='city_of_birth__country',
        lookup_expr='in')
    city_of_death = django_filters.ModelMultipleChoiceFilter(
        label=mark_safe(
            _("Place of death") + place_help.format(city_of_death_text)),
        queryset=Place.objects.all(),
        widget=Select2MultipleWidget(
            attrs={'data-placeholder': "Select multiple"}, ))
    country_of_death = django_filters.ModelMultipleChoiceFilter(
        label="Country of death",
        queryset=Country.objects.all(),
        widget=Select2MultipleWidget(
            attrs={'data-placeholder': "Select multiple"}, ),
        field_name='city_of_death__country',
        lookup_expr='in')
    profession = django_filters.ModelMultipleChoiceFilter(
        label="Profession",
        queryset=Profession.objects.all(),
        widget=Select2MultipleWidget(
            attrs={'data-placeholder': "Select multiple"}, ),
        field_name='personprofession__profession',
        lookup_expr='in')
    collection_roles = django_filters.ModelMultipleChoiceFilter(
        label="Collection roles",
        queryset=PersonCollectionRelationRole.objects.all(),
        widget=Select2MultipleWidget(
            attrs={'data-placeholder': "Select multiple"}, ),
        field_name='personcollectionrelation__role',
        lookup_expr='in')
    item_roles = django_filters.ModelMultipleChoiceFilter(
        label="Item roles",
        queryset=PersonItemRelationRole.objects.all(),
        widget=Select2MultipleWidget(
            attrs={'data-placeholder': "Select multiple"}, ),
        field_name='personitemrelation__role',
        lookup_expr='in')
    work_author = django_filters.BooleanFilter(label="Work author",
                                               field_name='works',
                                               lookup_expr='isnull',
                                               exclude=True)
    publisher = django_filters.BooleanFilter(label="Publisher",
                                             field_name='publisher',
                                             lookup_expr='isnull',
                                             exclude=True)
    religious_affiliation = django_filters.ModelMultipleChoiceFilter(
        label="Religious affiliation",
        queryset=Religion.objects.all(),
        widget=Select2MultipleWidget(
            attrs={'data-placeholder': "Select multiple"}, ),
        field_name='religiousaffiliation__religion',
        lookup_expr='in')
    city_of_residence = django_filters.ModelMultipleChoiceFilter(
        label=mark_safe(
            _("Place of residence") +
            place_help.format(city_of_residence_text)),
        queryset=Place.objects.all(),
        widget=Select2MultipleWidget(
            attrs={'data-placeholder': "Select multiple"}, ),
        field_name='residence__place',
        lookup_expr='in')
    country_of_residence = django_filters.ModelMultipleChoiceFilter(
        label="Country of residence",
        queryset=Country.objects.all(),
        widget=Select2MultipleWidget(
            attrs={'data-placeholder': "Select multiple"}, ),
        field_name='residence__place__country',
        lookup_expr='in')
    related_to = django_filters.ModelMultipleChoiceFilter(
        label="Related to",
        queryset=Person.objects.all(),
        widget=Select2MultipleWidget(
            attrs={'data-placeholder': "Select multiple"}, ),
        method='related_to_filter')
    nature_of_relation = django_filters.ModelMultipleChoiceFilter(
        label="Person relation types",
        queryset=PersonPersonRelationType.objects.all(),
        widget=Select2MultipleWidget(
            attrs={'data-placeholder': "Select multiple"}, ),
        method='nature_of_relation_filter')

    class Meta:
        model = Person
        fields = [
            'short_name', 'surname', 'sex', 'city_of_birth',
            'country_of_birth', 'date_of_birth', 'city_of_death',
            'country_of_death', 'date_of_death', 'profession',
            'collection_roles', 'item_roles', 'work_author', 'publisher',
            'religious_affiliation', 'city_of_residence',
            'country_of_residence', 'related_to', 'nature_of_relation'
        ]

    def short_name_filter(self, queryset, name, value):
        from django.db.models import Q
        if value:
            short_name_q = Q(short_name__icontains=value)
            alternative_short_name_q = Q(
                alternative_names__short_name__icontains=value)
            return queryset.filter(short_name_q | alternative_short_name_q)
        return queryset

    def surname_filter(self, queryset, name, value):
        from django.db.models import Q
        if value:
            surname_q = Q(surname__icontains=value)
            alternative_surname_q = Q(
                alternative_names__surname__icontains=value)
            return queryset.filter(surname_q | alternative_surname_q)
        return queryset

    def viaf_id_filter(self, queryset, name, value):
        if value:
            return queryset.filter(viaf_id=ViafAPI.uri_base + "/" + value)
        return queryset

    def related_to_filter(self, queryset, name, value):
        if value:
            first_person_query = Q(
                relations_when_first__second_person__in=value)
            second_person_query = Q(
                relations_when_second__first_person__in=value)
            return queryset.filter(first_person_query
                                   | second_person_query).distinct()
        return queryset

    def nature_of_relation_filter(self, queryset, name, value):
        if value:
            first_person_query = Q(relations_when_first__type__in=value)
            second_person_query = Q(relations_when_second__type__in=value)
            return queryset.filter(first_person_query
                                   | second_person_query).distinct()
        return queryset
Esempio n. 25
0
class PrefixFilter(TenancyFilterSet, CustomFieldFilterSet):
    id__in = NumericInFilter(
        field_name='id',
        lookup_expr='in'
    )
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    prefix = django_filters.CharFilter(
        method='filter_prefix',
        label='Prefix',
    )
    within = django_filters.CharFilter(
        method='search_within',
        label='Within prefix',
    )
    within_include = django_filters.CharFilter(
        method='search_within_include',
        label='Within and including prefix',
    )
    contains = django_filters.CharFilter(
        method='search_contains',
        label='Prefixes which contain this prefix or IP',
    )
    mask_length = django_filters.NumberFilter(
        method='filter_mask_length',
        label='Mask length',
    )
    vrf_id = django_filters.ModelMultipleChoiceFilter(
        queryset=VRF.objects.all(),
        label='VRF',
    )
    vrf = django_filters.ModelMultipleChoiceFilter(
        field_name='vrf__rd',
        queryset=VRF.objects.all(),
        to_field_name='rd',
        label='VRF (RD)',
    )
    site_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Site.objects.all(),
        label='Site (ID)',
    )
    site = django_filters.ModelMultipleChoiceFilter(
        field_name='site__slug',
        queryset=Site.objects.all(),
        to_field_name='slug',
        label='Site (slug)',
    )
    vlan_id = django_filters.ModelMultipleChoiceFilter(
        queryset=VLAN.objects.all(),
        label='VLAN (ID)',
    )
    vlan_vid = django_filters.NumberFilter(
        field_name='vlan__vid',
        label='VLAN number (1-4095)',
    )
    role_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Role.objects.all(),
        label='Role (ID)',
    )
    role = django_filters.ModelMultipleChoiceFilter(
        field_name='role__slug',
        queryset=Role.objects.all(),
        to_field_name='slug',
        label='Role (slug)',
    )
    status = django_filters.MultipleChoiceFilter(
        choices=PREFIX_STATUS_CHOICES,
        null_value=None
    )
    tag = TagFilter()

    class Meta:
        model = Prefix
        fields = ['family', 'is_pool']

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        qs_filter = Q(description__icontains=value)
        try:
            prefix = str(netaddr.IPNetwork(value.strip()).cidr)
            qs_filter |= Q(prefix__net_contains_or_equals=prefix)
        except (AddrFormatError, ValueError):
            pass
        return queryset.filter(qs_filter)

    def filter_prefix(self, queryset, name, value):
        if not value.strip():
            return queryset
        try:
            query = str(netaddr.IPNetwork(value).cidr)
            return queryset.filter(prefix=query)
        except ValidationError:
            return queryset.none()

    def search_within(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        try:
            query = str(netaddr.IPNetwork(value).cidr)
            return queryset.filter(prefix__net_contained=query)
        except (AddrFormatError, ValueError):
            return queryset.none()

    def search_within_include(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        try:
            query = str(netaddr.IPNetwork(value).cidr)
            return queryset.filter(prefix__net_contained_or_equal=query)
        except (AddrFormatError, ValueError):
            return queryset.none()

    def search_contains(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        try:
            # Searching by prefix
            if '/' in value:
                return queryset.filter(prefix__net_contains_or_equals=str(netaddr.IPNetwork(value).cidr))
            # Searching by IP address
            else:
                return queryset.filter(prefix__net_contains=str(netaddr.IPAddress(value)))
        except (AddrFormatError, ValueError):
            return queryset.none()

    def filter_mask_length(self, queryset, name, value):
        if not value:
            return queryset
        return queryset.filter(prefix__net_mask_length=value)
Esempio n. 26
0
class RackFilter(TenancyFilterSet, CustomFieldFilterSet,
                 CreatedUpdatedFilterSet):
    id__in = NumericInFilter(field_name='id', lookup_expr='in')
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    region_id = TreeNodeMultipleChoiceFilter(
        queryset=Region.objects.all(),
        field_name='site__region__in',
        label='Region (ID)',
    )
    region = TreeNodeMultipleChoiceFilter(
        queryset=Region.objects.all(),
        field_name='site__region__in',
        to_field_name='slug',
        label='Region (slug)',
    )
    site_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Site.objects.all(),
        label='Site (ID)',
    )
    site = django_filters.ModelMultipleChoiceFilter(
        field_name='site__slug',
        queryset=Site.objects.all(),
        to_field_name='slug',
        label='Site (slug)',
    )
    group_id = django_filters.ModelMultipleChoiceFilter(
        queryset=RackGroup.objects.all(),
        label='Group (ID)',
    )
    group = django_filters.ModelMultipleChoiceFilter(
        field_name='group__slug',
        queryset=RackGroup.objects.all(),
        to_field_name='slug',
        label='Group',
    )
    status = django_filters.MultipleChoiceFilter(choices=RACK_STATUS_CHOICES,
                                                 null_value=None)
    role_id = django_filters.ModelMultipleChoiceFilter(
        queryset=RackRole.objects.all(),
        label='Role (ID)',
    )
    role = django_filters.ModelMultipleChoiceFilter(
        field_name='role__slug',
        queryset=RackRole.objects.all(),
        to_field_name='slug',
        label='Role (slug)',
    )
    serial = django_filters.CharFilter(lookup_expr='iexact')
    tag = TagFilter()

    class Meta:
        model = Rack
        fields = [
            'id',
            'name',
            'facility_id',
            'asset_tag',
            'type',
            'width',
            'u_height',
            'desc_units',
            'outer_width',
            'outer_depth',
            'outer_unit',
        ]

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        return queryset.filter(
            Q(name__icontains=value) | Q(facility_id__icontains=value)
            | Q(serial__icontains=value.strip())
            | Q(asset_tag__icontains=value.strip())
            | Q(comments__icontains=value))
Esempio n. 27
0
class MultipleChoiceFieldFilterSet(django_filters.FilterSet):
    is_featured = django_filters.MultipleChoiceFilter(label='Is featured',
                                                      choices=[
                                                          (0, 'Featured'),
                                                          (1, 'Not featured')
                                                      ])
Esempio n. 28
0
class DeviceFilter(LocalConfigContextFilter, TenancyFilterSet,
                   CustomFieldFilterSet, CreatedUpdatedFilterSet):
    id__in = NumericInFilter(field_name='id', lookup_expr='in')
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    manufacturer_id = django_filters.ModelMultipleChoiceFilter(
        field_name='device_type__manufacturer',
        queryset=Manufacturer.objects.all(),
        label='Manufacturer (ID)',
    )
    manufacturer = django_filters.ModelMultipleChoiceFilter(
        field_name='device_type__manufacturer__slug',
        queryset=Manufacturer.objects.all(),
        to_field_name='slug',
        label='Manufacturer (slug)',
    )
    device_type_id = django_filters.ModelMultipleChoiceFilter(
        queryset=DeviceType.objects.all(),
        label='Device type (ID)',
    )
    role_id = django_filters.ModelMultipleChoiceFilter(
        field_name='device_role_id',
        queryset=DeviceRole.objects.all(),
        label='Role (ID)',
    )
    role = django_filters.ModelMultipleChoiceFilter(
        field_name='device_role__slug',
        queryset=DeviceRole.objects.all(),
        to_field_name='slug',
        label='Role (slug)',
    )
    platform_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Platform.objects.all(),
        label='Platform (ID)',
    )
    platform = django_filters.ModelMultipleChoiceFilter(
        field_name='platform__slug',
        queryset=Platform.objects.all(),
        to_field_name='slug',
        label='Platform (slug)',
    )
    region_id = TreeNodeMultipleChoiceFilter(
        queryset=Region.objects.all(),
        field_name='site__region__in',
        label='Region (ID)',
    )
    region = TreeNodeMultipleChoiceFilter(
        queryset=Region.objects.all(),
        field_name='site__region__in',
        to_field_name='slug',
        label='Region (slug)',
    )
    site_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Site.objects.all(),
        label='Site (ID)',
    )
    site = django_filters.ModelMultipleChoiceFilter(
        field_name='site__slug',
        queryset=Site.objects.all(),
        to_field_name='slug',
        label='Site name (slug)',
    )
    rack_group_id = django_filters.ModelMultipleChoiceFilter(
        field_name='rack__group',
        queryset=RackGroup.objects.all(),
        label='Rack group (ID)',
    )
    rack_id = django_filters.ModelMultipleChoiceFilter(
        field_name='rack',
        queryset=Rack.objects.all(),
        label='Rack (ID)',
    )
    cluster_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Cluster.objects.all(),
        label='VM cluster (ID)',
    )
    model = django_filters.ModelMultipleChoiceFilter(
        field_name='device_type__slug',
        queryset=DeviceType.objects.all(),
        to_field_name='slug',
        label='Device model (slug)',
    )
    status = django_filters.MultipleChoiceFilter(choices=DEVICE_STATUS_CHOICES,
                                                 null_value=None)
    is_full_depth = django_filters.BooleanFilter(
        field_name='device_type__is_full_depth',
        label='Is full depth',
    )
    mac_address = MultiValueMACAddressFilter(
        field_name='interfaces__mac_address',
        label='MAC address',
    )
    serial = django_filters.CharFilter(lookup_expr='iexact')
    has_primary_ip = django_filters.BooleanFilter(
        method='_has_primary_ip',
        label='Has a primary IP',
    )
    virtual_chassis_id = django_filters.ModelMultipleChoiceFilter(
        field_name='virtual_chassis',
        queryset=VirtualChassis.objects.all(),
        label='Virtual chassis (ID)',
    )
    virtual_chassis_member = django_filters.BooleanFilter(
        method='_virtual_chassis_member', label='Is a virtual chassis member')
    console_ports = django_filters.BooleanFilter(
        method='_console_ports',
        label='Has console ports',
    )
    console_server_ports = django_filters.BooleanFilter(
        method='_console_server_ports',
        label='Has console server ports',
    )
    power_ports = django_filters.BooleanFilter(
        method='_power_ports',
        label='Has power ports',
    )
    power_outlets = django_filters.BooleanFilter(
        method='_power_outlets',
        label='Has power outlets',
    )
    interfaces = django_filters.BooleanFilter(
        method='_interfaces',
        label='Has interfaces',
    )
    pass_through_ports = django_filters.BooleanFilter(
        method='_pass_through_ports',
        label='Has pass-through ports',
    )
    tag = TagFilter()

    class Meta:
        model = Device
        fields = [
            'id', 'name', 'asset_tag', 'face', 'position', 'vc_position',
            'vc_priority'
        ]

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        return queryset.filter(
            Q(name__icontains=value) | Q(serial__icontains=value.strip())
            | Q(inventory_items__serial__icontains=value.strip())
            | Q(asset_tag__icontains=value.strip())
            | Q(comments__icontains=value)).distinct()

    def _has_primary_ip(self, queryset, name, value):
        if value:
            return queryset.filter(
                Q(primary_ip4__isnull=False) | Q(primary_ip6__isnull=False))
        else:
            return queryset.exclude(
                Q(primary_ip4__isnull=False) | Q(primary_ip6__isnull=False))

    def _virtual_chassis_member(self, queryset, name, value):
        return queryset.exclude(virtual_chassis__isnull=value)

    def _console_ports(self, queryset, name, value):
        return queryset.exclude(consoleports__isnull=value)

    def _console_server_ports(self, queryset, name, value):
        return queryset.exclude(consoleserverports__isnull=value)

    def _power_ports(self, queryset, name, value):
        return queryset.exclude(powerports__isnull=value)

    def _power_outlets(self, queryset, name, value):
        return queryset.exclude(poweroutlets__isnull=value)

    def _interfaces(self, queryset, name, value):
        return queryset.exclude(interfaces__isnull=value)

    def _pass_through_ports(self, queryset, name, value):
        return queryset.exclude(frontports__isnull=value,
                                rearports__isnull=value)
Esempio n. 29
0
class ExperimentFilterset(filters.FilterSet):

    search = filters.CharFilter(
        method="filter_search",
        widget=SearchWidget(attrs={
            "class": "form-control",
            "placeholder": "Search Deliveries"
        }),
    )
    type = filters.MultipleChoiceFilter(
        choices=Experiment.TYPE_CHOICES,
        conjoined=False,
        widget=forms.SelectMultiple(attrs={
            "class": "form-control",
            "data-none-selected-text": "All Types"
        }),
    )
    projects = filters.ModelMultipleChoiceFilter(
        queryset=Project.objects.all(),
        null_label="No Projects",
        widget=forms.SelectMultiple(attrs={
            "class": "form-control",
            "data-none-selected-text": "All Projects"
        }),
    )
    status = filters.ChoiceFilter(
        empty_label="All Statuses",
        choices=Experiment.STATUS_CHOICES,
        widget=forms.Select(attrs={"class": "form-control"}),
    )
    firefox_channel = filters.ChoiceFilter(
        empty_label="All Channels",
        choices=Experiment.CHANNEL_CHOICES[1:],
        widget=forms.Select(attrs={"class": "form-control"}),
    )
    firefox_version = filters.ChoiceFilter(
        empty_label="All Versions",
        choices=Experiment.VERSION_CHOICES[1:],
        widget=forms.Select(attrs={"class": "form-control"}),
        method="version_filter",
    )
    owner = filters.ModelChoiceFilter(
        empty_label="All Owners",
        queryset=get_user_model().objects.all().order_by("email"),
        widget=forms.Select(attrs={"class": "form-control"}),
    )
    analysis_owner = filters.ModelChoiceFilter(
        empty_label="All Data Scientists",
        queryset=get_user_model().objects.all().order_by("email"),
        widget=forms.Select(attrs={"class": "form-control"}),
    )

    archived = filters.BooleanFilter(
        label="Show archived deliveries",
        widget=forms.CheckboxInput(),
        method="archived_filter",
    )
    experiment_date_field = filters.ChoiceFilter(
        empty_label="No Date Restriction",
        choices=[
            (Experiment.EXPERIMENT_STARTS, "Delivery Starts"),
            (Experiment.EXPERIMENT_PAUSES, "Delivery Pauses"),
            (Experiment.EXPERIMENT_ENDS, "Delivery Ends"),
        ],
        widget=forms.Select(attrs={"class": "form-control"}),
        method="experiment_date_field_filter",
    )
    date_range = filters.DateFromToRangeFilter(
        method="date_range_filter",
        widget=DateRangeWidget(attrs={
            "type": "date",
            "class": "form-control"
        }),
    )

    in_qa = filters.BooleanFilter(
        label="Show only deliveries in QA",
        widget=forms.CheckboxInput(),
        method="in_qa_filter",
    )

    surveys = filters.BooleanFilter(
        label="Show deliveries with surveys",
        widget=forms.CheckboxInput(),
        method="surveys_filter",
    )

    subscribed = filters.BooleanFilter(
        label="Show subscribed deliveries",
        widget=forms.CheckboxInput(),
        method="subscribed_filter",
    )

    longrunning = filters.BooleanFilter(
        label="Show long-running deliveries",
        widget=forms.CheckboxInput(),
        method="longrunning_filter",
    )

    is_paused = filters.BooleanFilter(
        label="Show enrollment complete deliveries",
        widget=forms.CheckboxInput(),
        method="is_paused_filter",
    )

    completed_results = filters.BooleanFilter(
        label="Show deliveries with results completed",
        widget=forms.CheckboxInput(),
        method="completed_results_filter",
    )

    class Meta:
        model = Experiment
        fields = (
            "search",
            "type",
            "projects",
            "status",
            "firefox_channel",
            "firefox_version",
            "owner",
            "analysis_owner",
            "in_qa",
            "surveys",
            "archived",
            "subscribed",
            "longrunning",
            "is_paused",
            "completed_results",
        )

    def filter_search(self, queryset, name, value):
        vector = SearchVector(
            "name",
            "short_description",
            "owner__email",
            "analysis_owner__email",
            "slug",
            "related_work",
            "addon_experiment_id",
            "pref_name",
            "public_description",
            "objectives",
            "analysis",
            "engineering_owner",
            "bugzilla_id",
            "recipe_slug",
            "data_science_issue_url",
            "feature_bugzilla_url",
        )

        query = SearchQuery(value)

        return (queryset.annotate(
            rank=SearchRank(vector, query),
            search=vector).filter(search=value).order_by("-rank"))

    def archived_filter(self, queryset, name, value):
        if not value:
            return queryset.exclude(archived=True)
        return queryset

    def experiment_date_field_filter(self, queryset, name, value):
        # this custom method isn't doing anything. There has to
        # be a custom method to be able to display the select
        # filter that controls which date range we show
        return queryset

    def version_filter(self, queryset, name, value):
        return queryset.filter(
            Q(firefox_min_version__lte=value, firefox_max_version__gte=value)
            | Q(firefox_min_version=value))

    def date_range_filter(self, queryset, name, value):
        date_type = self.form.cleaned_data["experiment_date_field"]
        if date_type:
            experiment_date_field = {
                Experiment.EXPERIMENT_STARTS: "start_date",
                Experiment.EXPERIMENT_PAUSES: "enrollment_end_date",
                Experiment.EXPERIMENT_ENDS: "end_date",
            }[date_type]

            results = []

            for experiment in queryset.all():
                date = getattr(experiment, experiment_date_field)

                # enrollment end dates are optional, so there won't always
                # be a pause date for an experiment
                if date:
                    if value.start and date < value.start.date():
                        continue
                    if value.stop and date > value.stop.date():
                        continue
                    results.append(experiment.id)

            return queryset.filter(pk__in=results)
        return queryset

    def in_qa_filter(self, queryset, name, value):
        if value:
            return queryset.filter(review_qa_requested=True, review_qa=False)

        return queryset

    def surveys_filter(self, queryset, name, value):
        if value:
            return queryset.filter(survey_required=True)

        return queryset

    def subscribed_filter(self, queryset, name, value):
        if value:
            return queryset.filter(subscribers__in=[self.request.user.id])

        return queryset

    def longrunning_filter(self, queryset, name, value):
        if value:
            return (queryset.exclude(firefox_max_version__exact="").annotate(
                firefox_min_int=Cast(
                    Func(
                        F("firefox_min_version"),
                        Value(ExperimentConstants.VERSION_REGEX.pattern),
                        function="substring",
                    ),
                    IntegerField(),
                ),
                firefox_max_int=Cast(
                    Func(
                        F("firefox_max_version"),
                        Value(ExperimentConstants.VERSION_REGEX.pattern),
                        function="substring",
                    ),
                    IntegerField(),
                ),
                version_count=F("firefox_max_int") - F("firefox_min_int"),
            ).filter(version_count__gte=3))

        return queryset

    def is_paused_filter(self, queryset, name, value):
        if value:
            return queryset.filter(is_paused=True,
                                   status=Experiment.STATUS_LIVE)

        return queryset

    def completed_results_filter(self, queryset, name, value):
        if value:
            return queryset.exclude(
                Q(results_url="") | Q(results_url=None),
                Q(results_initial="") | Q(results_initial=None),
                Q(results_lessons_learned="")
                | Q(results_lessons_learned=None),
            )
        return queryset

    def get_type_display_value(self):
        return ", ".join([
            dict(Experiment.TYPE_CHOICES)[type].replace(" Experiment", "")
            for type in self.data.getlist("type")
        ])

    def get_project_display_value(self):
        project_ids = self.data.getlist("projects")

        if project_ids:
            if "null" in project_ids:
                project_ids.remove("null")
            project_name_list = Project.objects.filter(
                id__in=project_ids).values_list("name")
            if project_name_list:
                return ", ".join(project_name[0]
                                 for project_name in project_name_list)
            return "No Projects"

    def get_owner_display_value(self):
        user_id = self.data.get("owner")

        if user_id is not None:
            return str(get_user_model().objects.get(id=user_id))

    def get_display_start_date_info(self):
        experiment_date_field = self.data.get("experiment_date_field")
        date_after = self.data.get("date_range_after")
        date_before = self.data.get("date_range_before")

        if date_after and date_before:
            return f"{experiment_date_field} between {date_after} and {date_before}"
        elif date_after and date_before == "":
            return f"{experiment_date_field} after {date_after}"
        elif date_after == "" and date_before:
            return f"{experiment_date_field} before {date_before}"
        else:
            return ""
Esempio n. 30
0
class DeviceFilter(CustomFieldFilterSet):
    id__in = NumericInFilter(field_name='id', lookup_expr='in')
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    manufacturer_id = django_filters.ModelMultipleChoiceFilter(
        field_name='device_type__manufacturer',
        queryset=Manufacturer.objects.all(),
        label='Manufacturer (ID)',
    )
    manufacturer = django_filters.ModelMultipleChoiceFilter(
        field_name='device_type__manufacturer__slug',
        queryset=Manufacturer.objects.all(),
        to_field_name='slug',
        label='Manufacturer (slug)',
    )
    device_type_id = django_filters.ModelMultipleChoiceFilter(
        queryset=DeviceType.objects.all(),
        label='Device type (ID)',
    )
    role_id = django_filters.ModelMultipleChoiceFilter(
        field_name='device_role_id',
        queryset=DeviceRole.objects.all(),
        label='Role (ID)',
    )
    role = django_filters.ModelMultipleChoiceFilter(
        field_name='device_role__slug',
        queryset=DeviceRole.objects.all(),
        to_field_name='slug',
        label='Role (slug)',
    )
    tenant_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Tenant.objects.all(),
        label='Tenant (ID)',
    )
    tenant = django_filters.ModelMultipleChoiceFilter(
        field_name='tenant__slug',
        queryset=Tenant.objects.all(),
        to_field_name='slug',
        label='Tenant (slug)',
    )
    platform_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Platform.objects.all(),
        label='Platform (ID)',
    )
    platform = django_filters.ModelMultipleChoiceFilter(
        field_name='platform__slug',
        queryset=Platform.objects.all(),
        to_field_name='slug',
        label='Platform (slug)',
    )
    name = NullableCharFieldFilter()
    asset_tag = NullableCharFieldFilter()
    region_id = django_filters.NumberFilter(
        method='filter_region',
        field_name='pk',
        label='Region (ID)',
    )
    region = django_filters.CharFilter(
        method='filter_region',
        field_name='slug',
        label='Region (slug)',
    )
    site_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Site.objects.all(),
        label='Site (ID)',
    )
    site = django_filters.ModelMultipleChoiceFilter(
        field_name='site__slug',
        queryset=Site.objects.all(),
        to_field_name='slug',
        label='Site name (slug)',
    )
    rack_group_id = django_filters.ModelMultipleChoiceFilter(
        field_name='rack__group',
        queryset=RackGroup.objects.all(),
        label='Rack group (ID)',
    )
    rack_id = django_filters.ModelMultipleChoiceFilter(
        field_name='rack',
        queryset=Rack.objects.all(),
        label='Rack (ID)',
    )
    cluster_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Cluster.objects.all(),
        label='VM cluster (ID)',
    )
    model = django_filters.ModelMultipleChoiceFilter(
        field_name='device_type__slug',
        queryset=DeviceType.objects.all(),
        to_field_name='slug',
        label='Device model (slug)',
    )
    status = django_filters.MultipleChoiceFilter(choices=DEVICE_STATUS_CHOICES,
                                                 null_value=None)
    is_full_depth = django_filters.BooleanFilter(
        field_name='device_type__is_full_depth',
        label='Is full depth',
    )
    mac_address = django_filters.CharFilter(
        method='_mac_address',
        label='MAC address',
    )
    has_primary_ip = django_filters.BooleanFilter(
        method='_has_primary_ip',
        label='Has a primary IP',
    )
    virtual_chassis_id = django_filters.ModelMultipleChoiceFilter(
        field_name='virtual_chassis',
        queryset=VirtualChassis.objects.all(),
        label='Virtual chassis (ID)',
    )
    console_ports = django_filters.BooleanFilter(
        method='_console_ports',
        label='Has console ports',
    )
    console_server_ports = django_filters.BooleanFilter(
        method='_console_server_ports',
        label='Has console server ports',
    )
    power_ports = django_filters.BooleanFilter(
        method='_power_ports',
        label='Has power ports',
    )
    power_outlets = django_filters.BooleanFilter(
        method='_power_outlets',
        label='Has power outlets',
    )
    interfaces = django_filters.BooleanFilter(
        method='_interfaces',
        label='Has interfaces',
    )
    pass_through_ports = django_filters.BooleanFilter(
        method='_pass_through_ports',
        label='Has pass-through ports',
    )
    tag = TagFilter()

    class Meta:
        model = Device
        fields = ['serial', 'position']

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        return queryset.filter(
            Q(name__icontains=value) | Q(serial__icontains=value.strip())
            | Q(inventory_items__serial__icontains=value.strip())
            | Q(asset_tag__icontains=value.strip())
            | Q(comments__icontains=value)).distinct()

    def filter_region(self, queryset, name, value):
        try:
            region = Region.objects.get(**{name: value})
        except ObjectDoesNotExist:
            return queryset.none()
        return queryset.filter(
            Q(site__region=region)
            | Q(site__region__in=region.get_descendants()))

    def _mac_address(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        try:
            mac = EUI(value.strip())
            return queryset.filter(interfaces__mac_address=mac).distinct()
        except AddrFormatError:
            return queryset.none()

    def _has_primary_ip(self, queryset, name, value):
        if value:
            return queryset.filter(
                Q(primary_ip4__isnull=False) | Q(primary_ip6__isnull=False))
        else:
            return queryset.exclude(
                Q(primary_ip4__isnull=False) | Q(primary_ip6__isnull=False))

    def _console_ports(self, queryset, name, value):
        return queryset.exclude(consoleports__isnull=value)

    def _console_server_ports(self, queryset, name, value):
        return queryset.exclude(consoleserverports__isnull=value)

    def _power_ports(self, queryset, name, value):
        return queryset.exclude(powerports__isnull=value)

    def _power_outlets(self, queryset, name, value):
        return queryset.exclude(poweroutlets_isnull=value)

    def _interfaces(self, queryset, name, value):
        return queryset.exclude(interfaces__isnull=value)

    def _pass_through_ports(self, queryset, name, value):
        return queryset.exclude(frontports__isnull=value,
                                rearports__isnull=value)