コード例 #1
0
ファイル: users.py プロジェクト: whit-colm/authentik
class UsersFilter(FilterSet):
    """Filter for users"""

    attributes = CharFilter(
        field_name="attributes",
        lookup_expr="",
        label="Attributes",
        method="filter_attributes",
    )

    is_superuser = BooleanFilter(field_name="ak_groups",
                                 lookup_expr="is_superuser")

    # pylint: disable=unused-argument
    def filter_attributes(self, queryset, name, value):
        """Filter attributes by query args"""
        try:
            value = loads(value)
        except ValueError:
            raise ValidationError(detail="filter: failed to parse JSON")
        if not isinstance(value, dict):
            raise ValidationError(
                detail="filter: value must be key:value mapping")
        qs = {}
        for key, _value in value.items():
            qs[f"attributes__{key}"] = _value
        return queryset.filter(**qs)

    class Meta:
        model = User
        fields = [
            "username", "name", "is_active", "is_superuser", "attributes"
        ]
コード例 #2
0
ファイル: filters.py プロジェクト: stuartquin/soitgoes
class TimeSlipFilter(FilterSet):
    start = DateFilter(field_name="date", lookup_expr="gte")
    end = DateFilter(field_name="date", lookup_expr="lte")
    no_invoice = BooleanFilter(field_name="invoice", lookup_expr="isnull")

    class Meta:
        model = TimeSlip
        fields = ["invoice", "project", "start", "end", "no_invoice"]
コード例 #3
0
class MyEventsFilter(FilterSet):
    """
    Filter events by the following parameters:
        - owner (boolean)
        - participating (boolean)
    """

    owner = BooleanFilter(method="owner_filter")
    participating = BooleanFilter(method="participating_filter")

    def owner_filter(self, queryset, _, value):
        return queryset.own_events(self.request.user) if value else queryset

    def participating_filter(self, queryset, _, value):
        return queryset.participating_events(
            self.request.user) if value else queryset

    class Meta:
        model = Event
        fields = ["owner"]
コード例 #4
0
class MembershipFilter(FilterSet):
    """ Filters Membership by membership_type """

    onlyMembers = BooleanFilter(method="filter_membership_type",
                                label="Filter only members")

    class Meta:
        model = Membership
        fields = ["onlyMembers"]

    def filter_membership_type(self, queryset, name, value):
        if value:
            return queryset.filter(membership_type=MembershipType.MEMBER)
        return queryset
コード例 #5
0
class CertificateKeyPairFilter(FilterSet):
    """Filter for certificates"""

    has_key = BooleanFilter(
        label="Only return certificate-key pairs with keys",
        method="filter_has_key")

    # pylint: disable=unused-argument
    def filter_has_key(self, queryset, name, value):  # pragma: no cover
        """Only return certificate-key pairs with keys"""
        return queryset.exclude(key_data__exact="")

    class Meta:
        model = CertificateKeyPair
        fields = ["name", "managed"]
コード例 #6
0
class TaskFilter(FilterSet):
    label = ModelChoiceFilter(queryset=Label.objects.all(),
                              field_name='labels',
                              label='Метка')
    is_author = BooleanFilter(field_name='author',
                              widget=forms.CheckboxInput,
                              label='Только свои задачи',
                              method='filter_author_tasks')

    def filter_author_tasks(self, queryset, name, value):
        if value:
            return queryset.filter(author=self.request.user)
        return queryset

    class Meta:
        model = Task
        fields = ['status', 'executor']
コード例 #7
0
 def test_default_field(self):
     f = BooleanFilter()
     field = f.field
     self.assertIsInstance(field, forms.NullBooleanField)
コード例 #8
0
 def test_filtering(self):
     qs = mock.Mock(spec=['filter'])
     f = BooleanFilter(name='somefield')
     result = f.filter(qs, True)
     qs.filter.assert_called_once_with(somefield=True)
     self.assertNotEqual(qs, result)
コード例 #9
0
 def test_filtering_skipped_with_none_value(self):
     qs = mock.Mock()
     f = BooleanFilter(name='somefield')
     result = f.filter(qs, None)
     self.assertListEqual(qs.method_calls, [])
     self.assertEqual(qs, result)
コード例 #10
0
ファイル: test_filters.py プロジェクト: msk7777/django-filter
 def test_filtering_exclude(self):
     qs = mock.Mock(spec=['exclude'])
     f = BooleanFilter(field_name='somefield', exclude=True)
     result = f.filter(qs, True)
     qs.exclude.assert_called_once_with(somefield__exact=True)
     self.assertNotEqual(qs, result)
コード例 #11
0
ファイル: test_filters.py プロジェクト: msk7777/django-filter
 def test_filtering_lookup_expr(self):
     qs = mock.Mock(spec=['filter'])
     f = BooleanFilter(field_name='somefield', lookup_expr='isnull')
     result = f.filter(qs, True)
     qs.filter.assert_called_once_with(somefield__isnull=True)
     self.assertNotEqual(qs, result)
