File: filters.py

package info (click to toggle)
django-polymorphic 4.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 892 kB
  • sloc: python: 6,784; javascript: 263; makefile: 137
file content (37 lines) | stat: -rw-r--r-- 1,196 bytes parent folder | download | duplicates (2)
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
from django.contrib import admin
from django.core.exceptions import PermissionDenied
from django.utils.translation import gettext_lazy as _


class PolymorphicChildModelFilter(admin.SimpleListFilter):
    """
    An admin list filter for the PolymorphicParentModelAdmin which enables
    filtering by its child models.

    This can be used in the parent admin:

    .. code-block:: python

        list_filter = (PolymorphicChildModelFilter,)
    """

    title = _("Type")
    parameter_name = "polymorphic_ctype"

    def lookups(self, request, model_admin):
        return model_admin.get_child_type_choices(request, "change")

    def queryset(self, request, queryset):
        try:
            value = int(self.value())
        except TypeError:
            value = None
        if value:
            # ensure the content type is allowed
            for choice_value, _ in self.lookup_choices:  # noqa: F402
                if choice_value == value:
                    return queryset.filter(polymorphic_ctype_id=choice_value)
            raise PermissionDenied(
                f'Invalid ContentType "{value}". It must be registered as child model.'
            )
        return queryset