Last night, as happens sometimes, I was wishing it was possible to add some of our custom admin views to the Django admin’s index page. It’s kind of a pain to have to type the URL every time, especially when talking to other people: “It’s in the admin, but no, you can’t… just go to this URL.”
So I was reading the Django admin docs and, frankly, they aren’t great. They tell you about the benefits of subclassing
AdminSite, or running multiple
AdminSites, but they never really mention how to do it.
So, with a little trial and error, I wrote my
AdminSite subclass and figured out how to use it. It simplified a bunch of code in our custom admin app, so I thought I would share it.
AdminPlus adds a method,
admin.site.register_view, that connects an arbitrary view function to your admin, and puts a link to it on the admin index page. If you put calls to
someapp/admin.py, they’re picked up during the normal
- from django.contribimport admin
- from django.shortcutsimport rendertoresponse
- def myadminview(request):
- return rendertoresponse(‘myapp/admin/view.html’)
- admin.site.registerview(‘mypath’, myadmin_view)
- # With an optional ‘name’ parameter:
- def myotheradmin_view(request):
- return rendertoresponse(‘myapp/admin/other.html’)
- admin.site.registerview(‘otherpath’, myotheradminview, ‘Fancy Stuff!’)
admin/, this will make
admin/otherpath, but it also puts them in a new section on the admin index, so you don’t even need to worry about the URL.
If no name is given we try to guess from the name of the view function.