1

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)
2
  • Your question is unclear. Your init function is just wrong; as the error says, you need to use the correct type - FooAdmin, not Foo. I'm not sure of the relevance of the bit about removing the register; without that, the class is never instantiated. Commented Nov 6, 2019 at 22:08
  • Thanks. That was it. I was sure other examples were using the model. I might be stupid. Commented Nov 6, 2019 at 22:11

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.