(1, 9), (10, 19), (20, 29), (30, 39), (40, 49), (50, 59), (60, 'Inf'), ) for lookup in count_ranges: title = '%s ~ %s' % lookup yield { 'selected': smart_text(lookup[0]) == '%0d' % (self.lookup_kwarg_gte_val or 0) and smart_text(lookup[1]) == '%0d' % (self.lookup_kwarg_lte_val or 0), 'query_string': changelist.get_query_string( { self.lookup_kwarg_gte: lookup[0], self.lookup_kwarg_lt: lookup[1] }, [self.lookup_kwarg_gte, self.lookup_kwarg_lt]), 'display': title, } FieldListFilter.register(lambda f: bool(f.choices), AgentInviteCountFieldListFilter)
return [self.lookup_kwarg, self.lookup_kwarg_isnull] def has_output(self): choices_count = len(self.objects) fld = self.field if (isinstance(fld, ForeignObjectRel) and fld.field.null or hasattr(fld, 'rel') and fld.null): choices_count += 1 return choices_count > 1 def label(self, obj): return '{0} {1}'.format(self.level_indicator * obj.get_level(), smart_text(obj)) def queryset(self, request, queryset): if self.lookup_val_isnull: return queryset.filter(**{self.lookup_kwarg_isnull: True}) elif self.lookup_val is not None: obj = self.other_model._default_manager.get(pk=self.lookup_val) objects = obj.get_descendants(include_self=True) return queryset.filter(**{self.lookup_kwarg: objects}) FieldListFilter.register( lambda fld: (fld.remote_field is not None and issubclass( fld.remote_field.model, Nestable) or isinstance(fld, ForeignObjectRel) and issubclass(fld.field.remote_field.model, Nestable)), NestableFieldListFilter, take_priority=True, )
def __new__(cls, *args, **kwargs): instance = FieldListFilter.create(*args, **kwargs) instance.title = title return instance
} none_title = '' for lookup, title in self.field.flatchoices: if lookup is None: none_title = title continue yield { 'selected': str(lookup) == str(self.lookup_val), 'query_string': changelist.get_query_string({self.lookup_kwarg: lookup}, [self.lookup_kwarg_isnull]), 'display': title, } if none_title: yield { 'selected': bool(self.lookup_val_isnull), 'query_string': changelist.get_query_string({self.lookup_kwarg_isnull: 'True'}, [self.lookup_kwarg]), 'display': none_title, } FieldListFilter.register(lambda f: bool(f.choices), DefaultChoicesFieldListFilter, take_priority=True)
yield { 'selected': self.month() == 0, 'this_year': today.year, 'year': self.year(), 'value': 0, 'query_string': changelist.get_query_string({}, ['month', 'year']), 'label': 'Not set', 'param_month_name': self.param_month_name, 'param_year_name': self.param_year_name, } for num, name in MONTHS.items(): yield { 'selected': num == self.month(), 'this_year': today.year, # this is tricky... 'year': self.year(), # this is tricky... 'value': num, 'query_string': changelist.get_query_string({}, ['month', 'year']), 'label': name, } def queryset(self, request, queryset): if self.month(): date = datetime(self.year(), self.month(), 1) return queryset.filter(month=date) return queryset FieldListFilter.register(lambda f: isinstance(f, MonthField), MonthAdminFilter, True)
class ForUserRelatedListFilter(RelatedFieldListFilter): def field_choices(self, field, request, model_admin): other_model = get_model_from_relation(field) qs = other_model.objects.exclude(**{field.related_query_name(): None}) if isinstance(model_admin, ForUserAdminMixin): if hasattr(qs, 'for_user'): qs = qs.for_user(request.user) return [(x._get_pk_val(), smart_text(x)) for x in qs] # Apply automatically as default admin filter on import FieldListFilter.register( lambda field: (bool(field.rel) if hasattr(field, 'rel') else isinstance(field, ForeignObjectRel)), ForUserRelatedListFilter, take_priority=True) class ForUserAdminMixin(ForUserBaseMixin, BaseModelAdmin): def get_form(self, request, obj=None, **kwargs): form = super(ForUserAdminMixin, self).get_form(request, obj, **kwargs) self.filter_form(form, request, obj) return form def get_formset(self, request, obj=None, **kwargs): formset = super(ForUserAdminMixin, self).get_formset(request, obj, **kwargs) self.filter_form(formset.form, request, obj) return formset
'query_string': cl.get_query_string({ self.lookup_kwarg: val, }, [self.lookup_kwarg_isnull]), 'prefix': prefix[0] if len(prefix)>1 else "", 'display': prefix[1] if len(prefix)>1 else val, } if include_none: yield { 'selected': bool(self.lookup_val_isnull), 'query_string': cl.get_query_string({ self.lookup_kwarg_isnull: 'True', }, [self.lookup_kwarg]), 'display': EMPTY_CHANGELIST_VALUE, } FieldListFilter.register(lambda f: isinstance(f, URIField), URIRefFieldFilter, take_priority=True) class LiteralFieldFilter(AllValuesFieldListFilter): def queryset(self, request, queryset): try: uri_ref = self.used_parameters.pop(self.lookup_kwarg, None) if uri_ref: splitted = uri_ref.split("^^^^") literal = Literal(splitted[0], datatype=URIRef(splitted[1])) if len(splitted)>1 and splitted[1] else Literal(splitted[0]) self.used_parameters[self.lookup_kwarg] = literal return queryset.filter(**self.used_parameters) except ValidationError as e: raise IncorrectLookupParameters(e) def choices(self, cl): from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
field, request, params, model, model_admin, field_path) def expected_parameters(self): return [self.lookup_kwarg_since, self.lookup_kwarg_until] def choices(self, cl): for title, param_dict in self.links: yield { 'selected': self.date_params == param_dict, 'query_string': cl.get_query_string( param_dict, [self.field_generic]), 'display': title, } FieldListFilter.register( lambda f: isinstance(f, models.DateField), DateScheduleFilter) class DateFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): self.field_generic = '%s__' % field_path self.date_params = dict([(k, v) for k, v in params.items() if k.startswith(self.field_generic)]) now = timezone.now() # When time zone support is enabled, convert "now" to the user's time # zone so Django's definition of "Today" matches what the user expects. if now.tzinfo is not None: current_tz = timezone.get_current_timezone() now = now.astimezone(current_tz) if hasattr(current_tz, 'normalize'):
from .forms import ForUserBaseMixin class ForUserRelatedListFilter(RelatedFieldListFilter): def field_choices(self, field, request, model_admin): other_model = get_model_from_relation(field) qs = other_model.objects.exclude(**{field.related_query_name(): None}) if isinstance(model_admin, ForUserAdminMixin): if hasattr(qs, 'for_user'): qs = qs.for_user(request.user) return [(x._get_pk_val(), smart_text(x)) for x in qs] # Apply automatically as default admin filter on import FieldListFilter.register(lambda field: ( bool(field.rel) if hasattr(field, 'rel') else isinstance(field, ForeignObjectRel)), ForUserRelatedListFilter, take_priority=True) class ForUserAdminMixin(ForUserBaseMixin, BaseModelAdmin): def get_form(self, request, obj=None, **kwargs): form = super(ForUserAdminMixin, self).get_form(request, obj, **kwargs) self.filter_form(form, request, obj) return form def get_formset(self, request, obj=None, **kwargs): formset = super(ForUserAdminMixin, self).get_formset( request, obj, **kwargs) self.filter_form(formset.form, request, obj) return formset
from django.contrib.admin import FieldListFilter from django.db import models from .filters import NumericFieldListFilter FieldListFilter.register(lambda f: isinstance(f, (models.IntegerField, models.FloatField, models.DecimalField)), NumericFieldListFilter, True)
nq[p] = v return nq class ExistingListFilter(SimpleListFilter): """ List filter. Show only species present in list """ def choices(self, cl): yield { "selected": self.lookup_val is None, "query_string": cl.get_query_string({}, [self.lookup_kwarg]), "display": _("All") } used = set(self.field.model.objects.distinct().values_list( self.field.name, flat=True)) for k, v in self.field.flatchoices: if k in used: yield { "selected": smart_unicode(k) == self.lookup_val, "query_string": cl.get_query_string({self.lookup_kwarg: k}), "display": v } # Install specific filters to all models FieldListFilter.register( lambda f: getattr(f, "existing_choices_filter", False), ExistingListFilter)
( _("Last month"), { "%s__year" % self.field_path: str(one_month_ago.year), "%s__month" % self.field_path: str(one_month_ago.month), }, ), ( _("This month"), {"%s__year" % self.field_path: str(today.year), "%s__month" % self.field_path: str(today.month)}, ), (_("This year"), {"%s__year" % self.field_path: str(today.year)}), ) FieldListFilter.register(lambda f: f.name == "estimated_through_date", DateFieldListFilter) FieldListFilter.register(lambda f: f.name == "through_date", DateFieldListFilter) FieldListFilter.register(lambda f: f.name == "estimated_perception_date", DateFieldListFilter) FieldListFilter.register(lambda f: f.name == "perception_date", DateFieldListFilter) class InvoiceChangeList(ChangeList): columns_with_total = [ {"column": "quantity", "name": "Quantity total", "lambda": lambda x: x}, {"column": "quantity_iva", "name": "Quantity total (IVA included)", "lambda": lambda x: x}, ] # TOTALS SUPPORT IN FILTERING def get_results(self, *args, **kwargs): super(InvoiceChangeList, self).get_results(*args, **kwargs)
# -*- coding: utf-8 -*- from django.contrib.admin import AllValuesFieldListFilter, FieldListFilter from django.utils.translation import gettext_lazy as _ _ALL = _('All') class TemplateFieldListFilter(AllValuesFieldListFilter): def choices(self, changelist): for choice in super(TemplateFieldListFilter, self).choices(changelist=changelist): if choice['display'] == _ALL: yield choice else: choice['display'] = self.field.display_name(choice['display']) yield choice from templateselector.fields import TemplateField FieldListFilter.register(lambda f: isinstance(f, TemplateField), TemplateFieldListFilter, take_priority=True)
from django.contrib.admin import FieldListFilter from django.db import models from .filters import NumericFieldListFilter FieldListFilter.register( lambda f: isinstance(f, (models.IntegerField, models.FloatField, models. DecimalField)), NumericFieldListFilter, True)
self.links = ( (_('Any date'), {}), (_('Today'), {'%s__year' % self.field_path: str(today.year), '%s__month' % self.field_path: str(today.month), '%s__day' % self.field_path: str(today.day)}), (_('Past 7 days'), {'%s__gte' % self.field_path: one_week_ago.strftime('%Y-%m-%d'), '%s__lte' % self.field_path: today_str}), (_('Last month'), {'%s__year' % self.field_path: str(one_month_ago.year), '%s__month' % self.field_path: str(one_month_ago.month)}), (_('This month'), {'%s__year' % self.field_path: str(today.year), '%s__month' % self.field_path: str(today.month)}), (_('This year'), {'%s__year' % self.field_path: str(today.year)}) ) FieldListFilter.register(lambda f: f.name == 'estimated_through_date', DateFieldListFilter) FieldListFilter.register(lambda f: f.name == 'through_date', DateFieldListFilter) FieldListFilter.register(lambda f: f.name == 'estimated_perception_date', DateFieldListFilter) FieldListFilter.register(lambda f: f.name == 'perception_date', DateFieldListFilter) class InvoiceChangeList(ChangeList): columns_with_total = [ { 'column': 'quantity', 'name': 'Quantity total', 'lambda': lambda x: x, }, { 'column': 'quantity_iva',
def __init__(self, model, admin_site): FieldListFilter.register(lambda f: bool(f.choices), ChoicesFieldComboFilter, True) FieldListFilter.register(lambda f: isinstance(f, models.BooleanField), AllValuesComboFilter, True) FieldListFilter.register(lambda f: f.remote_field, RelatedFieldComboFilter, True) super().__init__(model, admin_site)