Django setting - apps aren't loaded yet

628 Views Asked by At

I want to import an apps model in setting.py for PUSH_NOTIFICATIONS_SETTINGS in django-push-notifications. This is my code:

INSTALLED_APPS = (
    ....
    'my_app',
    'push_notifications'
    ....
)

from my_app.models import User

PUSH_NOTIFICATIONS_SETTINGS = {
    'GCM_API_KEY': 'xxxxx',
    'APNS_CERTIFICATE': 'xxxxx.pem',
    'USER_MODEL': User,  # i want to change the default from auth_user to my_app User
}

But it raise an error on this line:

from my_app.models import User

The error is:

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

How Can i load my_app model in setting.py?

2

There are 2 best solutions below

0
On

You cannot load models from inside your settings file like that - models can only be loaded once all apps are loaded (which can only happen after the settings have been loaded).

Looking at the code in django-push-notifications, you should be able to provide the model as a string with dotted path:

'USER_MODEL': 'my_app.User' 
0
On

You can't load User model in settings, but instead you can change it

PUSH_NOTIFICATIONS_SETTINGS = {
    'GCM_API_KEY': 'xxxxx',
    'APNS_CERTIFICATE': 'xxxxx.pem',
    'USER_MODEL': 'my_app.User',  
}

And use it later like:

from django.apps import apps
from django.conf import settings
User = apps.get_model(settings.PUSH_NOTIFICATIONS_SETTINGS['USER_MODEL'])

And you can do whatever you want with this User model