class PDAReportFilter(django_filters.FilterSet): first_name = CharFilter(field_name="teacher__first_name", label='First Name') last_name = CharFilter(field_name="teacher__last_name", label='Last Name') school = ModelChoiceFilter(field_name="teacher__school__name", label='School', queryset=users.models.School.objects.all()) school_year = ModelChoiceFilter(field_name='school_year', queryset=SchoolYear.objects.all(), label='School Year') start_created = DateFilter(field_name="created_at", lookup_expr='gte', label='Created after:') end_created = DateFilter(field_name="created_at", lookup_expr='lte', label='Created before:') start_updated = DateFilter(field_name="updated_at", lookup_expr='gte', label='Updated after:') end_updated = DateFilter(field_name="updated_at", lookup_expr='lte', label='Updated before:') CHOICES = (('n', 'Not Reviewed'), ('a', 'Approved'), ('d', 'Not Approved'), ('', 'Any')) isei_status = ChoiceFilter(field_name="isei_reviewed", choices=CHOICES, label='ISEI approval') principal_status = ChoiceFilter(field_name="principal_reviewed", choices=CHOICES, label='Principal approval')
class SectionFilter(FilterSet): semester = CharFilter(Semester.objects, label='Semester', method='filter_semester') professor = CharFilter(label='Professor Name Contains', method='filter_professor') course_descr = CharFilter(Course.objects, label='Course Info', method='filter_course') hours = CharFilter(field_name='hours', lookup_expr='icontains') location = CharFilter(field_name='location', lookup_expr='icontains') status = ChoiceFilter(choices=Section.STATUSES, field_name='status') graduate = ChoiceFilter(field_name='course__graduate', label='Course Level?', choices=((True, 'Graduate'), (False, 'Undergrad'))) # seats_remaining = RangeFilter() def filter_semester(self, queryset, name, value): return queryset.annotate(slug=Concat('semester__session', Value('-'), 'semester__year', output_field=CharField())).filter( slug__icontains=value) def filter_professor(self, queryset, name, value): return queryset.annotate( slug=Concat('professor__profile__user__first_name', Value(' '), 'professor__profile__user__last_name', output_field=CharField())).filter( slug__icontains=value) def filter_course(self, queryset, name, value): return queryset.annotate(slug=Concat('course__major__abbreviation', Value('-'), 'course__catalog_number', Value(': '), 'course__title', output_field=CharField())).filter( slug__icontains=value) def __init__(self, *args, **kwargs): super(SectionFilter, self).__init__(*args, **kwargs) self.filters['status'].extra.update({'empty_label': 'Any Status'}) self.filters['graduate'].extra.update( {'empty_label': 'Any Course Level'}) class Meta: model = Section fields = [ 'semester', 'course_descr', 'graduate', 'professor', 'hours', 'location', 'status' ]
class ArticleFilter(FilterSet): genre_choices = ( ('A', _('Accessoire')), ('V', _('Vêtement')), ('C', _('Chaussure')), ('S', _('Sous-vêtement')), ) clients_choices = ( ('H', _('Homme')), ('F', _('Femme')), ('M', _('Mixte')), ('E', _('Enfant')), ) solde_choices = (('S', _('en solde')), ) genre_article = ChoiceFilter(choices=genre_choices, label=_(u"Article Type")) type_client = ChoiceFilter(choices=clients_choices, label=_('Client Type')) solde = ChoiceFilter(choices=solde_choices) arrivage = ModelChoiceFilter(queryset=Arrivage.objects.all()) marque = ModelChoiceFilter(queryset=Marque.objects.all()) quantity = RangeFilter() class Meta: model = Article fields = { 'name': ['icontains'], 'id': ['exact'], 'quantity': ['lte', 'gte'], }
class SectionStudentFilter(FilterSet): semester = CharFilter(label='Semester', method='filter_semester') def filter_semester(self, queryset, name, value): return queryset.annotate(slug=Concat('section__semester__session', Value('-'), 'section__semester__year', output_field=CharField())).filter( slug__icontains=value) sec_status = ChoiceFilter(choices=Section.STATUSES, field_name='section__status', label="Section Status") student_status = ChoiceFilter(choices=SectionStudent.STATUSES, field_name='status', label="Student Status") grade = ChoiceFilter(choices=SectionStudent.GRADES, field_name='grade', label="Grade") def __init__(self, *args, **kwargs): super(SectionStudentFilter, self).__init__(*args, **kwargs) self.filters['sec_status'].extra.update({'empty_label': 'Any Section Status'}) self.filters['student_status'].extra.update({'empty_label': 'Any Student Status'}) self.filters['grade'].extra.update({'empty_label': 'Any Grade'}) class Meta: model = SectionStudent fields = ['semester', 'sec_status', 'student_status', 'grade']
class BannerFilter(SortedFilterSet): name = CharFilter(label=pgettext_lazy('Banner name filter label', 'Name'), lookup_expr='icontains') is_active = ChoiceFilter(label=pgettext_lazy('Banner list filter label', 'Is public'), choices=BOOLEAN_CHOICES, empty_label=pgettext_lazy( 'Filter empty choice label', 'All'), widget=forms.Select) is_default = ChoiceFilter(label=pgettext_lazy('Banner list filter label', 'Is default'), choices=BOOLEAN_CHOICES, empty_label=pgettext_lazy( 'Filter empty choice label', 'All'), widget=forms.Select) sort_by = OrderingFilter(label=pgettext_lazy( 'Voucher list sorting filter label', 'Sort by'), fields=SORT_BY_FIELDS.keys(), field_labels=SORT_BY_FIELDS) class Meta: model = Banner fields = [] def get_summary_message(self): counter = self.qs.count() return npgettext( 'Number of matching records in the dashboard banners list', 'Found %(counter)d matching banner', 'Found %(counter)d matching banners', number=counter) % { 'counter': counter }
class OrderFilter(SortedFilterSet): id = NumberFilter(label=pgettext_lazy('Order list filter label', 'ID')) name_or_email = CharFilter(label=pgettext_lazy('Order list filter label', 'Customer name or email'), method=filter_by_order_customer) created = DateFromToRangeFilter(label=pgettext_lazy( 'Order list filter label', 'Placed on'), name='created', widget=DateRangeWidget) status = ChoiceFilter(label=pgettext_lazy('Order list filter label', 'Order status'), choices=OrderStatus.CHOICES, empty_label=pgettext_lazy( 'Filter empty choice label', 'All'), widget=forms.Select) payment_status = ChoiceFilter( label=pgettext_lazy('Order list filter label', 'Payment status'), name='payments__status', choices=PaymentStatus.CHOICES, empty_label=pgettext_lazy('Filter empty choice label', 'All'), widget=forms.Select) total_net = RangeFilter(label=pgettext_lazy('Order list filter label', 'Total'), widget=PriceRangeWidget) sort_by = OrderingFilter(label=pgettext_lazy('Order list filter label', 'Sort by'), fields=SORT_BY_FIELDS, field_labels=SORT_BY_FIELDS_LABELS) class Meta: model = Order fields = []
class ProductFilter(SortedFilterSet): name = CharFilter(label=pgettext_lazy('Product list filter label', 'Name'), lookup_expr='icontains') categories = ModelMultipleChoiceFilter(label=pgettext_lazy( 'Product list filter label', 'Categories'), name='categories', queryset=Category.objects.all()) price = RangeFilter(label=pgettext_lazy('Product list filter label', 'Price'), name='price', widget=PriceRangeWidget) is_published = ChoiceFilter( label=pgettext_lazy('Product list filter label', 'Is published'), choices=PUBLISHED_CHOICES, empty_label=pgettext_lazy('Filter empty choice label', 'All'), widget=forms.Select) is_featured = ChoiceFilter( label=pgettext_lazy('Product list is featured filter label', 'Is featured'), choices=FEATURED_CHOICES, empty_label=pgettext_lazy('Filter empty choice label', 'All'), widget=forms.Select) sort_by = OrderingFilter(label=pgettext_lazy('Product list filter label', 'Sort by'), fields=PRODUCT_SORT_BY_FIELDS.keys(), field_labels=PRODUCT_SORT_BY_FIELDS) class Meta: model = Product fields = []
class SentMessageFilter(FilterSet): prefix = 'sent' BOOLE_CHOICES = ((True, 'Only Archived'), (False, 'Only Not Archived')) time_sent = DateTimeFromToRangeFilter() recipient = CharFilter(field_name='recipient__user__name', label='To', method='filter_recipient', lookup_expr='icontains') unread = ChoiceFilter(field_name='unread', label='Read?', choices=((True, 'Unread Only'), (False, 'Read Only'))) subject = CharFilter(field_name='subject', lookup_expr='icontains') high_priority = ChoiceFilter(label='High Pri?', choices=((True, 'High Pri'), (False, 'Normal'))) def filter_recipient(self, queryset, name, value): return queryset.annotate(slug=Concat( 'recipient__user__username', Value('-'), 'recipient__user__first_name', Value(' '), 'recipient__user__last_name', )).filter(slug__icontains=value) def __init__(self, data=None, *args, **kwargs): newdict = data.dict() super(SentMessageFilter, self).__init__(newdict, *args, **kwargs) self.filters['high_priority'].extra.update({'empty_label': 'Any Pri'}) self.filters['unread'].extra.update({'empty_label': 'Read/Unread'}) class Meta: fields = ['time_sent', 'recipient', 'subject', 'unread', 'high_priority']
class TrialStatusFilter(FilterSet): TODAY_CHOICES = (('2', 'Yes'), ('', 'Unknown')) status = MultipleChoiceFilter(label='Trial status', choices=Trial.STATUS_CHOICES, widget=QueryArrayWidget) is_overdue_today = ChoiceFilter(label='Is overdue today', method='filter_today', choices=TODAY_CHOICES) is_no_longer_overdue_today = ChoiceFilter( label='Is no longer overdue today', method='filter_today', choices=TODAY_CHOICES) def filter_today(self, queryset, name, value): if str(value ) == '2': # A truthy value per django-rest-api/django-filters if name == 'is_overdue_today': queryset = queryset.overdue_today() elif name == 'is_no_longer_overdue_today': queryset = queryset.no_longer_overdue_today() return queryset class Meta: model = Trial fields = ('has_exemption', 'has_results', 'results_due', 'sponsor', 'status', 'is_pact', 'is_overdue_today', 'is_no_longer_overdue_today')
class PostsFilterSet(FilterSet): date_order = ChoiceFilter(field_name='date', choices=ORDER_CHOICES, label=' Order ', initial='1', method='custom_order_filter') date_limit = ChoiceFilter(field_name='date', choices=DATE_CHOICES, label=' Publication limit time ', method='custom_date_filter') class Meta: model = Post fields = ['author'] def __init__(self, data, *args, **kwargs): data = data.copy() data.setdefault('format', 'paperback') data.setdefault('order', 'added') super().__init__(data, *args, **kwargs) def custom_order_filter(self, queryset, name, value): return queryset.filter().order_by(int(value) * '-' + str(name)) def custom_date_filter(self, queryset, name, value): lookup = '__'.join([name, 'gte']) time_bound = timezone.now() - datetime.timedelta(days=float(value)) return queryset.filter(**{lookup: time_bound})
class LeagueFilter(FilterSet): league = ChoiceFilter(choices=LeagueOfLegendsAccount.LEAGUE_CHOICES) division = ChoiceFilter(choices=LeagueOfLegendsAccount.DIVISION_CHOICES) server = ChoiceFilter(choices=LeagueOfLegendsAccount.SERVER_CHOICES) class Meta: model = LeagueOfLegendsAccount fields = ['league', 'division', 'server']
class VacationFilter(FilterSet): def get_full_name(): employees = [] employees_queryset = Employee.objects.all() for employee in employees_queryset: employee_dict = employee.id, employee.get_full_name_property employees.append(employee_dict) return employees search_first_name = CharFilter(label="First name: ", method='search_employee_by_first_name') search_last_name = CharFilter(label="Last name: ", method='search_employee_by_last_name') search_by_month_from_date = ChoiceFilter( choices=MONTHS, label='From date - month: ', empty_label='Month', method='search_vacation_by_month_from_date', lookup_expr='icontains', ) search_by_year_from_date = CharFilter( label='From date - year: ', method='search_vacation_by_year_from_date', ) search_employee_by_full_name = ChoiceFilter( # choices=get_full_name(), # TODO: it's not working with empty db choices=[], # TODO: it's not working with empty db label='Employee: ', empty_label='Employee', method='search_employee', lookup_expr='icontains', ) def search_employee_by_first_name(self, qs, name, value): return qs.filter(Q(employee__first_name__icontains=value)) def search_employee_by_last_name(self, qs, name, value): return qs.filter(Q(employee__last_name__icontains=value)) def search_vacation_by_month_from_date(self, qs, name, value): return qs.filter(Q(from_date__month=value)) def search_vacation_by_year_from_date(self, qs, name, value): return qs.filter(Q(from_date__year=value)) def search_employee(self, qs, name, value): return qs.filter(Q(employee=value)) class Meta: model = Vacation fields = ( 'search_first_name', 'search_last_name', 'search_by_month_from_date', 'search_by_year_from_date', 'search_employee_by_full_name', )
class FullReceivedMessageFilter(FilterSet): prefix = 'received' BOOLE_CHOICES = ((True, 'Only Archived'), (False, 'Only Not Archived')) HANDLED_CHOICES = ((True, 'Only Handled'), (False, 'Only Unhandled')) time_sent = DateTimeFromToRangeFilter() sender = CharFilter(field_name='sender__user__name', label='Frxom', method='filter_sender', lookup_expr='icontains') unread = ChoiceFilter(field_name='unread', label='Read?', choices=((True, 'Unread Only'), (False, 'Read Only'))) archived = ChoiceFilter(field_name='archived', label='Archived?', choices=BOOLE_CHOICES, initial=False) subject = CharFilter(field_name='subject', lookup_expr='icontains') handled = ChoiceFilter(field_name='handled', label='Handled?', choices=HANDLED_CHOICES) high_priority = ChoiceFilter(label='High Pri?', choices=((True, 'High Pri'), (False, 'Normal'))) def filter_recipient(self, queryset, name, value): return queryset.annotate(slug=Concat( 'recipient__user__username', Value('-'), 'recipient__user__first_name', Value(' '), 'recipient__user__last_name', )).filter(slug__icontains=value) def filter_sender(self, queryset, name, value): return queryset.annotate(slug=Concat( 'sender__user__username', Value('-'), 'sender__user__first_name', Value(' '), 'sender__user__last_name', )).filter(slug__icontains=value) def __init__(self, data=None, *args, **kwargs): newdict = data.dict() if len(newdict) == 0: newdict[f'{self.prefix}-archived'] = False super(FullReceivedMessageFilter, self).__init__(newdict, *args, **kwargs) self.filters['high_priority'].extra.update({'empty_label': 'Any Pri'}) self.filters['unread'].extra.update({'empty_label': 'Read/Unread'}) self.filters['archived'].extra.update({'empty_label': 'Archived?'}) self.filters['handled'].extra.update({'empty_label': 'Handled?'}) class Meta: fields = [ 'time_sent', 'sender', 'subject', 'unread', 'high_priority', 'handled', 'archived' ]
class AnimalFilter(FilterSet): animal_type = ChoiceFilter(empty_label='Todos', choices=Animal.ANIMAL_TYPE_CHOICES) sex = ChoiceFilter(empty_label='Todos', choices=Animal.SEX_CHOICES) size = ChoiceFilter(empty_label='Todos', choices=Animal.SIZE_CHOICES) is_puppy = ChoiceFilter(empty_label='Todos', choices=AGE_CHOICES) class Meta: model = Animal fields = ['animal_type', 'sex', 'size', 'is_puppy']
class ProfileFilter(FilterSet): class Meta: model = Profile fields = ( "first_name", "last_name", "nickname", "emails__email", "emails__email_type", "emails__primary", "emails__verified", "phones__phone", "phones__phone_type", "phones__primary", "addresses__address", "addresses__postal_code", "addresses__city", "addresses__country_code", "addresses__address_type", "addresses__primary", "language", "enabled_subscriptions", ) first_name = CharFilter(lookup_expr="icontains") last_name = CharFilter(lookup_expr="icontains") nickname = CharFilter(lookup_expr="icontains") emails__email = CharFilter(lookup_expr="icontains") emails__email_type = ChoiceFilter(choices=EmailType.choices()) emails__primary = BooleanFilter() emails__verified = BooleanFilter() phones__phone = CharFilter(lookup_expr="icontains") phones__phone_type = ChoiceFilter(choices=PhoneType.choices()) phones__primary = BooleanFilter() addresses__address = CharFilter(lookup_expr="icontains") addresses__postal_code = CharFilter(lookup_expr="icontains") addresses__city = CharFilter(lookup_expr="icontains") addresses__country_code = CharFilter(lookup_expr="icontains") addresses__address_type = ChoiceFilter(choices=AddressType.choices()) addresses__primary = BooleanFilter() language = CharFilter() enabled_subscriptions = CharFilter(method="get_enabled_subscriptions") order_by = PrimaryContactInfoOrderingFilter(fields=( ("first_name", "firstName"), ("last_name", "lastName"), ("nickname", "nickname"), ("language", "language"), )) def get_enabled_subscriptions(self, queryset, name, value): """ Custom filter to join the enabled of subscription with subscription type correctly """ return queryset.filter(subscriptions__enabled=True, subscriptions__subscription_type__code=value)
class VoucherFilter(SortedFilterSet): name = CharFilter( label=pgettext_lazy("Voucher list name filter label", "Name"), lookup_expr="icontains", ) type = ChoiceFilter( field_name="type", label=pgettext_lazy("Voucher list type filter label", "Voucher type"), choices=VOUCHER_TYPE_CHOICES, empty_label=pgettext_lazy("Filter empty choice label", "All"), widget=forms.Select, ) discount_value_type = ChoiceFilter( field_name="discount_value_type", label=pgettext_lazy("Voucher list is sale type filter label", "Discount type"), choices=DISCOUNT_VALUE_TYPE_CHOICES, empty_label=pgettext_lazy("Filter empty choice label", "All"), widget=forms.Select, ) discount_value = RangeFilter( label=pgettext_lazy("Voucher list filter label", "Discount_value")) date = DateFromToRangeFilter( label=pgettext_lazy("Voucher list sorting filter label", "Period of validity"), field_name="created", widget=DateRangeWidget, method=filter_by_date_range, ) min_spent_amount = RangeFilter( label=pgettext_lazy("Voucher list sorting filter", "Minimum amount spent"), field_name="min_spent_amount", ) sort_by = OrderingFilter( label=pgettext_lazy("Voucher list sorting filter label", "Sort by"), fields=SORT_BY_FIELDS_LABELS_VOUCHER.keys(), field_labels=SORT_BY_FIELDS_LABELS_VOUCHER, ) class Meta: model = Voucher fields = [] def get_summary_message(self): counter = self.qs.count() return npgettext( "Number of matching records in the dashboard vouchers list", "Found %(counter)d matching voucher", "Found %(counter)d matching vouchers", number=counter, ) % { "counter": counter }
class BookFilter(FilterSet): COUNTRY_CHOICES = ( ('all', 'All'), ('china', 'China'), ('korea', 'Korea'), ('japan', 'Japan'), ) CHAPTER_FILTER = ( ('high', 'Highest'), ('low', 'Lowest'), ) VOTES_FILTER = ( ('high', 'Highest'), ('low', 'Lowest'), ) RATING_FILTER = ( ('all', 'All'), (1, 'atleast 1 star'), (2, 'atleast 2 star'), (3, 'atleast 3 star'), (4, 'atleast 4 star'), ) # status_release = ChoiceFilter() country = ChoiceFilter(label='Country', choices=COUNTRY_CHOICES, method='filter_by_country') chapters = ChoiceFilter(label='Chapters', choices=CHAPTER_FILTER, method='filter_by_chapters') votes = ChoiceFilter(label='Votes', choices=VOTES_FILTER, method='filter_by_votes') rating = ChoiceFilter(label='Rating', choices=RATING_FILTER, method='filter_by_rating') class Meta: model = Book fields = ['status_release'] def __init__(self, *args, **kwargs): super(BookFilter, self).__init__(*args, **kwargs) self.filters['status_release'].label = 'Completion' def filter_by_country(self, qs, name, value): if not value == 'all': qs = qs if not value else qs.filter(country__iexact=value) return qs def filter_by_chapters(self, qs, name, value): expression = 'chapters_count' if value == 'low' else '-chapters_count' return qs.order_by(expression) def filter_by_votes(self, qs, name, value): expression = 'chapters_count' if value == 'low' else '-chapters_count' return qs.order_by(expression) def filter_by_rating(self, qs, name, value): if not value == 'all': qs = qs if not value else qs.filter(rating__gte=value) return qs
class OrderFilter(SortedFilterSet): id = NumberFilter(label=pgettext_lazy('Order list filter label', 'ID')) name_or_email = CharFilter(label=pgettext_lazy('Order list filter label', 'Customer name or email'), method='filter_by_order_customer') created = DateFromToRangeFilter(label=pgettext_lazy( 'Order list filter label', 'Placed on'), name='created', widget=DateRangeWidget) status = ChoiceFilter(label=pgettext_lazy('Order list filter label', 'Order status'), choices=OrderStatus.CHOICES, empty_label=pgettext_lazy( 'Filter empty choice label', 'All'), method='filter_by_status', widget=forms.Select) payment_status = ChoiceFilter( label=pgettext_lazy('Order list filter label', 'Payment status'), name='payments__status', choices=PaymentStatus.CHOICES, empty_label=pgettext_lazy('Filter empty choice label', 'All'), widget=forms.Select) total_net = RangeFilter(label=pgettext_lazy('Order list filter label', 'Total'), widget=PriceRangeWidget) sort_by = OrderingFilter(label=pgettext_lazy('Order list filter label', 'Sort by'), fields=SORT_BY_FIELDS, field_labels=SORT_BY_FIELDS_LABELS) class Meta: model = Order fields = [] def filter_by_order_customer(self, queryset, name, value): return queryset.filter( Q(user__email__icontains=value) | Q(user__default_billing_address__first_name__icontains=value) | Q(user__default_billing_address__last_name__icontains=value)) def filter_by_status(self, queryset, name, value): """Filter by status using custom querysets.""" return (queryset.open() if value == OrderStatus.OPEN else queryset.closed()) def get_summary_message(self): counter = self.qs.count() return npgettext( 'Number of matching records in the dashboard orders list', 'Found %(counter)d matching order', 'Found %(counter)d matching orders', number=counter) % { 'counter': counter }
class IndicatorFilter(FilterSet): #level = ModelChoiceFilter(queryset = Indicator.objects.values('level').distinct()) level = ChoiceFilter(choices = STATUS_CHOICES_LEVEL) sector = ChoiceFilter(choices = STATUS_CHOICES_SECTOR) class Meta: model = Indicator fields = { 'level':['exact'], 'sector':['exact'], 'name': ['icontains'] }
class AllPlayerUnitsFilter(FilterSet): player = ChoiceFilter(choices=Player.objects.values_list( "id", "name").order_by(Lower("name"))) category = ChoiceFilter( field_name="unit__categories", choices=Category.objects.values_list("id", "name").order_by(Lower("name")), ) class Meta: model = PlayerUnit fields = ["unit", "player", "category"]
class ProjectVersionListFilterSet(FilterSet): """ Filter and sorting for project version listing page. This is used from the project versions list view page to provide filtering and sorting to the version list and search UI. It is normally instantiated with an included queryset, which provides user project authorization. """ VISIBILITY_HIDDEN = 'hidden' VISIBILITY_VISIBLE = 'visible' VISIBILITY_CHOICES = ( ('hidden', _('Hidden versions')), ('visible', _('Visible versions')), ) PRIVACY_CHOICES = ( ('public', _('Public versions')), ('private', _('Private versions')), ) # Attribute filter fields version = CharFilter(field_name='slug', widget=HiddenInput) privacy = ChoiceFilter( field_name='privacy_level', label=_('Privacy'), choices=PRIVACY_CHOICES, empty_label=_('Any'), ) # This field looks better as ``visibility=hidden`` than it does # ``hidden=true``, otherwise we could use a BooleanFilter instance here # instead visibility = ChoiceFilter( field_name='hidden', label=_('Visibility'), choices=VISIBILITY_CHOICES, method='get_visibility', empty_label=_('Any'), ) sort = VersionSortOrderingFilter( field_name='sort', label=_('Sort by'), empty_label=_('Relevance'), ) def get_visibility(self, queryset, name, value): if value == self.VISIBILITY_HIDDEN: return queryset.filter(hidden=True) if value == self.VISIBILITY_VISIBLE: return queryset.filter(hidden=False) return queryset
class VoucherCodeFilter(FilterSet): batch__channel = ChoiceFilter(choices=get_choices('channel'), label='Channel') batch__affiliate = ChoiceFilter(choices=get_choices('affiliate'), label='Affiliate') batch__campaign = ChoiceFilter(choices=get_choices('campaign'), label='Campaign') class Meta: model = VoucherCode fields = { 'code': ['icontains'], }
class UserFilter(FilterSet): username = CharFilter(lookup_expr='icontains') name = CharFilter(field_name='name', label='Name', method='filter_has_name', lookup_expr='icontains') access_role = ChoiceFilter(field_name='profile__role', label='Access Role', choices=Profile.ROLES) major = ModelChoiceFilter( queryset=Major.objects.order_by('abbreviation'), # provided because it needs one. Will be ignoring this. field_name='name', method='filter_has_major', label='Major') def filter_has_major(self, queryset, name, value): return queryset.filter( Q(profile__professor__major__abbreviation=value) | Q(profile__student__major__abbreviation=value)) def filter_has_name(self, queryset, name, value): return queryset.annotate( fullname=Concat('first_name', Value(' '), 'last_name')).filter( fullname__icontains=value).distinct() is_active = ChoiceFilter(label='Enabled?', choices=((True, 'Enabled'), (False, 'Disabled'))) graduate = ChoiceFilter(field_name='profile__student__grad_student', label='Grad Student?', choices=((True, 'Grad Student'), (False, 'Undergrad'))) student_gpa = RangeFilter(field_name='profile__student__gpa', label='GPA') class Meta: model = User fields = [ 'username', 'name', 'major', 'access_role', 'graduate', 'student_gpa', 'is_active' ] def __init__(self, *args, **kwargs): super(UserFilter, self).__init__(*args, **kwargs) self.filters['is_active'].extra.update( {'empty_label': 'Enabled/Disabled'}) self.filters['access_role'].extra.update({'empty_label': 'Any Role'}) self.filters['major'].extra.update({'empty_label': 'Any Major/Dept'}) self.filters['graduate'].extra.update( {'empty_label': 'Grad/Undergrad'})
class TrackerFilter(django_filters.FilterSet): adult_or_pediatric = ChoiceFilter(choices=AGE_CHOICES) access = ChoiceFilter(choices=ACCESS_CHOICES) trackerID = ChoiceFilter(choices=TRACKERID_CHOICES) groups = ChoiceFilter(choices=GROUP_CHOICES) class Meta: model = Tracker fields = [ 'dataset_name', 'cancer_type', 'adult_or_pediatric', 'group', 'access', 'details', 'accession' ] orderable = True attrs = {"class": "paleblue"}
class TaskFilter(FilterSet): class Meta: model = Task fields = [ 'name', 'date_due', 'category', 'group', 'status', 'priority' ] name = CharFilter(label="Nom de la Tache contient", lookup_expr='icontains') date_due = DateTimeFilter(label="Date limite", lookup_expr='icontains') category = ModelChoiceFilter(queryset=Category.objects.all(), label="De la categorie") group = ModelChoiceFilter(queryset=Group.objects.all(), label="Du groupe") statut = ChoiceFilter(label="Statut") priority = ChoiceFilter(label="Ayant la priorite")
class TemplatesFilter(ModelSearchFilter): # Fields of the model that can be filtered template_name = CharFilter(lookup_expr='icontains', help_text='Use % for wildcard searching.', label='Template Name') application_domain = ChoiceFilter(choices=Template.DOMAINS, lookup_expr='exact', label='Adpplication Domain') template_type = ChoiceFilter(choices=Template.TYPES, lookup_expr='exact', label='Template Type') class Meta: model = Template fields = [] # Django complains without fields set in the meta
class ProductFilter(SortedFilterSet): name = CharFilter(label=pgettext_lazy('Product list filter label', 'Name'), lookup_expr='icontains') category = ModelMultipleChoiceFilter(label=pgettext_lazy( 'Product list filter label', 'Category'), name='category', queryset=Category.objects.all()) brand_id = ModelMultipleChoiceFilter(label=pgettext_lazy( 'Product list filter label', 'Brand'), name='brand_id', queryset=Brand.objects.all()), product_type = ModelMultipleChoiceFilter( label=pgettext_lazy('Product list filter label', 'Product type'), name='product_type', queryset=ProductType.objects.all()) price = RangeFilter(label=pgettext_lazy('Product list filter label', 'Price'), name='price', widget=MoneyRangeWidget) is_published = ChoiceFilter( label=pgettext_lazy('Product list filter label', 'Is published'), choices=PUBLISHED_CHOICES, empty_label=pgettext_lazy('Filter empty choice label', 'All'), widget=forms.Select) is_featured = ChoiceFilter( label=pgettext_lazy('Product list is featured filter label', 'Is featured'), choices=FEATURED_CHOICES, empty_label=pgettext_lazy('Filter empty choice label', 'All'), widget=forms.Select) sort_by = OrderingFilter(label=pgettext_lazy('Product list filter label', 'Sort by'), fields=PRODUCT_SORT_BY_FIELDS.keys(), field_labels=PRODUCT_SORT_BY_FIELDS) class Meta: model = Product fields = ['brand_id', 'location_id'] def get_summary_message(self): counter = self.qs.count() return npgettext( 'Number of matching records in the dashboard products list', 'Found %(counter)d matching product', 'Found %(counter)d matching products', number=counter) % { 'counter': counter }
class TaxFilter(SortedFilterSet): country_code = ChoiceFilter( label=pgettext_lazy("Taxes list filter label", "Country name"), empty_label=pgettext_lazy("Filter empty choice label", "All"), widget=forms.Select, ) sort_by = OrderingFilter( label=pgettext_lazy("Taxes list sorting form", "Sort by"), fields=SORT_BY_FIELDS.keys(), field_labels=SORT_BY_FIELDS, ) class Meta: model = VAT fields = [] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.filters["country_code"].extra.update( {"choices": get_country_choices_for_vat()}) def get_summary_message(self): counter = self.qs.count() return npgettext( "Number of matching records in the dashboard taxes list", "Found %(counter)d matching country", "Found %(counter)d matching countries", number=counter, ) % { "counter": counter }
class TaskFilter(FilterSet): flow_task = ChoiceFilter(help_text='') created = DateRangeFilter(help_text='') process = ModelChoiceFilter(queryset=models.Process.objects.all(), help_text='') def __init__(self, data=None, queryset=None, prefix=None, strict=None): super(TaskFilter, self).__init__(data=data, queryset=queryset, prefix=prefix, strict=strict) self.filters['process'].field.queryset = \ models.Process.objects.filter(id__in=queryset.values_list('process', flat=True)) def task_name(task_ref): flow_task = import_task_by_ref(task_ref) return "{}/{}".format(flow_task.flow_class.process_title, flow_task.name.title()) tasks = [ (task_ref, task_name(task_ref)) for task_ref in queryset.order_by( 'flow_task').distinct().values_list('flow_task', flat=True) ] self.filters['flow_task'].field.choices = [(None, 'All')] + tasks class Meta: fields = ['process', 'flow_task', 'created'] model = models.Task
class StaffFilter(SortedFilterSet): name_or_email = CharFilter(label=pgettext_lazy('Staff list filter label', 'Name or email'), method=filter_by_customer) location = CharFilter(label=pgettext_lazy('Staff list filter label', 'Location'), method=filter_by_location) groups = ModelMultipleChoiceFilter(label=pgettext_lazy( 'Staff list filter label', 'Groups'), name='groups', queryset=Group.objects.all()) is_active = ChoiceFilter(label=pgettext_lazy('Staff list filter label', 'Is active'), choices=IS_ACTIVE_CHOICES, empty_label=pgettext_lazy( 'Filter empty choice label', 'All'), widget=forms.Select) sort_by = OrderingFilter(label=pgettext_lazy('Staff list filter label', 'Sort by'), fields=SORT_BY_FIELDS, field_labels=SORT_BY_FIELDS_LABELS) class Meta: model = User fields = []