Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django admin – admin inheritance

When registering django admin, I inherited another admin, but I don’t know why the model of list_display is changed.

Let me explain the situation in detail with code.

@admin.register(User) 
class UserAdmin(models.Model):
    list_display = [a.name for a in User._meta.concrete_fields]


@admin.register(Sales)
class SalesAdmin(UserAdmin):
    pass

According to the code above, SalesAdmin Admin appears to inherit from UserAdmin.
In this case, shouldn’t list_display of User model appear in list_display?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I don’t understand why the list_display of Sales Model comes out.
If I want to display the list_display of the Sales model while inheriting UserAdmin, shouldn’t I have to redeclare the list_display as shown below?

@admin.register(User) 
class UserAdmin(models.Model):
    list_display = [a.name for a in User._meta.concrete_fields]


@admin.register(Sales)
class SalesAdmin(UserAdmin):
    list_display = [a.name for a in Sales._meta.concrete_fields]

I did not redeclare list_display, but I do not understand whether it is automatically output as the list_display of the changed model. If anyone knows, please explain.

>Solution :

Override the get_list_display method to return a list_display that is dynamic based on the current model.

FYI, your admin classes should inherit from admin.ModelAdmin not models.Model

@admin.register(User) 
class UserAdmin(admin.ModelAdmin):
    def get_list_display(self, request):
        return [a.name for a in self.model._meta.concrete_fields]


@admin.register(Sales)
class SalesAdmin(UserAdmin):
    pass
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading