HIT_girl
HIT_girl

Reputation: 875

Django - generic ModelAdmin definition

This is a newbie question.

I have multiple models that I would like to show in admin view. I would like to show all model's fields when viewing a list of records for a model. I'd like to define a generic ModelAdmin subclass which will be able to list out all fields for a model. But not sure how to pass the class objects to it. admin.py looks like this

class ModelFieldsAdmin(admin.ModelAdmin):

    def __init__(self, classObj):
        self.classObj = classObj
        self.list_display = [field.name for field in classObj._meta.get_fields()]


admin.site.register(Candy, ModelFieldsAdmin)
admin.site.register(Bagel, ModelFieldsAdmin)

How can I pass the classObj (which would be one of the models Candy or Bagel) , and also ensure that the get_list_display() picks up the value from self.list_display ?

Upvotes: 0

Views: 186

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599796

This isn't the right approach. You shouldn't override __init__ for an admin class.

Rather, define get_list_display and access self.model:

def get_list_display(request):
    return [field.name for field in self.model._meta.get_fields()]

Upvotes: 1

Related Questions