コード例 #12
0
 def test_filtering_skipped_with_none_value(self):
     qs = mock.Mock()
     f = BooleanFilter(name='somefield')
     result = f.filter(qs, None)
     self.assertListEqual(qs.method_calls, [])
     self.assertEqual(qs, result)
コード例 #13
0
 def test_filtering_lookup_type(self):
     qs = mock.Mock(spec=['filter'])
     f = BooleanFilter(name='somefield', lookup_type='isnull')
     result = f.filter(qs, True)
     qs.filter.assert_called_once_with(somefield__isnull=True)
     self.assertNotEqual(qs, result)
コード例 #14
0
 def test_filtering_exclude(self):
     qs = mock.Mock(spec=['exclude'])
     f = BooleanFilter(name='somefield', exclude=True)
     result = f.filter(qs, True)
     qs.exclude.assert_called_once_with(somefield__exact=True)
     self.assertNotEqual(qs, result)
コード例 #15
0
ファイル: filters.py プロジェクト: stuartquin/soitgoes
class TaskFilter(FilterSet):
    no_invoice = BooleanFilter(field_name="invoices", lookup_expr="isnull")

    class Meta:
        model = Task
        fields = ["invoices", "project", "no_invoice", "billing_type"]
コード例 #16
0
ファイル: forms.py プロジェクト: felipecoliveira/saap
class ContatoAgrupadoPorGrupoFilterSet(FilterSet):
    search = MethodFilter()

    municipio = MethodModelChoiceFilter(required=False,
                                        queryset=Municipio.objects.all())

    grupo = MethodModelMultipleChoiceFilter(
        required=False, queryset=GrupoDeContatos.objects.all())

    ativo = BooleanFilter()

    # contato_ativo = MethodChoiceFilter(
    #     choices=NONE_YES_NO_CHOICES,
    #     initial=None)

    def filter_municipio(self, queryset, value):
        queryset = queryset.filter(endereco_set__municipio=value)
        return queryset

    def filter_grupo(self, queryset, value):
        if value:
            queryset = queryset.filter(grupodecontatos_set__in=value)

        return queryset.order_by('grupodecontatos_set__nome', 'nome')

    def filter_ativo(self, queryset, value):
        if value is not None:
            queryset = queryset.filter(ativo=value)

        return queryset

    # def filter_contato_ativo(self, queryset, value):
    #     if value is not None:
    #         queryset = queryset.filter(ativo=value)
    #
    #     return queryset

    class Meta:
        model = Contato

    def __init__(self,
                 data=None,
                 queryset=None,
                 prefix=None,
                 strict=None,
                 **kwargs):

        workspace = kwargs.pop('workspace')

        super(ContatoAgrupadoPorGrupoFilterSet,
              self).__init__(data=data,
                             queryset=queryset,
                             prefix=prefix,
                             strict=strict,
                             **kwargs)

        c1_row1 = to_row([
            ('municipio', 7),
            ('grupo', 7),
            ('ativo', 7),
        ])

        col1 = Fieldset(
            _('Informações para Seleção de Contados'), c1_row1,
            to_row([(SubmitFilterPrint('filter',
                                       value=_('Filtrar'),
                                       css_class='btn-default pull-right',
                                       type='submit'), 12)]))

        col2 = Fieldset(
            _('Inf p/ Impressão'),
            SubmitFilterPrint('print',
                              value=_('Imprimir'),
                              css_class='btn-primary pull-right',
                              type='submit'))

        rows = to_row([
            (col1, 9),
            (col2, 3),
        ])

        self.form.helper = FormHelper()
        self.form.helper.form_method = 'GET'
        self.form.helper.layout = Layout(rows, )

        self.form.fields['grupo'].queryset = GrupoDeContatos.objects.filter(
            workspace=workspace)
        self.form.fields['municipio'].queryset = Municipio.objects.all()
