admin.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import django
  2. import six
  3. from django.core.exceptions import ValidationError
  4. if django.VERSION < (2, 0):
  5. from django.utils.translation import ugettext_lazy as _
  6. else:
  7. # Aliased since Django 2.0 https://github.com/django/django/blob/2.0/django/utils/translation/__init__.py#L80-L81
  8. from django.utils.translation import gettext_lazy as _
  9. from django.contrib.admin import FieldListFilter
  10. from django.contrib.admin.options import IncorrectLookupParameters
  11. from bitfield import Bit, BitHandler
  12. class BitFieldListFilter(FieldListFilter):
  13. """
  14. BitField list filter.
  15. """
  16. def __init__(self, field, request, params, model, model_admin, field_path):
  17. self.lookup_kwarg = field_path
  18. self.lookup_val = int(request.GET.get(self.lookup_kwarg, 0))
  19. self.flags = field.flags
  20. self.labels = field.labels
  21. super(BitFieldListFilter, self).__init__(
  22. field, request, params, model, model_admin, field_path
  23. )
  24. def queryset(self, request, queryset):
  25. filter_kwargs = dict(
  26. (p, BitHandler(v, ())) for p, v in six.iteritems(self.used_parameters)
  27. )
  28. if not filter_kwargs:
  29. return queryset
  30. try:
  31. return queryset.filter(**filter_kwargs)
  32. except ValidationError as e:
  33. raise IncorrectLookupParameters(e)
  34. def expected_parameters(self):
  35. return [self.lookup_kwarg]
  36. def choices(self, cl):
  37. yield {
  38. "selected": self.lookup_val == 0,
  39. "query_string": cl.get_query_string({}, [self.lookup_kwarg]),
  40. "display": _("All"),
  41. }
  42. for number, flag in enumerate(self.flags):
  43. bit_mask = Bit(number).mask
  44. yield {
  45. "selected": self.lookup_val == bit_mask,
  46. "query_string": cl.get_query_string({self.lookup_kwarg: bit_mask}),
  47. "display": self.labels[number],
  48. }