|
| 1 | +title: django.contrib.admin.filters SimpleListFilter Example Code |
| 2 | +category: page |
| 3 | +slug: django-contrib-admin-filters-simplelistfilter-examples |
| 4 | +sortorder: 50055 |
| 5 | +toc: False |
| 6 | +sidebartitle: django.contrib.admin.filters SimpleListFilter |
| 7 | +meta: Python code examples for using the SimpleListFilter class contained within django.contrib.admin.filters. |
| 8 | + |
| 9 | + |
| 10 | +[SimpleListFilter](https://github.com/django/django/blob/master/django/contrib/admin/filters.py) |
| 11 | +is a class within the [Django](/django.html) project which can |
| 12 | +be subclasses to customize the Django admin's lookups and querying |
| 13 | +interface. |
| 14 | + |
| 15 | +Understanding the following concepts are useful when coding projects |
| 16 | +that use Django's `SimpleListFilter` class: |
| 17 | + |
| 18 | +* [Django](/django.html) and [Django templates](/django-templates.html) |
| 19 | +* [Web development](/web-development.html), |
| 20 | + [web frameworks](/web-frameworks.html) and |
| 21 | + [HTML](/hypertext-markup-language-html.html) |
| 22 | +* [Angular](/angular.html) and [JavaScript](/javascript.html) |
| 23 | + |
| 24 | +You can also view the [complete all topics page](/table-of-contents.html) |
| 25 | +for even more resources. |
| 26 | + |
| 27 | + |
| 28 | +## Example 1 from AuditLog |
| 29 | +[Auditlog](https://github.com/jjkester/django-auditlog) |
| 30 | +([project documentation](https://django-auditlog.readthedocs.io/en/latest/)) |
| 31 | +is a [Django](/django.html) app that logs changes to Python objects, |
| 32 | +similar to the Django admin's logs but with more details and |
| 33 | +output formats. Auditlog's source code is provided as open source under the |
| 34 | +[MIT license](https://github.com/jjkester/django-auditlog/blob/master/LICENSE). |
| 35 | + |
| 36 | +[**django-auditlog / src / auditlog / filters.py**](https://github.com/jjkester/django-auditlog/blob/master/src/auditlog/filters.py) |
| 37 | + |
| 38 | +```python |
| 39 | +# filters.py |
| 40 | +~~from django.contrib.admin import SimpleListFilter |
| 41 | + |
| 42 | + |
| 43 | +~~class ResourceTypeFilter(SimpleListFilter): |
| 44 | + title = 'Resource Type' |
| 45 | + parameter_name = 'resource_type' |
| 46 | + |
| 47 | + def lookups(self, request, model_admin): |
| 48 | + qs = model_admin.get_queryset(request) |
| 49 | + types = qs.values_list('content_type_id', 'content_type__model') |
| 50 | + return list(types.order_by('content_type__model').distinct()) |
| 51 | + |
| 52 | + def queryset(self, request, queryset): |
| 53 | + if self.value() is None: |
| 54 | + return queryset |
| 55 | + return queryset.filter(content_type_id=self.value()) |
| 56 | +``` |
0 commit comments