Ejemplo n.º 1
0
class WorkerFilter(filters.FilterSet):
    health = ChoiceFilter(choices=Worker.HEALTH_CHOICES)
    state = ChoiceFilter(choices=Worker.STATE_CHOICES)

    class Meta:
        model = Worker
        fields = {
            "hostname": [
                "exact",
                "in",
                "contains",
                "icontains",
                "startswith",
                "endswith",
            ],
            "description": [
                "exact",
                "in",
                "contains",
                "icontains",
                "startswith",
                "endswith",
            ],
            "last_ping": ["exact", "lt", "gt"],
            "state": ["exact", "in"],
            "health": ["exact", "in"],
        }
Ejemplo n.º 2
0
    def test_null_choice(self):
        # default is to be disabled
        f = ChoiceFilter(choices=[('a', 'a')], )
        self.assertEqual(f.field.choices, [
            ('', '---------'),
            ('a', 'a'),
        ])

        # set label, allow blank label
        f = ChoiceFilter(choices=[('a', 'a')], null_label='')
        self.assertEqual(f.field.choices, [
            ('', '---------'),
            ('null', ''),
            ('a', 'a'),
        ])

        # set null value
        f = ChoiceFilter(choices=[('a', 'a')],
                         null_value='NULL',
                         null_label='')
        self.assertEqual(f.field.choices, [
            ('', '---------'),
            ('NULL', ''),
            ('a', 'a'),
        ])

        # explicitly disable
        f = ChoiceFilter(choices=[('a', 'a')], null_label=None)
        self.assertEqual(f.field.choices, [
            ('', '---------'),
            ('a', 'a'),
        ])
Ejemplo n.º 3
0
class TelemetryFilter(django_filters.FilterSet):
    datetime = DateTimeFromToRangeFilter()
    sensor__category = ChoiceFilter(choices=SENSOR_CATEGORY)
    sensor__code_name = ChoiceFilter(choices=Sensor.get_sensors_name())

    class Meta:
        model = Telemetry
        fields = ['datetime', 'sensor__category', 'sensor__code_name']
Ejemplo n.º 4
0
class DeviceFilter(filters.FilterSet):
    device_type = filters.RelatedFilter(DeviceTypeFilter,
                                        name="device_type",
                                        queryset=DeviceType.objects.all())
    physical_owner = filters.RelatedFilter(UserFilter,
                                           name="physical_owner",
                                           queryset=User.objects.all())
    physical_group = filters.RelatedFilter(GroupFilter,
                                           name="physical_group",
                                           queryset=Group.objects.all())
    tags = filters.RelatedFilter(TagFilter,
                                 name="tags",
                                 queryset=Tag.objects.all())
    last_health_report_job = filters.RelatedFilter(
        "TestJobFilter",
        name="last_health_report_job",
        queryset=TestJob.objects.filter(health_check=True),
    )
    worker_host = filters.RelatedFilter(WorkerFilter,
                                        name="worker_host",
                                        queryset=Worker.objects.all())
    health = ChoiceFilter(choices=Device.HEALTH_CHOICES)
    state = ChoiceFilter(choices=Device.STATE_CHOICES)

    class Meta:
        model = Device
        fields = {
            "hostname": [
                "exact",
                "in",
                "contains",
                "icontains",
                "startswith",
                "endswith",
            ],
            "device_version": [
                "exact",
                "in",
                "contains",
                "icontains",
                "startswith",
                "endswith",
            ],
            "description": [
                "exact",
                "in",
                "contains",
                "icontains",
                "startswith",
                "endswith",
            ],
            "state": ["exact", "in"],
            "health": ["exact", "in"],
        }
Ejemplo n.º 5
0
class EventSearchFilter(django_filters.FilterSet):
	ownership = MultipleChoiceFilter(choices=[('admin','Created'), ('joined',' Joined')], widget=forms.CheckboxSelectMultiple )
	location = ChoiceFilter(name='location',choices=[('Venue','Venue'), ('Online','Online')], widget=forms.Select(attrs={'class': 'selects'}))
	city = CharFilter(name="city", lookup_expr="icontains", widget=forms.TextInput(attrs={'placeholder': 'City'}))
	state = CharFilter(name="state", lookup_expr="icontains", widget=forms.TextInput(attrs={'placeholder': 'State'}))
	country = CharFilter(name="india", lookup_expr="icontains", widget=forms.TextInput(attrs={'placeholder': 'India'}))
	category = ChoiceFilter(name="category",choices=[('Adventure','Adventure'), ('Business & Tech','Business & Tech'), ('Entertainment','Entertainment'), ('Social','Social'), ('Sports','Sports'), ('Talks','Talks')], widget=forms.Select(attrs={'class': 'selects'}))
	gender = ChoiceFilter(name='gender',choices=[('Male','Male'), ('Female','Female'), ('Others','Others'), ('Any', 'Any')], widget=forms.Select(attrs={'class': 'selects'}))
	age_group = ChoiceFilter(name='age',choices=[('Under 18','Under 18'), ('18-30','18-30'), ('30-50','30-50'), ('Above 50','Above 50')], widget=forms.Select(), lookup_expr="icontains", label='Age Group')
	year = NumberFilter(label='Start Date', name='start_date',lookup_expr='year', widget=forms.NumberInput(attrs={'class': 'form_inps', 'placeholder': 'Year'}) )
	month = NumberFilter(label='Start Date', name='start_date',lookup_expr='month', widget=forms.NumberInput(attrs={'class': 'form_inps', 'placeholder': 'Month'}) )
	day = NumberFilter(label='Start Date', name='start_date',lookup_expr='day', widget=forms.NumberInput(attrs={'class': 'form_inps', 'placeholder': 'Day'}) )
	class Meta:
		model = Event
		fields = ['ownership']
