Alexander Kleinhans
Alexander Kleinhans

Reputation: 6258

Django using __init__ method in classes extending (admin.ModelAdmin)

I am fairly new to Django.

I have an admin.Models extended class that's pretty typical (has list_display, search_fields, etc).

It looks something like this:

class FooAdmin(admin.ModelAdmin):
    list_display = (
        'all',
        'my',
        'things',
    )
    ...
admin.site.register(Foo, FooAdmin)

My problem is that this ModelAdmin loads somethings from a model with something like foo_list = Foo.objects.filter(group__name='something').

Because this is a heavy task, I'd like to do it once on initialization, and then use the same thing over and over again when specifying custom "_field" functions.

My thoughts are to do this in the __init__ method of this class, but when implement my own constructor, it doesn't register with Django as a url; i.e.

class FooAdmin(admin.ModelAdmin):
    def __init__(self, *args, **kwargs):
        super(Foo, self).__init__(*args, **kwargs)
    list_display = (
        'all',
        'my',
        'things',
    )
    ...
# This register portion removed.
# admin.site.register(Foo, FooAdmin)

The above will "build" correctly and run, but attempting to visit the site says the URL is not found (not surprising since I removed the register part).

However, when I add the register portion back in, I get a message about a misuse of my constructor, i.e adding back the admin.site.register and running python manage.py runserver ... results in something like:

TypeError: super(type, obj): obj must be an instance or subtype of type

I've taken this constructor from multiple examples to no avail, so I'm not sure if this is a Django versioning thing or not.

My questions are:

  1. How can I use an initialization method or some kind of "lifecycle-hook" in an admin.ModelAdmin extended class?
  2. Why does implemented my constructor break the constructors interface when registering the URL?

This is my environment:

$ python
Python 3.7.4 (default, Sep  7 2019, 18:29:04)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.VERSION
(2, 2, 5, 'final', 0)

Upvotes: 1

Views: 569

Answers (0)

Related Questions