コード例 #17
0
ファイル: filters.py プロジェクト: ropable/wastd
class TaxonFilter(django_filters.FilterSet):
    """Filter for Taxon."""

    is_terminal_taxon = BooleanFilter(label="Terminal Taxon",
                                      widget=BooleanWidget(),
                                      method="filter_leaf_nodes")
    current = BooleanFilter(label="Taxonomic name is current",
                            widget=BooleanWidget())
    admin_areas = ModelMultipleChoiceFilter(
        label="DBCA Regions and Districts",
        queryset=Area.objects.filter(area_type__in=[
            Area.AREATYPE_DBCA_REGION, Area.AREATYPE_DBCA_DISTRICT
        ]).order_by("area_type", "name"),
        method='taxa_occurring_in_area')
    eoo = geo_models.PolygonField()
    aoo = CharFilter(
        label="Area of Occupancy (AOO) intersects",
        widget=LeafletWidget(),
        method="taxa_occurring_in_poly",
    )
    conservation_level = MultipleChoiceFilter(
        label="Conservation Level",
        choices=cons_models.ConservationCategory.LEVEL_CHOICES,
        method='taxon_conservation_level')
    categories = ModelMultipleChoiceFilter(
        label="Conservation Listing Categories",
        queryset=cons_models.ConservationCategory.objects.filter(
            conservation_list__scope_species=True).order_by(
                "conservation_list__code",
                "rank").prefetch_related("conservation_list"),
        method="taxa_with_conservation_criteria")

    class Meta:
        """Class opts."""

        model = Taxon
        fields = [
            "paraphyletic_groups", "admin_areas", "eoo", "aoo",
            "conservation_level", "categories", "taxonomic_name",
            "vernacular_names", "rank", "is_terminal_taxon", "current",
            "publication_status", "name_id", "field_code"
        ]
        filter_overrides = FILTER_OVERRIDES

    def filter_leaf_nodes(self, queryset, name, value):
        """Return terminal taxa (leaf nodes) if value is true."""
        return queryset.filter(children__isnull=value)

    def taxa_occurring_in_area(self, queryset, name, value):
        """Return Taxa occurring in the given list of ``Area`` instances.

        * The filter returns a list of Area objects as ``value``
        * We need to extract their PKs to create a queryset equivalent to
          the list of objects ``value``. Only querysets allow agggregation, not lists.
        * A search_area Multipolygon is collected from the geoms of Areas in ``value``
        * The Taxon PKs are calculated from occurrences (TaxonAreaEncounters)
          ``intersect``ing the search_area
        * The queryset is filtered by the list of Taxon PKs with occurrences
        """
        if value:
            area_pks = [area.pk for area in value]
            search_area = Area.objects.filter(pk__in=area_pks).aggregate(
                Collect('geom'))["geom__collect"]
            taxon_pks_in_area = set([
                x["taxon__pk"]
                for x in occ_models.TaxonAreaEncounter.objects.filter(
                    Q(point__intersects=search_area)
                    | Q(geom__intersects=search_area)).values("taxon__pk")
            ])
            return queryset.filter(pk__in=taxon_pks_in_area)
        else:
            return queryset

    def taxa_occurring_in_poly(self, queryset, name, value):
        """Return Taxa occurring in the given Area polygon.

        * The filter returns a ``value``
        * (magic) value becomes search area
        * The Taxon PKs are calculated from occurrences (TaxonAreaEncounters)
          ``intersect``ing the search_area
        * The queryset is filtered by the list of Taxon PKs with occurrences
        """
        if value:
            taxon_pks_in_area = set([
                x["taxon__pk"]
                for x in occ_models.TaxonAreaEncounter.objects.filter(
                    Q(point__intersects=value)
                    | Q(geom__intersects=value)).values("taxon__pk")
            ])
            return queryset.filter(pk__in=taxon_pks_in_area)
        else:
            return queryset

    def taxon_conservation_level(self, queryset, name, value):
        """Return Taxa matching a conservation level.

        * The filter returns a list of ConservationCategory levels as ``value``
        * The Taxon PKs are calculated from active, WA CommunityConservationListings
          with categories matching the level
        * The queryset is filtered by the list of Taxon PKs with
          active taxon listings in WA  matching the conservation level
        """
        if value:
            taxon_pks = set([
                x["taxon__pk"]
                for x in cons_models.TaxonConservationListing.objects.filter(
                    scope=cons_models.ConservationListing.
                    SCOPE_WESTERN_AUSTRALIA,
                    status=cons_models.ConservationListing.STATUS_EFFECTIVE,
                    category__level__in=value).values("taxon__pk")
            ])
            return queryset.filter(pk__in=taxon_pks)
        else:
            return queryset

    def taxa_with_conservation_criteria(self, queryset, name, value):
        """Return Taxa matching a conservation level.

        * The filter returns a list of ConservationCategories as ``value``
        * The Taxon PKs are calculated from TaxonConservationListings
          with categories matching the list of categories in ``value``
        * The queryset is filtered by the list of Taxon PKs
          matching the conservation level
        """
        if value:
            taxon_pks = set([
                x["taxon__pk"]
                for x in cons_models.TaxonConservationListing.objects.filter(
                    category__in=value).values("taxon__pk")
            ])
            return queryset.filter(pk__in=taxon_pks)
        else:
            return queryset
コード例 #18
0
 def test_filtering(self):
     qs = mock.Mock(spec=['filter'])
     f = BooleanFilter(name='somefield')
     result = f.filter(qs, True)
     qs.filter.assert_called_once_with(somefield=True)
     self.assertNotEqual(qs, result)