Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any official way to get the admin options of a model?

Tags:

python

django

I need to get to the search_fields property defined on the admin options for a model. A long time ago it was really simple and direct (but undocumented), i.e. model._meta.admin.search_fields.

Getting to the admin is the hard part, and the closest I could get was:

def admin_options(model):
    from django.contrib import admin
    return admin.site._registry.get(model)

I couldn't find the ._registry member documented (and the underscore seems to imply that it isn't public). This also doesn't work for sites that haven't run admin.autodiscover(). The fallback-code does this:

try:
    appname = model.__module__.split('.models')[0]
    admin_module = appname + '.admin'
    __import__(admin_module)  # registers admin option classes with AdminSite
except:
    return None
else:
   return admin.site._registry.get(model)

Is there an official (or simpler) way to get the admin options for a model?

like image 336
thebjorn Avatar asked Dec 06 '15 16:12

thebjorn


2 Answers

first create model

from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
class LocationCode(models.Model):
    """
    A web service that will allow user to create there price rule based on conditions
    """
    name = models.CharField(max_length=255)
    code = models.CharField(max_length=255)

    def __unicode__(self):
        return self.name

in admin.py you need to add code

from django.contrib import admin
from dx_man.models import LocationCode 
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

class LocationAdmin(admin.ModelAdmin):
    list_display=[]
    for x in LocationCode._meta.get_all_field_names():
        list_display.append(str(x))

admin.site.register(LocationCode, LocationAdmin)

in url.py add these line

from django.contrib import admin
admin.autodiscover()
like image 188
Atul Jain Avatar answered Nov 11 '22 21:11

Atul Jain


You need to ensure the registration code has been run or the site will not contain the (model, modeladmin) in the _registry.

code.py

from django.contrib.admin.sites import site

# run admin registration code before we get here
for model, model_admin in site._registry.items():
    if model == whatevermodel: 
        print(model_admin.search_fields)
like image 24
Victor 'Chris' Cabral Avatar answered Nov 11 '22 19:11

Victor 'Chris' Cabral