Samuel Muiruri
Samuel Muiruri

Reputation: 522

Add default filter to django admin

I've got a model with boolean fields visible and hidden in using the admin.py I think it's possible to add a default filter to the page /admin/articles/article/ so it has filter by visible=True and hidden=True

class ArticleAdmin(admin.ModelAdmin):
    list filter = [...]
    ...
    def changelist_view(self, request, extra_context=None):
        if not request.GET: #No filter
            #Perform filter to queryset for visible and hidden = True
        return super(ArticleAdmin,self).changelist_view(request, extra_context=extra_context)

Upvotes: 1

Views: 2109

Answers (1)

Satendra
Satendra

Reputation: 6865

Register your model in admin.py file and mention your model fields in list_filter property.

class ArticleAdmin(admin.ModelAdmin):

    list_filter=["hidden", "visible", "created", "modified"],
    ...

    def changelist_view(self, request, extra_context=None):
       if not request.GET: #No filter
          #Perform filter to queryset for visible and hidden = True
          return super(ArticleAdmin,self).changelist_view(request, extra_context=extra_context)

hope that helps!

Upvotes: 1

Related Questions