Search code examples
pythondjangodjango-modelsdjango-admin

Custimizing Django Admin (multiple registraion to a model)


I have a Django app with a master model that has a lot on detailed models. the detaled models are related to the master with foreign keys in each. I registered my master model in django admin and included all my detail models as "TabularInline" layout.

My models.py looks like:

# models.py file #
class MasterModel(models.Model):
    # master model fields ...

class DetailModel_01(models.Model):
    # detail model fields

class DetailModel_02(models.Model):
    # detail model fields

class DetailModel_03(models.Model):
    # detail model fields

class DetailModel_04(models.Model):
    # detail model fields

My admin.py looks like:

class Detail_01_Inline(admin.TabularInline):
    model = Detail_01
class Detail_02_Inline(admin.TabularInline):
    model = Detail_02
class Detail_03_Inline(admin.TabularInline):
    model = Detail_03
class Detail_04_Inline(admin.TabularInline):
    model = Detail_04

@admin.register(MasterModel)
class MasterModelAdmin(admin.ModelAdmin):
    inlines = [
        Detail_01_Inline,
        Detail_02_Inline,
        Detail_03_Inline,
        Detail_04_Inline,
    ]

The master model has too many fields, and too many inlines. therefore, not convienient to the users. I need to splet the inlines.

can i register the master model more than one time in Django admin, and include part of the inlines each time ??

I tried this:

class MasterModelAdmin(admin.ModelAdmin):
    model = MasterModel

class MasterModelAdmin2(admin.ModelAdmin):
    model = MasterModel

admin.site.register(MasterModel, MasterModelAdmin)
admin.site.register(MasterModel, MasterModelAdmin2)

but.. it doesn't work.

your ideas are so appreciated.

Suhail


Solution

  • You can create a proxy for the master model. Proxy models are declared like normal models. You tell Django that it’s a proxy model by setting the proxy attribute of the Meta class to True.

    models.py

    class MasterModelProxy(MasterModel):
    
        class Meta:
            proxy = True
    

    admin.py

    @admin.register(MasterModelProxy)
    class MasterModelProxyAdmin(admin.ModelAdmin):
        ...