Ejemplo n.º 6
0
        class F(FilterSet):
            status = ChoiceFilter(widget=forms.RadioSelect,
                                  choices=STATUS_CHOICES)

            class Meta:
                model = User
                fields = ['status', 'username']
class ProgrammeDocumentIndicatorFilter(django_filters.FilterSet):

    pd_statuses = ChoiceFilter(choices=PD_STATUS, method='get_status')
    pds = CharFilter(method='get_programme_document')
    location = CharFilter(method='get_locations')
    blueprint__title = CharFilter(method='get_blueprint_title')
    incomplete = CharFilter(method='get_incomplete')

    class Meta:
        model = Reportable
        fields = (
            'id',
            'blueprint__title',
        )

    def get_status(self, queryset, name, value):
        return queryset.filter(
            lower_level_outputs__cp_output__programme_document__status=value)

    def get_programme_document(self, queryset, name, value):
        return queryset.filter(
            lower_level_outputs__cp_output__programme_document_id=value)

    def get_locations(self, queryset, name, value):
        return queryset.filter(locations=value)

    def get_blueprint_title(self, queryset, name, value):
        return queryset.filter(blueprint__title__contains=value)

    def get_incomplete(self, queryset, name, value):
        return queryset.filter(
            lower_level_outputs__cp_output__programme_document__progress_reports__indicator_reports__submission_date__isnull
            =True) if value == "1" else queryset
Ejemplo n.º 8
0
class PartnerProjectFilter(filters.FilterSet):
    partner = CharFilter(method='get_partner')
    title = CharFilter(method='get_title')
    location = CharFilter(method='get_location')
    status = ChoiceFilter(choices=PARTNER_PROJECT_STATUS)
    start_date = DateFilter(method='get_start_date')
    end_date = DateFilter(method='get_end_date')
    cluster_id = CharFilter(method='get_cluster_id')

    class Meta:
        model = PartnerProject
        fields = ['title', 'location', 'status', 'start_date', 'end_date']

    def get_partner(self, queryset, name, value):
        return queryset.filter(partner_id=value)

    def get_title(self, queryset, name, value):
        return queryset.filter(title__icontains=value)

    def get_location(self, queryset, name, value):
        return queryset.filter(locations__id=value)

    def get_start_date(self, queryset, name, value):
        return queryset.filter(start_date__gte=value)

    def get_end_date(self, queryset, name, value):
        return queryset.filter(end_date__lte=value)

    def get_cluster_id(self, queryset, name, value):
        return queryset.filter(clusters__in=[value])
Ejemplo n.º 9
0
class TodoFilter(CosinnusFilterSet):
    creator = AllObjectsFilter(label=_('Created By'),
                               widget=SelectCreatorWidget)
    assigned_to = AllObjectsFilter(label=_('Assigned To'),
                                   widget=SelectUserWidget)
    priority = ChoiceFilter(label=_('Priority'),
                            choices=FILTER_PRIORITY_CHOICES,
                            widget=DropdownChoiceWidget)
    due_date = ForwardDateRangeFilter(label=_('Due date'),
                                      widget=DropdownChoiceWidget)
    is_completed = IsCompletedFilter(label=_('Status'),
                                     choices=FILTER_COMPLETED_CHOICES,
                                     widget=DropdownChoiceWidgetWithEmpty())

    o = TodoOrderingFilter(fields=(
        ('created', 'created'),
        ('priority', 'priority'),
        ('due_date', 'due_date'),
        ('title', 'title'),
    ),
                           choices=(('-created', _('Newest Created')),
                                    ('title', _('Title')), ('-priority',
                                                            _('Priority')),
                                    ('due_date', _('Soonest Due'))),
                           default='-created',
                           widget=DropdownChoiceWidget)

    class Meta(object):
        model = TodoEntry
        fields = [
            'creator', 'assigned_to', 'priority', 'due_date', 'is_completed',
            'o'
        ]
