File: admin.py

package info (click to toggle)
django-bitfield 1.9.6-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 180 kB
  • sloc: python: 931; makefile: 4
file content (48 lines) | stat: -rw-r--r-- 1,657 bytes parent folder | download | duplicates (3)
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
import six

from django.db.models import F
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from django.contrib.admin import FieldListFilter
from django.contrib.admin.options import IncorrectLookupParameters

from bitfield import Bit
from bitfield.compat import bitor


class BitFieldListFilter(FieldListFilter):
    """
    BitField list filter.
    """

    def __init__(self, field, request, params, model, model_admin, field_path):
        self.lookup_kwarg = field_path
        self.lookup_val = int(request.GET.get(self.lookup_kwarg, 0))
        self.flags = field.flags
        self.labels = field.labels
        super(BitFieldListFilter, self).__init__(
            field, request, params, model, model_admin, field_path)

    def queryset(self, request, queryset):
        filter = dict((p, bitor(F(p), v)) for p, v in six.iteritems(self.used_parameters))
        try:
            return queryset.filter(**filter)
        except ValidationError as e:
            raise IncorrectLookupParameters(e)

    def expected_parameters(self):
        return [self.lookup_kwarg]

    def choices(self, cl):
        yield {
            'selected': self.lookup_val == 0,
            'query_string': cl.get_query_string({}, [self.lookup_kwarg]),
            'display': _('All'),
        }
        for number, flag in enumerate(self.flags):
            bit_mask = Bit(number).mask
            yield {
                'selected': self.lookup_val == bit_mask,
                'query_string': cl.get_query_string({self.lookup_kwarg: bit_mask}),
                'display': self.labels[number],
            }