Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin - how to get all registered models in templatetag?

I'm writing a custom admin stuff and need to get all registered models in Admin. Is this possible? I need it to make some custom views on admin index page.

like image 986
tunarob Avatar asked Mar 22 '12 09:03

tunarob


People also ask

How do I automatically register all models in Django admin?

To automate this process, we can programmatically fetch all the models in the project and register them with the admin interface. Open admin.py file and add this code to it. This will fetch all the models in all apps and registers them with the admin interface.

How can I get admin panel in Django?

To login to the site, open the /admin URL (e.g. http://127.0.0.1:8000/admin ) and enter your new superuser userid and password credentials (you'll be redirected to the login page, and then back to the /admin URL after you've entered your details).


2 Answers

You can access admin.site._registry dict of Model->ModelAdmin:

>>> ./manage.py shell

In [1]: from urls import * # load admin

In [2]: from django.contrib import admin

In [3]: admin.site._registry
Out[3]: 
{django.contrib.auth.models.Group: <django.contrib.auth.admin.GroupAdmin at 0x22629d0>,
 django.contrib.auth.models.User: <django.contrib.auth.admin.UserAdmin at 0x2262a10>,
 django.contrib.sites.models.Site: <django.contrib.sites.admin.SiteAdmin at 0x2262c90>,
 testapp.models.Up: <django.contrib.admin.options.ModelAdmin at 0x2269c10>,
 nashvegas.models.Migration: <nashvegas.admin.MigrationAdmin at 0x2262ad0>}

This is what the admin index view does:

@never_cache
def index(self, request, extra_context=None):
    """ 
    Displays the main admin index page, which lists all of the installed
    apps that have been registered in this site.
    """
    app_dict = {}
    user = request.user
    for model, model_admin in self._registry.items():
        # ...

Note that variables prefixed with an underscore are potentially subject to changes in future versions of django.

like image 136
jpic Avatar answered Sep 19 '22 03:09

jpic


You can do something like this:

from django.apps import apps

models = apps.get_models()

for model in models:
   try:
       my_custom_admin_site.register(model)
   except admin.sites.AlreadyRegistered:
       pass

apps.get_models() will give all the registered models in the default Django Admin site.

like image 38
Jay Patel Avatar answered Sep 20 '22 03:09

Jay Patel