The ChangeList
provided in Django admin is so powerful and useful. We used it in our views and were surprised at the things we can do. It was like exposing the admin change-list page to everyone, in a secure way. Adding new features or updating the display is now just a 1-2 line change in list_display
and list_filter
options.
Proof of Concept
We create a function to create a ChangeList
object from any queryset. It doesn’t need to be a model instance. Full code is here →.
We use the function like this:
queryset = Book.objects.filter(available=True)
cl = get_change_list(
title="Books available",
request=request,
queryset=queryset,
list_display=("title", "author", "price"),
list_filter=("author", "price", DeliveryFilter),
# we can define custom filters and displays just like we do in admin.py
)
context = {'cl': cl, 'opts': cl.opts}
This is how we use the above in templates:
{% load admin_list %}
<!-- render search -->
<div>{% search_form cl %}</div>
<!-- render date_hierarchy -->
{% if cl.date_hierarchy %}{% date_hierarchy cl %}{% endif %}
<!-- render results table -->
{% result_list cl %}
<!-- render pagination -->
{% pagination cl %}
<!-- render filters -->
{% if cl.has_filters %}
<div>
{% if cl.has_active_filters %}
<a href="{{ cl.clear_all_filters_qs }}">Clear all</a>
{% endif %}
<div>
{% for spec in cl.filter_specs %}
{% admin_list_filter cl spec %}
{% endfor %}
</div>
</div>
{% endif %}
All the above tags search_form
, date_hierarchy
, result_list
, pagination
and admin_list_filter
are loaded from admin_list
. We require zero code. We can still personalise everything using CSS. Just like we do with Django Forms.
Advantages
The above allows us to use these on any page.
- A search
- A date-hierarchy
- Pagination
- Filters
- Customisable table
Larger ideas
I think we can re-factor the existing ChangeList
module to make the above even easier. Just like Django forms.
The current ChangeList
module is a bit coupled with models through ModelAdmin
. It doesn’t need to be so. We can refactor it to handle any queryset. And that can allow us to use it at wider places.
Has anyone tried this? Does anyone else find this useful?