Ejemplo n.º 10
0
class ProjectFilter(FilterSet):

    tab = ChoiceFilter(label="tab", method="get_tab", choices=TabChoice.choices)

    class Meta:
        model = Project
        fields = {
            "title": ["exact"],
            "organization": ["exact"],
            "visibility": ["exact"],
            "status": ["exact"],
        }

    def get_tab(self, queryset, name, value):
        user = self.request.user
        my_projects = queryset.filter(Q(created_by=user) | Q(users=user))
        if value == TabChoice.MY_PROJECT:
            return my_projects
        my_projects_id = my_projects.values("id")
        organization_projects = queryset.filter(
            Q(organization__admins=user) | Q(visibility="public_within_organization")
        ).exclude(id__in=my_projects_id)
        if value == TabChoice.ORGANIZATION:
            return organization_projects
        organization_projects_id = organization_projects.values("id")
        if value == TabChoice.PUBLIC:
            return queryset.exclude(
                Q(id__in=organization_projects_id) | Q(id__in=my_projects_id)
            )
Ejemplo n.º 11
0
class F203Filter(FormFilter):
    f201 = NumberFilter()
    RHC = ChoiceFilter(widget=Select2Widget(),
                       choices=RHC.objects.as_choices())

    class Meta:
        model = F203

        fields = [
            'id',
            'f201',
            'SNER',
            'NNRT',
            'NNRT1',
            'NNST',
            'RHC',
            'CIR',
        ]

    def __init__(self, *args, **kwargs):
        super(F203Filter, self).__init__(*args, **kwargs)

        self.extend_filter('NNRT', State_Division_Choices)
        self.extend_filter('NNRT1', District_Choices)
        self.extend_filter('NNST', Township_or_town_Choices)
        self.extend_filter('CIR', Sub_code_No_Choices)
Ejemplo n.º 12
0
class CandidateFilter(FilterSet):
    name = CharFilter(method='name_filter')
    status = ChoiceFilter(choices=Candidate.CANDIDATE_STATUS, help_text="")

    def __init__(self, *args, **kwargs):
        super(CandidateFilter, self).__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.form_method = 'get'

        layout = Div(Div(Field('name'), css_class='col-xs-12 col-md-6'),
                     Div(Field('status'), css_class='col-xs-12 col-md-6'))

        self.helper.layout = Layout(*layout)

        self.helper.add_input(Submit('submit', 'Filter', css_class='btn-info'))

    class Meta:
        model = Candidate
        fields = ['name', 'status']

    def name_filter(self, queryset, name, value):
        if value:
            return queryset.filter(
                reduce(or_, (Q(first_name__icontains=name)
                             | Q(last_name__icontains=name)
                             for name in value.split())))
        else:
            return queryset
Ejemplo n.º 13
0
class FlagFilterSet(FilterSet):
    """ Filtre django-filters des signalements """

    # Constantes
    AUTOMATIC_CHOICES = (
        ('1', _("Automatic")),
        ('0', _("Manual")),
    )

    # Champs
    automatic = ChoiceFilter(widget=LinkWidget,
                             choices=AUTOMATIC_CHOICES,
                             label=_("Automatic"))

    # Overrides
    def __init__(self, *args, **kwargs):
        """ Initialiser le filtre """
        super(FlagFilterSet, self).__init__(*args, **kwargs)
        self.filters['type'].widget = LinkWidget(attrs={'class': ''})
        self.filters['status'].widget = LinkWidget(attrs={'class': ''})
        self.filters['automatic'].widget = LinkWidget(attrs={'class': ''})
        for _name, field in self.filters.items():
            if isinstance(field, ChoiceFilter):
                field.extra['choices'] = tuple([("", _("All"))] +
                                               list(field.extra['choices']))

    # Métadonnées
    class Meta:
        model = Flag
        fields = ['type', 'status', 'automatic']
Ejemplo n.º 14
0
 def test_settings_overrides(self):
     f = ChoiceFilter(choices=[('a', 'a')], )
     self.assertEqual(f.field.choices, [
         ('', 'EMPTY LABEL'),
         ('NULL VALUE', 'NULL LABEL'),
         ('a', 'a'),
     ])
Ejemplo n.º 15
0
    class BaseFilter(django_filters.FilterSet):
        name = CharFilter(lookup_expr='contains')
        status = ChoiceFilter(choices=Base.STATUS)

        class Meta:
            exclude = [
                'id', 'tags', 'description', 'pin', 'documentation', 'comment'
            ]
Ejemplo n.º 16
0
    def test_callable_choices(self):
        def choices():
            yield ('a', 'a')
            yield ('b', 'b')

        f = ChoiceFilter(choices=choices)
        self.assertEqual(f.field.choices, [
            ('', '---------'),
            ('a', 'a'),
            ('b', 'b'),
        ])
Ejemplo n.º 17
0
    def test_empty_choice(self):
        # default value
        f = ChoiceFilter(choices=[('a', 'a')])
        self.assertEqual(f.field.choices, [
            ('', '---------'),
            ('a', 'a'),
        ])

        # set value, allow blank label
        f = ChoiceFilter(choices=[('a', 'a')], empty_label='')
        self.assertEqual(f.field.choices, [
            ('', ''),
            ('a', 'a'),
        ])

        # disable empty choice w/ None
        f = ChoiceFilter(choices=[('a', 'a')], empty_label=None)
        self.assertEqual(f.field.choices, [
            ('a', 'a'),
        ])
