Skip to content

Instantly share code, notes, and snippets.

@kezabelle
Last active December 24, 2015 12:09
Show Gist options
  • Save kezabelle/6795421 to your computer and use it in GitHub Desktop.
Save kezabelle/6795421 to your computer and use it in GitHub Desktop.
Get the Django AdminSite.index() method, from any URL in the admin, in a template tag... hmm.
# there must be a better way :|
current_view = resolve(request.path)
root_url = reverse('%s:index' % current_view.app_name)
index_view = resolve(root_url)
# getting the actual AdminSite instance.
# This works on Python 2.
adminsite = index_view.func.func_closure[0].cell_contents
# this works on Python 2 and 3, because Python 3 seems to lack
# func_closure, and Python 2/3 have different ordering for the
# cells in __closure__ ...
# SIGH.
try:
adminsite = next(x.cell_contents for x in index_view.func.__closure__
if isinstance(x.cell_contents, AdminSite))
except StopIteration as e:
adminsite = None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment