Search code examples
pythondjangodjango-modelsdjango-2.1

Django - Users inconsistently registered to Admin


This is the default User model, nothing custom, no modifications to Auth in any way. I am using Django 2.1.

Depot/Admin.py

import depot.models as models
from django.contrib import admin
from django.db.models.base import ModelBase
from django.contrib.auth.models import User

admin.site.site_header = "DSG IT Database"
for model_name in dir(models):
    model = getattr(models, model_name)
    if isinstance(model, ModelBase):
        if model in admin.site._registry: 
            admin.site.unregister(model)
        else:
            admin.site.register(model)

Stores/Admin.py

import stores.models as models
from django.contrib import admin
from django.db.models.base import ModelBase
from django.contrib.auth.models import User

admin.site.site_header = "DSG IT Database"
for model_name in dir(models):
    model = getattr(models, model_name)
    if isinstance(model, ModelBase):
        if model in admin.site._registry: 
            admin.site.unregister(model)
        else:
            admin.site.register(model)

I do understand these are sort of redundant, but that isn't the problem because this was an issue when this was a single application project as well.

enter image description here

What is happening is that Users is just completely missing from the admin site. I can register it again with admin.site.register(User), but then later down the road (seemingly randomly) I'll get an error that User is already registered. Then I unregister the model, and it'll work for a while then at some point Users will just disappear again and the only way to make it work again is by registering it again.

I can't find where I need to be to debug this. I'm assuming somewhere the model is being registered but only under certain conditions I'm unsure of. Has anyone had an issue similar to this?

Please feel free to ask me to include any information you feel will help diagnose!


Solution

  • If stores.models imports User it will be listed in dir(models) and since ModelBase is the Django metaclass for all Django models:

    isinstance(User, ModelBase)   # Is True
    

    So, the User model is not there because you are unregistering it.

    You could use:

    from django.apps import apps
    
    stores_app_config = apps.get_app_config('stores')
    
    for model in stores_app_config.get_models():
        # process models from stores app here.
    

    Proposed reading: Python metaclasses.