RuntimeError: Model class doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS for Django OAuth Toolkit

Viewed 4462

I want to access the models that are used by Django OAUTH Toolkit so I can periodically delete old tokens from the database. I thought I'd just import them:

from oauth2_provider.management.commands.cleartokens import Command
from oauth2_provider.models import AccessToken
Command.handle()

However when I try to run this file in the command line I receive the following error:

Traceback (most recent call last):
  File ".\db_cleanup.py", line 5, in <module>
    from oauth2_provider.models import AccessToken
  File "C:\Users\User\.virtualenvs\gsm-django\lib\site-packages\oauth2_provider\models.py", line 178, in <module>
    class Application(AbstractApplication):
  File "C:\Users\User\.virtualenvs\gsm-django\lib\site-packages\django\db\models\base.py", line 95, in __new__
    "INSTALLED_APPS." % (module, name)
RuntimeError: Model class oauth2_provider.models.Application doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

I tried adding oauth2_provider.models.Application to my installed apps in my settings file as well but to no avail:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'api',
    'oauth2_provider',
    'oauth2_provider.models.Application',
    'rest_framework',
    'rest_framework.authtoken',
    'graphene_django',
    'corsheaders',
]

I added app_label to the Application class it mentions as well, but that does not work either.

1 Answers

If you look at the django-oauth2-provider docs (I assume this is the correct library; I had to guess since I did not find a link in your question), it says there:

Add OAuth2 Provider to INSTALLED_APPS

INSTALLED_APPS = (
    # ...
    'provider',
    'provider.oauth2',
)

But I noticed that your code in the question has something else:

'oauth2_provider',
'oauth2_provider.models.Application',

Have you tried what the docs suggest? Does that work for you?

Related