Ejemplo n.º 18
0
class MiscBooleanChoiceFiltersFilterSet(PropertyFilterSet):
    LOOKUP_CHOICES = [
        (True, 'Yes'),
        # (True, 'True'),
        # (True, 'GiveMeYes'),
        (False, 'No'),
        # (False, 'False'),
        # (False, 'GiveMeNo'),
    ]

    is_true_ChoiceFilter = ChoiceFilter(field_name='is_true',
                                        lookup_expr='exact',
                                        choices=LOOKUP_CHOICES)
    is_true_MultipleChoiceFilter = MultipleChoiceFilter(field_name='is_true',
                                                        lookup_expr='exact',
                                                        conjoined=False,
                                                        choices=LOOKUP_CHOICES)
    is_true_AllValuesFilter = AllValuesFilter(field_name='is_true',
                                              lookup_expr='exact')
    is_true_AllValuesMultipleFilter = AllValuesMultipleFilter(
        field_name='is_true', lookup_expr='exact', conjoined=False)
    # Typed Choice Filter might not have a blank option, skip
    #is_true_TypedChoiceFilter = TypedChoiceFilter(field_name='is_true', lookup_expr='exact', choices=LOOKUP_CHOICES, coerce=str)
    is_true_TypedMultipleChoiceFilter = TypedMultipleChoiceFilter(
        field_name='is_true',
        lookup_expr='exact',
        conjoined=False,
        choices=LOOKUP_CHOICES,
        coerce=str)

    prop_is_true_PropertyChoiceFilter = PropertyChoiceFilter(
        field_name='prop_is_true', lookup_expr='exact', choices=LOOKUP_CHOICES)
    prop_is_true_PropertyMultipleChoiceFilter = PropertyMultipleChoiceFilter(
        field_name='prop_is_true',
        lookup_expr='exact',
        conjoined=False,
        choices=LOOKUP_CHOICES)
    prop_is_true_PropertyAllValuesFilter = PropertyAllValuesFilter(
        field_name='prop_is_true', lookup_expr='exact')
    prop_is_true_PropertyAllValuesMultipleFilter = PropertyAllValuesMultipleFilter(
        field_name='prop_is_true', lookup_expr='exact', conjoined=False)
    # Typed Choice Filter might not have a blank option, skip
    #prop_is_true_PropertyTypedChoiceFilter = PropertyTypedChoiceFilter(field_name='prop_is_true', lookup_expr='exact', choices=LOOKUP_CHOICES, coerce=str)
    prop_is_true_PropertyTypedMultipleChoiceFilter = PropertyTypedMultipleChoiceFilter(
        field_name='prop_is_true',
        lookup_expr='exact',
        conjoined=False,
        choices=LOOKUP_CHOICES,
        coerce=str)

    class Meta:
        model = models.BooleanFilterModel
        exclude = ['is_true']
Ejemplo n.º 19
0
class AdvertisementFilter(filters.FilterSet):
    """Фильтры для объявлений."""

    # TODO: задайте требуемые фильтры
    created_at = DateFromToRangeFilter()
    status = ChoiceFilter(choices=AdvertisementStatusChoices.choices)

    # creator =

    class Meta:
        model = Advertisement
        fields = ("status", "created_at", "creator")
class PDReportsFilter(filters.FilterSet):
    status = ChoiceFilter(
        choices=PROGRESS_REPORT_STATUS,
        method="get_status",
        label="Status")

    class Meta:
        model = IndicatorReport
        fields = ['status', ]

    def get_status(self, queryset, name, value):
        return queryset.filter(progress_report__status=value)
Ejemplo n.º 21
0
    def filter_for_field(cls, f, name):
        filter_for_field = dict(FILTER_FOR_DBFIELD_DEFAULTS,
                                **cls.filter_overrides)

        default = {'name': name, 'label': capfirst(f.verbose_name)}

        if f.choices:
            default['choices'] = f.choices
            return ChoiceFilter(**default)

        data = filter_for_field.get(f.__class__)
        if data is None:
            return
        filter_class = data.get('filter_class')
        default.update(data.get('extra', lambda f: {})(f))
        if filter_class is not None:
            return filter_class(**default)
Ejemplo n.º 22
0
class DeviceTypeFilter(filters.FilterSet):
    architecture = RelatedFilter(ArchitectureFilter,
                                 name="architecture",
                                 queryset=Architecture.objects.all())
    processor = RelatedFilter(ProcessorFamilyFilter,
                              name="processor",
                              queryset=ProcessorFamily.objects.all())
    alias = RelatedFilter(AliasFilter,
                          name="alias",
                          queryset=Alias.objects.all())
    bits = RelatedFilter(BitWidthFilter,
                         name="bits",
                         queryset=BitWidth.objects.all())
    cores = RelatedFilter(CoreFilter,
                          name="cores",
                          queryset=Core.objects.all())
    health_denominator = ChoiceFilter(choices=DeviceType.HEALTH_DENOMINATOR)

    class Meta:
        model = DeviceType
        fields = {
            "name":
            ["exact", "in", "contains", "icontains", "startswith", "endswith"],
            "cpu_model": [
                "exact",
                "in",
                "contains",
                "icontains",
                "startswith",
                "endswith",
            ],
            "description": [
                "exact",
                "in",
                "contains",
                "icontains",
                "startswith",
                "endswith",
            ],
            "health_frequency": ["exact", "in"],
            "disable_health_check": ["exact", "in"],
            "health_denominator": ["exact", "in"],
            "display": ["exact", "in"],
            "core_count": ["exact", "in"],
        }
