Closure for FieldListFilter classes with custom sets of ranges

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from django.utils.translation import ugettext_lazy as _
from django.contrib.admin import FieldListFilter

def makeRangeFieldListFilter(lookups, nullable=False):
    class RangeFieldListFilter(FieldListFilter):
        def __init__(self, field, request, params, model, model_admin, field_path):
            self.field_generic = '%s__' % field_path
            self.range_params = dict([(k, v) for k, v in params.items()
                                     if k.startswith(self.field_generic)])

            self.lookup_kwarg_start = '%s__gte' % field_path
            self.lookup_kwarg_stop = '%s__lt' % field_path
            self.lookup_kwarg_null = '%s__isnull' % field_path

            self.links = [ (_('Any value'), {}), ]
            for name, start, stop in lookups:
                query_params = {}
                if start is not None:
                    query_params[self.lookup_kwarg_start] = str(start)
                if stop is not None:
                    query_params[self.lookup_kwarg_stop] = str(stop)

                self.links.append((name, query_params))

            if nullable:
                self.links.append((_('Unknown'), {
                    self.lookup_kwarg_null: 'True'
                }))

            super(RangeFieldListFilter, self).__init__(
                field, request, params, model, model_admin, field_path)

        def expected_parameters(self):
            return [
                self.lookup_kwarg_start,
                self.lookup_kwarg_stop,
                self.lookup_kwarg_null
            ]

        def choices(self, cl):
            for title, param_dict in self.links:
                yield {
                    'selected': self.range_params == param_dict,
                    'query_string': cl.get_query_string(
                                        param_dict, [self.field_generic]),
                    'display': title,
                }

    return RangeFieldListFilter

More like this

  1. Group results by a range of values in admin sidebar by wgollino 6 years, 2 months ago
  2. SuperChoices by willhardy 5 years, 5 months ago
  3. Friendly ID by willhardy 5 years, 4 months ago
  4. Time ranges like 7-9 p.m. by sgb 6 years, 3 months ago
  5. Pattern to integer list function by marinho 6 years, 4 months ago

Comments

(Forgotten your password?)