For anyone still facing this error raise NotRegistered('The model %s is not registered' % model.__name__), even after doing either
admin.site.unregister(TokenProxy) or admin.site.unregister(Token)
This can happen due to the order in which Django initializes applications and their components. When your admin.py is processed, it might be that TokenProxy or Token hasn't been registered yet with the admin site, leading to the NotRegistered error.
A solution to this issue involves ensuring your unregister call occurs after all apps, including the rest_framework.authtoken, have been fully initialized. One way to achieve this is by using Django's AppConfig.ready method, which allows you to execute code once Django is ready and all models are loaded.
Here's how you can do it:
Step 1: Create or Modify an AppConfig for Your Application
If your application doesn't already have a custom AppConfig, create one. This involves creating a subclass of django.apps.AppConfig in your application's apps.py file. If apps.py doesn't exist, create it inside your application directory. Here's an example:
from django.apps import AppConfig
class MyAppConfig(AppConfig):
name = 'your_app_name' # Replace 'your_app_name' with the name of your app
verbose_name = "My Application"
def ready(self):
# This method will be executed once Django is fully initialized
from django.contrib import admin
from rest_framework.authtoken.models import TokenProxy #or Token based on your Django version
try:
admin.site.unregister(TokenProxy)
except admin.sites.NotRegistered:
pass
Step 2: Update Your Application's Configuration in settings.py
In your settings.py, update the INSTALLED_APPS entry for your application to use the new AppConfig. This involves using the full path to your AppConfig class:
INSTALLED_APPS = [
# other apps
'your_app_name.apps.MyAppConfig', # Replace with your AppConfig path
# other apps
]