Ejemplo n.º 23
0
class PartnerActivityFilter(django_filters.FilterSet):

    partner = CharFilter(method='get_partner')
    project = CharFilter(method='get_project')
    cluster_id = CharFilter(method='get_cluster_id')
    activity = CharFilter(method='get_activity')
    custom = TypedChoiceFilter(
        field_name='custom',
        choices=Boolean.CHOICES,
        coerce=strtobool,
        method='get_custom',
        label='Show only custom activities',
    )
    status = ChoiceFilter(choices=PARTNER_PROJECT_STATUS)
    location = CharFilter(method='get_location')

    class Meta:
        model = PartnerActivity
        fields = [
            'partner', 'project', 'cluster_id', 'activity', 'custom', 'status',
            'location'
        ]

    def get_partner(self, queryset, name, value):
        return queryset.filter(partner=value)

    def get_project(self, queryset, name, value):
        return queryset.filter(projects=value)

    def get_cluster_id(self, queryset, name, value):
        return queryset.filter(
            Q(cluster_activity__cluster_objective__cluster__id=value)
            | Q(cluster_objective__cluster__id=value))

    def get_activity(self, queryset, name, value):
        return queryset.filter(title__icontains=value)

    def get_custom(self, queryset, name, value):
        if value:
            return queryset.filter(cluster_activity=None)
        return queryset

    def get_location(self, queryset, name, value):
        return queryset.filter(locations__id=value)
class ProgrammeDocumentFilter(django_filters.FilterSet):
    ref_title = CharFilter(method='get_reference_number_title')
    status = ChoiceFilter(choices=PD_STATUS)
    location = CharFilter(method='get_location')

    class Meta:
        model = ProgrammeDocument
        fields = ['ref_title', 'status', 'location']

    def get_reference_number_title(self, queryset, name, value):
        return queryset.filter(
            Q(reference_number__icontains=value) | Q(title__icontains=value))

    def get_status(self, queryset, name, value):
        return queryset.filter(status=value)

    def get_location(self, queryset, name, value):
        return queryset.filter(
            progress_reports__indicator_reports__indicator_location_data__location
            =value)
Ejemplo n.º 25
0
class EtherpadFilter(CosinnusFilterSet):
    creator = AllObjectsFilter(label=_('Created By'),
                               widget=SelectCreatorWidget)
    type = ChoiceFilter(label=_('Type'),
                        choices=((0, _('Etherpad')), (1, _('Ethercalc'))),
                        widget=DropdownChoiceWidgetWithEmpty)

    o = CosinnusOrderingFilter(fields=(
        ('last_accessed', 'last_accessed'),
        ('created', 'created'),
        ('title', 'title'),
    ),
                               choices=(
                                   ('-last_accessed', _('Last accessed')),
                                   ('-created', _('Newest Pads')),
                                   ('title', _('Title')),
                               ),
                               default='-last_accessed',
                               widget=DropdownChoiceWidget)

    class Meta(object):
        model = Etherpad
        fields = ['creator', 'type', 'o']
Ejemplo n.º 26
0
    def filter_for_field(cls, f, name):
        filter_for_field = dict(FILTER_FOR_DBFIELD_DEFAULTS,
                                **cls.filter_overrides)
        if hasattr(f, 'field'):
            f = f.field
        default = {'name': name, 'label': capfirst(f.verbose_name)}

        if f.choices:
            default['choices'] = f.choices
            return ChoiceFilter(**default)

        data = filter_for_field.get(f.__class__)
        if data is None:
            # probably a derived field, inspect parents
            for _class in f.__class__.__bases__:
                data = filter_for_field.get(_class)
                if data:
                    break
            if data is None:
                return
        filter_class = data.get('filter_class')
        default.update(data.get('extra', lambda f: {})(f))
        if filter_class is not None:
            return filter_class(**default)
