|
| 1 | +""" |
| 2 | +FilterSpec encapsulates the logic for displaying filters in the Django admin. |
| 3 | +Filters are specified in models with the "list_filter" option. |
| 4 | +
|
| 5 | +Each filter subclass knows how to display a filter for a field that passes a |
| 6 | +certain test -- e.g. being a DateField or ForeignKey. |
| 7 | +""" |
| 8 | + |
| 9 | +from django.core import meta |
| 10 | +import datetime |
| 11 | + |
| 12 | +class FilterSpec(object): |
| 13 | + filter_specs = [] |
| 14 | + def __init__(self, f, request, params): |
| 15 | + self.field = f |
| 16 | + self.params = params |
| 17 | + |
| 18 | + def register(cls, test, factory): |
| 19 | + cls.filter_specs.append( (test, factory) ) |
| 20 | + register = classmethod(register) |
| 21 | + |
| 22 | + def create(cls, f, request, params): |
| 23 | + for test, factory in cls.filter_specs: |
| 24 | + if test(f): |
| 25 | + return factory(f, request, params) |
| 26 | + create = classmethod(create) |
| 27 | + |
| 28 | + def has_output(self): |
| 29 | + return True |
| 30 | + |
| 31 | + def choices(self, cl): |
| 32 | + raise NotImplementedError() |
| 33 | + |
| 34 | + def title(self): |
| 35 | + return self.field.verbose_name |
| 36 | + |
| 37 | + def output(self, cl): |
| 38 | + t = [] |
| 39 | + if self.has_output(): |
| 40 | + t.append(_('<h3>By %s:</h3>\n<ul>\n') % self.title()) |
| 41 | + |
| 42 | + for choice in self.choices(cl): |
| 43 | + t.append('<li%s><a href="%s">%s</a></li>\n' % \ |
| 44 | + ((choice['selected'] and ' class="selected"' or ''), |
| 45 | + choice['query_string'] , |
| 46 | + choice['display'])) |
| 47 | + t.append('</ul>\n\n') |
| 48 | + return "".join(t) |
| 49 | + |
| 50 | +class RelatedFilterSpec(FilterSpec): |
| 51 | + def __init__(self, f, request, params): |
| 52 | + super(RelatedFilterSpec, self).__init__(f, request, params) |
| 53 | + if isinstance(f, meta.ManyToManyField): |
| 54 | + self.lookup_title = f.rel.to.verbose_name |
| 55 | + else: |
| 56 | + self.lookup_title = f.verbose_name |
| 57 | + self.lookup_kwarg = '%s__%s__exact' % (f.name, f.rel.to.pk.name) |
| 58 | + self.lookup_val = request.GET.get(self.lookup_kwarg, None) |
| 59 | + self.lookup_choices = f.rel.to.get_model_module().get_list() |
| 60 | + |
| 61 | + def has_output(self): |
| 62 | + return len(self.lookup_choices) > 1 |
| 63 | + |
| 64 | + def title(self): |
| 65 | + return self.lookup_title |
| 66 | + |
| 67 | + def choices(self, cl): |
| 68 | + yield {'selected': self.lookup_val is None, |
| 69 | + 'query_string': cl.get_query_string({}, [self.lookup_kwarg]), |
| 70 | + 'display': _('All')} |
| 71 | + for val in self.lookup_choices: |
| 72 | + pk_val = getattr(val, self.field.rel.to.pk.attname) |
| 73 | + yield {'selected': self.lookup_val == str(pk_val), |
| 74 | + 'query_string': cl.get_query_string( {self.lookup_kwarg: pk_val}), |
| 75 | + 'display': val} |
| 76 | + |
| 77 | +FilterSpec.register(lambda f: bool(f.rel), RelatedFilterSpec) |
| 78 | + |
| 79 | +class ChoicesFilterSpec(FilterSpec): |
| 80 | + def __init__(self, f, request, params): |
| 81 | + super(ChoicesFilterSpec, self).__init__(f, request, params) |
| 82 | + self.lookup_kwarg = '%s__exact' % f.name |
| 83 | + self.lookup_val = request.GET.get(self.lookup_kwarg, None) |
| 84 | + |
| 85 | + def choices(self, cl): |
| 86 | + yield {'selected': self.lookup_val is None, |
| 87 | + 'query_string': cl.get_query_string( {}, [self.lookup_kwarg]), |
| 88 | + 'display': _('All')} |
| 89 | + for k, v in self.field.choices: |
| 90 | + yield {'selected': str(k) == self.lookup_val, |
| 91 | + 'query_string': cl.get_query_string( {self.lookup_kwarg: k}), |
| 92 | + 'display': v} |
| 93 | + |
| 94 | +FilterSpec.register(lambda f: bool(f.choices), ChoicesFilterSpec) |
| 95 | + |
| 96 | +class DateFieldFilterSpec(FilterSpec): |
| 97 | + def __init__(self, f, request, params): |
| 98 | + super(DateFieldFilterSpec, self).__init__(f, request, params) |
| 99 | + |
| 100 | + self.field_generic = '%s__' % self.field.name |
| 101 | + |
| 102 | + self.date_params = dict([(k, v) for k, v in params.items() if k.startswith(self.field_generic)]) |
| 103 | + |
| 104 | + today = datetime.date.today() |
| 105 | + one_week_ago = today - datetime.timedelta(days=7) |
| 106 | + today_str = isinstance(self.field, meta.DateTimeField) and today.strftime('%Y-%m-%d 23:59:59') or today.strftime('%Y-%m-%d') |
| 107 | + |
| 108 | + self.links = ( |
| 109 | + (_('Any date'), {}), |
| 110 | + (_('Today'), {'%s__year' % self.field.name: str(today.year), |
| 111 | + '%s__month' % self.field.name: str(today.month), |
| 112 | + '%s__day' % self.field.name: str(today.day)}), |
| 113 | + (_('Past 7 days'), {'%s__gte' % self.field.name: one_week_ago.strftime('%Y-%m-%d'), |
| 114 | + '%s__lte' % f.name: today_str}), |
| 115 | + (_('This month'), {'%s__year' % self.field.name: str(today.year), |
| 116 | + '%s__month' % f.name: str(today.month)}), |
| 117 | + (_('This year'), {'%s__year' % self.field.name: str(today.year)}) |
| 118 | + ) |
| 119 | + |
| 120 | + def title(self): |
| 121 | + return self.field.verbose_name |
| 122 | + |
| 123 | + def choices(self, cl): |
| 124 | + for title, param_dict in self.links: |
| 125 | + yield {'selected': self.date_params == param_dict, |
| 126 | + 'query_string': cl.get_query_string( param_dict, self.field_generic), |
| 127 | + 'display': title} |
| 128 | + |
| 129 | +FilterSpec.register(lambda f: isinstance(f, meta.DateField), DateFieldFilterSpec) |
| 130 | + |
| 131 | +class BooleanFieldFilterSpec(FilterSpec): |
| 132 | + def __init__(self, f, request, params): |
| 133 | + super(BooleanFieldFilterSpec, self).__init__(f, request, params) |
| 134 | + self.lookup_kwarg = '%s__exact' % f.name |
| 135 | + self.lookup_kwarg2 = '%s__isnull' % f.name |
| 136 | + self.lookup_val = request.GET.get(self.lookup_kwarg, None) |
| 137 | + self.lookup_val2 = request.GET.get(self.lookup_kwarg2, None) |
| 138 | + |
| 139 | + def title(self): |
| 140 | + return self.field.verbose_name |
| 141 | + |
| 142 | + def choices(self, cl): |
| 143 | + for k, v in ((_('All'), None), (_('Yes'), '1'), (_('No'), '0')): |
| 144 | + yield {'selected': self.lookup_val == v and not self.lookup_val2, |
| 145 | + 'query_string': cl.get_query_string( {self.lookup_kwarg: v}, [self.lookup_kwarg2]), |
| 146 | + 'display': k} |
| 147 | + if isinstance(self.field, meta.NullBooleanField): |
| 148 | + yield {'selected': self.lookup_val2 == 'True', |
| 149 | + 'query_string': cl.get_query_string( {self.lookup_kwarg2: 'True'}, [self.lookup_kwarg]), |
| 150 | + 'display': _('Unknown')} |
| 151 | + |
| 152 | +FilterSpec.register(lambda f: isinstance(f, meta.BooleanField) or isinstance(f, meta.NullBooleanField), BooleanFieldFilterSpec) |
0 commit comments