Django Filter | Collapsed by Default

Question:

I have a Django admin panel. In list filter I have a lot of filters. So when loading the page for the first time its not a pleasant sight to see all the filters so what I am trying to do is hide list filter by default and then if user clicks on it it opens up. Is there any option in Django admin to handle this? How can I make the filters collapsed by Default?

Asked By: planet260

||

Answers:

I happened upon your question while looking for a way to have my fieldsets in the admin panel be collapsible but not collapsed by default.

I’m following this guide: https://docs.djangoproject.com/en/1.8/intro/tutorial02/

Here’s a code snippet:

class QuestionAdmin(admin.ModelAdmin):
    fieldsets = [
        ('Question information',               {'fields': ['question_text']}),
        ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]

Adding the collapse class to the ‘Date information’ fieldset made it collapsed by default and provides a show/hide button.

Answered By: Gusty

Yes, you can make the filters collapsed by default in the Django admin by using JavaScript.
You can add a JavaScript script that will hide the filter elements when the page is loaded and then show them when a button is clicked.
You can include this script in the admin template file or you can include it in a static file and include that file in the admin template.
Here is an example of the script you can use to hide the filter elements by default:

<script>
    document.addEventListener("DOMContentLoaded", function(){
        var filters = document.getElementsByClassName("filters");
        for (var i = 0; i < filters.length; i++) {
            filters[i].style.display = "none";
        }

        var button = document.getElementById("show-filters-button");
        button.addEventListener("click", function(){
            for (var i = 0; i < filters.length; i++) {
                filters[i].style.display = "block";
            }
        });
    });
</script>

This script will hide all elements with the class "filters" when the page is loaded and show them when a button with the id "show-filters-button" is clicked.
You can add the button in the admin template using the following code

<button id="show-filters-button" type="button">Show Filters</button>

You can also add the script in the media attribute of the ModelAdmin class

class MyModelAdmin(admin.ModelAdmin):
    ...
    media = (
        '<script>...</script>',
    )

It’s important to note that this is just one example, and you may need to adjust the script to match the specific structure of your Django admin page.

Answered By: planet260