Ejemplo n.º 27
0
class TripSearchFilter(django_filters.FilterSet):
	dayslist = [(str(i),'0'+str(i)) for i in [i for i in range(1,10)]] + [(str(i),str(i)) for i in [i for i in range(10,32)]]
	monthslist =  [(1,'Jan'), (2,'Feb'), (3,'Mar'), (4,'Apr'), (5,'May'), (6,'Jun'), (7,'Jul'), (8,'Aug'), (9,'Sep'), (10,'Oct'), (11,'Nov'), (12,'Dec')]
	yearslist = [(i, i) for i in range(2018,2050)]
	source = django_filters.CharFilter(label="Source:", lookup_expr='icontains', widget=forms.TextInput(attrs={}))
	destination = django_filters.CharFilter(label="Destination:", lookup_expr='icontains')
	company = ChoiceFilter(choices=[('Group','Group'), ('Solo','Solo')], widget=forms.Select() )
	moto = ChoiceFilter(label='Travel Moto',choices=[('','Any'), ('Adventure','Adventure'), ('Exploring','Exploring'), ('Photography','Photography'), ('Sports Event','Sports Event'), ('Food & Cuisine','Food & Cuisine'), ('Fitness','Fitness'), ('Shopping','Shopping'), ('Travel Blogging','Travel Blogging'), ('Partying','Partying'), ('Backtracking','Backtracking')], widget=forms.Select() )
	mode = ChoiceFilter(choices=[('Car','Car'), ('Motorbike','Motorbike'), ('Cycle','Cycle'), ('On-Foot','On-Foot'), ('Any', 'Any') ], widget=forms.Select() )
	year = NumberFilter(label='Start Date', name='start_date',lookup_expr='year', widget=forms.NumberInput(attrs={'class': 'search_inputs', 'placeholder': 'Year'}) )
	month = NumberFilter(label='Start Date', name='start_date',lookup_expr='month', widget=forms.NumberInput(attrs={'class': 'search_inputs', 'placeholder': 'Month'}) )
	day = NumberFilter(label='Start Date', name='start_date',lookup_expr='day', widget=forms.NumberInput(attrs={'class': 'search_inputs', 'placeholder': 'Day'}) )
	age_group = ChoiceFilter(choices=[('Under 18','Under 18'), ('18-30','18-30'), ('30-50','30-50'), ('Above 50','Above 50')], widget=forms.Select(), lookup_expr="icontains", label='Age Group' )
	#year = ChoiceFilter(name='start_date',choices=yearslist, widget=forms.Select(attrs={'class': 'search_inputs'}) )
	#start_date = django_filters.NumberFilter(name='start_date', lookup_expr='year')
	ownership = MultipleChoiceFilter(choices=[('admin','Created'), ('joined',' Joined')], widget=forms.CheckboxSelectMultiple )
	location = ChoiceFilter(choices=[('male','Male'), ('female','Female'), ('others','Others'), ('any','Any')], widget=forms.Select())
	gender = ChoiceFilter(choices=[('male','Male'), ('female','Female'), ('others','Others'), ('Any', 'Any')], widget=forms.Select(attrs={'class': 'selects'}))
	trip_id = django_filters.CharFilter(label="Trip id:", name="trip_id", lookup_expr='icontains', widget=forms.TextInput(attrs={}))

	class Meta:
		model = Trip
		fields = []
Ejemplo n.º 28
0
        class F(FilterSet):
            status = ChoiceFilter(choices=STATUS_CHOICES, initial=1)

            class Meta:
                model = User
                fields = ['status']
