├── .github └── workflows │ └── python-publish.yml ├── .gitignore ├── LICENSE ├── README.md ├── pyproject.toml └── src └── django_admin_multi_select_filter ├── __init__.py └── filters.py /.github/workflows/python-publish.yml: -------------------------------------------------------------------------------- 1 | name: Upload Python Package 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | permissions: 8 | contents: read 9 | 10 | jobs: 11 | deploy: 12 | 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v3 17 | - name: Set up Python 18 | uses: actions/setup-python@v3 19 | with: 20 | python-version: '3.9' 21 | - name: Install dependencies 22 | run: | 23 | python -m pip install --upgrade pip 24 | pip install build 25 | - name: Build package 26 | run: python -m build 27 | - name: Publish package 28 | uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29 29 | with: 30 | user: __token__ 31 | password: ${{ secrets.PYPI_API_TOKEN }} 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Job Doesburg 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Django admin multi-select filter 2 | 3 | Django admin multi-select filter is a Django app that allows you to add a multi-select filter to the Django admin. 4 | 5 | ## Installation 6 | 1. Install using pip: 7 | ```bash 8 | pip install django-admin-multi-select-filter 9 | ``` 10 | 2. Use the `MultiSelectFilter` (or `MultiSelectRelatedFieldListFilter` when using on related fields) in your admin classes (you do **not** need to add the app to `INSTALLED_APPS`): 11 | ```python 12 | from django.contrib import admin 13 | from django_admin_multi_select_filter.filters import MultiSelectFieldListFilter 14 | 15 | class MyModelAdmin(admin.ModelAdmin): 16 | list_filter = ( 17 | ... 18 | ('my_field', MultiSelectFieldListFilter), 19 | ... 20 | ) 21 | ``` -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "django-admin-multi-select-filter" 3 | version = "1.4.1" 4 | description = "Django admin filter for multiple select" 5 | readme = "README.md" 6 | authors = [{ name = "Job Doesburg", email = "job.doesburg@gmail.com" }] 7 | license = { file = "LICENSE" } 8 | classifiers = [ 9 | "License :: OSI Approved :: MIT License", 10 | "Programming Language :: Python", 11 | "Programming Language :: Python :: 3", 12 | "Framework :: Django", 13 | "Framework :: Django :: 3.0", 14 | "Framework :: Django :: 3.1", 15 | "Framework :: Django :: 3.2", 16 | "Framework :: Django :: 4.0", 17 | "Framework :: Django :: 4.1", 18 | "Framework :: Django :: 4.2", 19 | "Framework :: Django :: 5.0", 20 | "Intended Audience :: Developers", 21 | "Operating System :: OS Independent", 22 | ] 23 | dependencies = [ 24 | "django>=3", 25 | ] 26 | requires-python = ">=3" 27 | 28 | [project.urls] 29 | homepage = "https://github.com/JobDoesburg/django-admin-multi-select-filter" 30 | repository = "https://github.com/JobDoesburg/django-admin-multi-select-filter" 31 | documentation = "https://github.com/JobDoesburg/django-admin-multi-select-filter" 32 | 33 | [build-system] 34 | requires = ["setuptools>=61.0.0", "wheel"] 35 | build-backend = "setuptools.build_meta" 36 | 37 | [tool.setuptools.packages.find] 38 | where = ["src"] 39 | 40 | [tool.setuptools.package-data] 41 | "*" = ["*.html"] 42 | -------------------------------------------------------------------------------- /src/django_admin_multi_select_filter/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JobDoesburg/django-admin-multi-select-filter/a4dac810a155f30114a9b1146e465ce4248d73bb/src/django_admin_multi_select_filter/__init__.py -------------------------------------------------------------------------------- /src/django_admin_multi_select_filter/filters.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.contrib.admin.options import IncorrectLookupParameters 3 | from django.contrib.admin.utils import reverse_field_path 4 | from django.core.exceptions import ValidationError 5 | from django.db.models import Count, Q 6 | from django.utils.translation import gettext_lazy as _ 7 | 8 | 9 | class MultiSelectFieldListFilter(admin.FieldListFilter): 10 | def __init__(self, field, request, params, model, model_admin, field_path): 11 | self.lookup_kwarg = field_path + "__in" 12 | self.lookup_kwarg_isnull = field_path + "__isnull" 13 | 14 | super().__init__(field, request, params, model, model_admin, field_path) 15 | 16 | self.lookup_val = self.used_parameters.get(self.lookup_kwarg, []) 17 | if len(self.lookup_val) == 1 and self.lookup_val[0] == "": 18 | self.lookup_val = [] 19 | elif len(self.lookup_val) == 1 and type(self.lookup_val[0]) != str: 20 | # In Django 5.0, we get an extra list 21 | self.lookup_val = self.lookup_val[0] 22 | self.lookup_val_isnull = self.used_parameters.get(self.lookup_kwarg_isnull) 23 | 24 | self.empty_value_display = model_admin.get_empty_value_display() 25 | parent_model, reverse_path = reverse_field_path(model, field_path) 26 | # Obey parent ModelAdmin queryset when deciding which options to show 27 | if model == parent_model: 28 | queryset = model_admin.get_queryset(request) 29 | else: 30 | queryset = parent_model._default_manager.all() 31 | self.lookup_choices = ( 32 | queryset.distinct().order_by(field.name).values_list(field.name, flat=True) 33 | ) 34 | self.field_verboses = {} 35 | if self.field.choices: 36 | self.field_verboses = { 37 | field_value: field_verbose 38 | for field_value, field_verbose in self.field.choices 39 | } 40 | 41 | def expected_parameters(self): 42 | return [self.lookup_kwarg, self.lookup_kwarg_isnull] 43 | 44 | def choices(self, changelist): 45 | yield { 46 | "selected": not self.lookup_val and self.lookup_val_isnull is None, 47 | "query_string": changelist.get_query_string( 48 | remove=[self.lookup_kwarg, self.lookup_kwarg_isnull] 49 | ), 50 | "display": _("All"), 51 | } 52 | include_none = False 53 | for val in self.lookup_choices: 54 | if val is None: 55 | include_none = True 56 | continue 57 | val = str(val) 58 | 59 | if val in self.lookup_val: 60 | values = [v for v in self.lookup_val if v != val] 61 | else: 62 | values = self.lookup_val + [val] 63 | 64 | if values: 65 | yield { 66 | "selected": val in self.lookup_val, 67 | "query_string": changelist.get_query_string( 68 | {self.lookup_kwarg: ",".join(values)}, 69 | [self.lookup_kwarg_isnull], 70 | ), 71 | "display": self.field_verboses.get(val, val), 72 | } 73 | else: 74 | yield { 75 | "selected": val in self.lookup_val, 76 | "query_string": changelist.get_query_string( 77 | remove=[self.lookup_kwarg] 78 | ), 79 | "display": self.field_verboses.get(val, val), 80 | } 81 | 82 | if include_none: 83 | yield { 84 | "selected": bool(self.lookup_val_isnull), 85 | "query_string": changelist.get_query_string( 86 | {self.lookup_kwarg_isnull: "True"}, [self.lookup_kwarg] 87 | ), 88 | "display": self.empty_value_display, 89 | } 90 | 91 | 92 | class MultiSelectRelatedFieldListFilter(admin.RelatedFieldListFilter): 93 | def __init__(self, field, request, params, model, model_admin, field_path): 94 | super().__init__(field, request, params, model, model_admin, field_path) 95 | self.lookup_kwarg = "%s__%s__in" % (field_path, field.target_field.name) 96 | self.lookup_kwarg_isnull = "%s__isnull" % field_path 97 | values = params.get(self.lookup_kwarg, []) 98 | if len(values) == 1 and type(values[0]) != str: 99 | # In Django 5.0, we get an extra list 100 | values = values[0] 101 | self.lookup_val = values.split(",") if values else [] 102 | self.lookup_choices = self.field_choices(field, request, model_admin) 103 | 104 | def choices(self, changelist): 105 | yield { 106 | "selected": (self.lookup_val is None or self.lookup_val == []) 107 | and not self.lookup_val_isnull, 108 | "query_string": changelist.get_query_string( 109 | remove=[self.lookup_kwarg, self.lookup_kwarg_isnull] 110 | ), 111 | "display": _("All"), 112 | } 113 | 114 | for pk_val, val in self.lookup_choices: 115 | if val is None: 116 | self.include_empty_choice = True 117 | continue 118 | val = str(val) 119 | 120 | if str(pk_val) in self.lookup_val: 121 | values = [str(v) for v in self.lookup_val if str(v) != str(pk_val)] 122 | else: 123 | values = self.lookup_val + [str(pk_val)] 124 | 125 | yield { 126 | "selected": self.lookup_val is not None 127 | and str(pk_val) in self.lookup_val, 128 | "query_string": changelist.get_query_string( 129 | {self.lookup_kwarg: ",".join(values)}, [self.lookup_kwarg_isnull] 130 | ), 131 | "display": val, 132 | } 133 | empty_title = self.empty_value_display 134 | if self.include_empty_choice: 135 | yield { 136 | "selected": bool(self.lookup_val_isnull), 137 | "query_string": changelist.get_query_string( 138 | {self.lookup_kwarg_isnull: "True"}, [self.lookup_kwarg] 139 | ), 140 | "display": empty_title, 141 | } 142 | 143 | 144 | class ExclusiveMultiSelectRelatedFieldListFilter(MultiSelectRelatedFieldListFilter): 145 | def queryset(self, request, queryset): 146 | try: 147 | if self.lookup_val_isnull: 148 | return queryset.filter(**{self.lookup_kwarg_isnull: True}) 149 | 150 | choices = self.lookup_val 151 | choice_len = len(choices) 152 | if choice_len == 0: 153 | return queryset 154 | 155 | queryset = queryset.alias( 156 | nmatch=Count( 157 | self.field_path, 158 | filter=Q(**{f'{self.lookup_kwarg}': choices}), 159 | distinct=True 160 | ) 161 | ).filter(nmatch=choice_len) 162 | return queryset 163 | 164 | except (ValueError, ValidationError) as e: 165 | raise IncorrectLookupParameters(e) 166 | --------------------------------------------------------------------------------