Home > Back-end >  How to create a subsection in django admin site of a model with some special filters?
How to create a subsection in django admin site of a model with some special filters?

Time:01-10

I have a Law model and a custom command that amend Laws every 20 days. Now I want to email the admin that Laws are amended with a link redirecting to the admin site.

In the admin section, I need a subsection of laws named LatestAmendedLaws that filters all the recently amended laws, so the admin can verify if laws are correctly amended.

Here is the admin.py of Laws:

@admin.register(Law)
class LawAdmin(admin.ModelAdmin):
    list_display = (
        'id',
        'rs_number',
        'created'
    )

usually when a law is amended the created date updates. so we can filter with the created date.

CodePudding user response:

You can create additional Admin page on proxy model of Law.

models.py:

class LatestAmendedLaws(Law):
    class Meta:
        proxy = True
        verbose_name = "Latest Amended Laws"

then in admins.py:

from datetime import date, timedelta

@admin.register(LatestAmendedLaws)
class LatestAmendedLawsAdmin(admin.ModelAdmin):
    list_display = (
        'id',
        'rs_number',
        'created'
    )

    def get_queryset(self, request):
        return super().get_queryset(request).filter(created__gte=datetime.now() - timedelta(days=20))
  • Related