Ejemplo n.º 29
0
class ContatoAgrupadoPorProcessoFilterSet(FilterSet):

    AGRUPADO_POR_NADA = 'sem_agrupamento'
    AGRUPADO_POR_TITULO = 'titulo'
    AGRUPADO_POR_IMPORTANCIA = 'importancia'
    AGRUPADO_POR_TOPICO = 'topicos__descricao'
    AGRUPADO_POR_ASSUNTO = 'assuntos__descricao'
    AGRUPADO_POR_STATUS = 'status__descricao'
    AGRUPADO_POR_CLASSIFICACAO = 'classificacoes__descricao'

    AGRUPAMENTO_CHOICE = (
        (AGRUPADO_POR_NADA, _('Sem Agrupamento')),
        (AGRUPADO_POR_TITULO, _('Por Título de Processos')),
        (AGRUPADO_POR_IMPORTANCIA, _('Por Importância')),
        (AGRUPADO_POR_TOPICO, _('Por Tópicos')),
        (AGRUPADO_POR_ASSUNTO, _('Por Assuntos')),
        (AGRUPADO_POR_STATUS, _('Por Status')),
        (AGRUPADO_POR_CLASSIFICACAO, _('Por Classificação')),
    )

    search = CharFilter(method='filter_search')

    agrupamento = ChoiceFilter(required=False,
                               empty_label=None,
                               choices=AGRUPAMENTO_CHOICE,
                               method='filter_agrupamento')

    importancia = MultipleChoiceFilter(required=False,
                                       choices=IMPORTANCIA_CHOICE,
                                       method='filter_importancia')

    status = ModelMultipleChoiceFilter(required=False,
                                       queryset=StatusProcesso.objects.all(),
                                       method='filter_status')

    def filter_agrupamento(self, queryset, field_name, value):
        return queryset

    def filter_importancia(self, queryset, field_name, value):
        if not value:
            return queryset

        q = None
        for i in value:
            q = q | Q(importancia=i) if q else Q(importancia=i)
        return queryset.filter(q)

    def filter_status(self, queryset, field_name, value):
        if not value:
            return queryset

        q = None
        for sta in value:
            q = q | Q(status=sta) if q else Q(status=sta)
        return queryset.filter(q)

    def filter_search(self, queryset, field_name, value):

        query = normalize(value)

        query = query.split(' ')
        if query:
            q = Q()
            for item in query:
                if not item:
                    continue
                q = q & Q(search__icontains=item)

            if q:
                queryset = queryset.filter(q)
        return queryset

    class Meta:
        model = Processo
        fields = [
            'search',
            'data',
            'topicos',
            'importancia',
            'classificacoes',
            'assuntos',
            'status',
        ]
        filter_overrides = {
            models.DateField: {
                'filter_class': DataRangeFilter,
                'extra': lambda f: {
                    'label': '%s (%s)' %
                    (f.verbose_name, _('Inicial - Final')),
                    'widget': RangeWidgetOverride
                }
            }
        }

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

        workspace = kwargs.pop('workspace')

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

        c1_row1 = to_row([
            ('search', 7),
            ('data', 5),
            ('importancia', 4),
            ('status', 4),
            ('classificacoes', 4),
            ('topicos', 6),
            ('assuntos', 6),
        ])

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

        col2 = Fieldset(
            _('Inf p/ Impressão'), 'agrupamento',
            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['search'].label = _('Filtrar Títulos de Processos')

        self.form.fields['topicos'].widget = forms.SelectMultiple(
            attrs={'size': '7'})
        self.form.fields['topicos'].queryset = TopicoProcesso.objects.all()

        self.form.fields['assuntos'].widget = forms.SelectMultiple(
            attrs={'size': '7'})
        self.form.fields['assuntos'].queryset = AssuntoProcesso.objects.filter(
            workspace=workspace)

        self.form.fields['importancia'].widget = forms.CheckboxSelectMultiple()
        #self.form.fields['importancia'].inline_class = True

        self.form.fields[
            'classificacoes'].widget = forms.CheckboxSelectMultiple()

        self.form.fields['status'].widget = forms.CheckboxSelectMultiple()
        """#self.form.fields['status'].inline_class = True
        self.form.fields['status'].choices = list(
            self.form.fields['status'].choices)
        del self.form.fields['status'].choices[0]"""

        self.form.fields['agrupamento'].label = _('Agrupar Contatos')
        self.form.fields['agrupamento'].widget = forms.RadioSelect()
Ejemplo n.º 30
0
class ImpressoEnderecamentoContatoFilterSet(FilterSet):

    FEMININO = 'F'
    MASCULINO = 'M'
    AMBOS = ''
    SEXO_CHOICE = ((AMBOS, _('Ambos')), (FEMININO, _('Feminino')),
                   (MASCULINO, _('Masculino')))

    DEPOIS_PRONOME = 'DP'
    LINHA_NOME = 'LN'
    DEPOIS_NOME = 'DN'
    LOCAL_CARGO_CHOICE = ((DEPOIS_PRONOME,
                           _('Depois do Pronome '
                             'de tratamento')),
                          (LINHA_NOME, _('Antes do Nome do Contato')),
                          (DEPOIS_NOME,
                           _('Entre o Nome do Contato '
                             'e seu Endereço')))

    FILHOS_CHOICE = [(None, _('Ambos'))] + YES_NO_CHOICES

    search = CharFilter(method='filter_search')
    sexo = ChoiceFilter(choices=SEXO_CHOICE)
    tem_filhos = ChoiceFilter(label=_('Com filhos?'), choices=FILHOS_CHOICE)

    idade = RangeFilter(label=_('Idade entre:'),
                        widget=RangeWidgetNumber,
                        method='filter_idade')

    impresso = ModelChoiceFilter(
        label=ImpressoEnderecamento._meta.verbose_name_plural,
        required=True,
        queryset=ImpressoEnderecamento.objects.all(),
        method='filter_impresso')

    grupo = ChoiceFilter(label=_('Contatos Agrupados'),
                         required=False,
                         method='filter_grupo')

    imprimir_pronome = ChoiceFilter(label=_('Imprimir Pronome?'),
                                    choices=YES_NO_CHOICES,
                                    required=True,
                                    initial=False,
                                    method='filter_imprimir_pronome')
    imprimir_cargo = ChoiceFilter(label=_('Imprimir Cargo?'),
                                  required=True,
                                  empty_label=None,
                                  choices=YES_NO_CHOICES,
                                  initial=False,
                                  method='filter_imprimir_cargo')

    fontsize = NumberFilter(label=_('Tamanho da Fonte'),
                            initial='',
                            max_value=100,
                            min_value=0,
                            max_digits=3,
                            decimal_places=0,
                            method='filter_fontsize')

    nome_maiusculo = ChoiceFilter(label=_('Nome Maiúsculo'),
                                  choices=YES_NO_CHOICES,
                                  initial=False,
                                  method='filter_nome_maiusculo')

    local_cargo = ChoiceFilter(label=_('Local para imprimir o Cargo'),
                               choices=LOCAL_CARGO_CHOICE,
                               initial=False,
                               method='filter_local_cargo')

    def filter_impresso(self, queryset, field_name, value):
        return queryset

    def filter_fontsize(self, queryset, field_name, value):
        return queryset

    def filter_grupo(self, queryset, field_name, value):
        if value == '0':
            queryset = queryset.filter(grupodecontatos_set__isnull=True)
        elif value != '':
            queryset = queryset.filter(grupodecontatos_set=value)
        return queryset

    def filter_local_cargo(self, queryset, field_name, value):
        return queryset

    def filter_imprimir_pronome(self, queryset, field_name, value):
        return queryset

    def filter_imprimir_cargo(self, queryset, field_name, value):
        return queryset

    def filter_nome_maiusculo(self, queryset, field_name, value):
        return queryset

    def filter_idade(self, queryset, field_name, value):
        idi = int(value.start) if value.start is not None else 0
        idf = int(
            value.stop) if value.stop is not None else date.today().year - 2

        if idi > idf:
            a = idi
            idi = idf
            idf = a

        # lim inicial-dt.mais antiga
        li = date.today() - relativedelta(years=idf + 1)
        # lim final - dt. mais nova
        lf = date.today() - relativedelta(years=idi)

        return queryset.filter(data_nascimento__gt=li, data_nascimento__lte=lf)

    def filter_search(self, queryset, field_name, value):

        query = normalize(value)

        query = query.split(' ')
        if query:
            q = Q()
            for item in query:
                if not item:
                    continue
                q = q & Q(search__icontains=item)

            if q:
                queryset = queryset.filter(q)
        return queryset

    def filter_data_nascimento(self, queryset, field_name, value):
        #_where = "date_part('year', age(timestamp '%s', data_nascimento)) != date_part('year', age(timestamp '%s', data_nascimento))"
        # return queryset.extra(where=_where, params=value)

        if not value[0] or not value[1]:
            return queryset

        now = datetime.datetime.strptime(value[0], "%d/%m/%Y").date()
        then = datetime.datetime.strptime(value[1], "%d/%m/%Y").date()
        if now > then:
            a = now
            now = then
            then = a

        # Build the list of month/day tuples.
        monthdays = [(now.month, now.day)]
        while now <= then:
            monthdays.append((now.month, now.day))
            now += timedelta(days=1)

        # Tranform each into queryset keyword args.
        monthdays = (dict(
            zip(("data_nascimento__month", "data_nascimento__day"), t))
                     for t in monthdays)

        # Compose the djano.db.models.Q objects together for a single query.
        query = reduce(operator.or_, (Q(**d) for d in monthdays))

        # Run the query.
        return queryset.extra(
            select={
                'month': 'extract( month from data_nascimento )',
                'day': 'extract( day from data_nascimento )',
            }).order_by('month', 'day', 'nome').filter(query)

    data_nascimento = DataRangeFilter(widget=RangeWidgetOverride,
                                      method='filter_data_nascimento')

    class Meta:
        model = Contato
        fields = [
            'search', 'sexo', 'tem_filhos', 'data_nascimento',
            'tipo_autoridade'
        ]
        """filter_overrides = {
            models.DateField: {
                'filter_class': DataRangeFilter,
                'extra': lambda f: {
                    'label': '%s (%s)' % (f.verbose_name, _('Inicial - Final')),
                    'widget': RangeWidgetOverride
                }
            }
        }"""

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

        workspace = kwargs.pop('workspace')

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

        col1 = to_row([
            ('search', 6),
            ('sexo', 3),
            ('tem_filhos', 3),
            ('data_nascimento', 6),
            ('idade', 6),
            ('tipo_autoridade', 6),
            ('grupo', 6),
        ])

        col2 = to_row([
            ('impresso', 12),
            ('fontsize', 4),
            ('nome_maiusculo', 4),
            ('imprimir_pronome', 4),
            ('imprimir_cargo', 5),
            ('local_cargo', 7),
        ])

        row = to_row([
            (Fieldset(
                _('Informações para Seleção de Contatos'), col1,
                to_row([(SubmitFilterPrint(
                    'filter',
                    value=_('Filtrar'),
                    css_class='btn-outline-primary pull-right',
                    type='submit'), 12)])), 6),
            (Fieldset(
                _('Informações para Impressão'), col2,
                to_row([(SubmitFilterPrint('print',
                                           value=_('Imprimir'),
                                           css_class='btn-primary pull-right',
                                           type='submit'), 12)])), 6)
        ])

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

        self.form.fields['search'].label = _('Nome/Nome Social/Apelido')
        self.form.fields['data_nascimento'].label = '%s (%s)' % (
            _('Aniversário'), _('Inicial - Final'))

        self.form.fields['tem_filhos'].choices.choices[0] = (None, _('Ambos'))

        self.form.fields['grupo'].choices = [
            ('0', _('Apenas Contatos sem Grupo')),
        ] + [(g.pk, str(g))
             for g in GrupoDeContatos.objects.filter(workspace=workspace)]