[Django]-Django model "doesn't declare an explicit app_label"

165πŸ‘

βœ…

Are you missing putting in your application name into the settings file?
The myAppNameConfig is the default class generated at apps.py by the .manage.py createapp myAppName command. Where myAppName is the name of your app.

settings.py

INSTALLED_APPS = [
'myAppName.apps.myAppNameConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

This way, the settings file finds out what you want to call your application. You can change how it looks later in the apps.py file by adding the following code in

myAppName/apps.py

class myAppNameConfig(AppConfig):
    name = 'myAppName'
    verbose_name = 'A Much Better Name'
πŸ‘€Xeberdee

93πŸ‘

I get the same error and I don’t know how to figure out this problem. It took me many hours to notice that I have an __init__.py at the same directory as the manage.py from Django.

Before:

|-- myproject
  |-- __init__.py  <---
  |-- manage.py
  |-- myproject
    |-- ...
  |-- app1
    |-- models.py
  |-- app2
    |-- models.py

After:

|-- myproject
  |-- manage.py
  |-- myproject
    |-- ...
  |-- app1
    |-- models.py
  |-- app2
    |-- models.py

It is quite confused that you get this doesn’t declare an explicit app_label error. But deleting this __init__.py file solved my problem.

πŸ‘€Samuel Knoch

54πŸ‘

I had exactly the same error when running tests with PyCharm. I’ve fixed it by explicitly setting DJANGO_SETTINGS_MODULE environment variable. If you’re using PyCharm, just hit Edit Configurations button and choose Environment Variables.

Set the variable to your_project_name.settings and that should fix the thing.

It seems like this error occurs, because PyCharm runs tests with its own manage.py.

πŸ‘€stasdeep

39πŸ‘

I got this one when I used ./manage.py shell
then I accidentally imported from the root project level directory

# don't do this
from project.someapp.someModule import something_using_a_model
# do this
from someapp.someModule import something_using_a_model

something_using_a_model()
πŸ‘€lukeaus

27πŸ‘

as a noob using Python3 ,I find it might be an import error instead of a Django error

wrong:

from someModule import someClass

right:

from .someModule import someClass

this happens a few days ago but I really can’t reproduce it…I think only people new to Django may encounter this.here’s what I remember:

try to register a model in admin.py:

from django.contrib import admin
from user import User
admin.site.register(User)

try to run server, error looks like this

some lines...
File "/path/to/admin.py" ,line 6
tell you there is an import error
some lines...
Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label

change user to .user ,problem solved

πŸ‘€rpstw

22πŸ‘

I had the same problem just now. I’ve fixed mine by adding a namespace on the app name. Hope someone find this helpful.

apps.py

from django.apps import AppConfig    

class SalesClientConfig(AppConfig):
        name = 'portal.sales_client'
        verbose_name = 'Sales Client'
πŸ‘€Wreeecks

21πŸ‘

I had a similar issue, but I was able to solve mine by specifying explicitly the app_label using Meta class in my models class

class Meta:
    app_label  = 'name_of_my_app'

15πŸ‘

I got this error on importing models in tests, i.e. given this Django project structure:

|-- myproject
    |-- manage.py
    |-- myproject
    |-- myapp
        |-- models.py  # defines model: MyModel
        |-- tests
            |-- test_models.py

in file test_models.py I imported MyModel in this way:

from models import MyModel

The problem was fixed if it is imported in this way:

from myapp.models import MyModel

Hope this helps!

PS: Maybe this is a bit late, but I not found in others answers how to solve this problem in my code and I want to share my solution.

πŸ‘€juliocesar

11πŸ‘

After keep on running into this issue and keep on coming back to this question I thought I’d share what my problem was.

Everything that @Xeberdee is correct so follow that and see if that solves the issue, if not this was my issue:

In my apps.py this is what I had:

class AlgoExplainedConfig(AppConfig):
    name = 'algo_explained'
    verbose_name = "Explain_Algo"
    ....

And all I did was I added the project name in front of my app name like this:

class AlgoExplainedConfig(AppConfig):
name = '**algorithms_explained**.algo_explained'
verbose_name = "Explain_Algo"

and that solved my problem and I was able to run the makemigrations and migrate command after that! good luck

πŸ‘€ZaMy

8πŸ‘

I had this error today trying to run Django tests because I was using the shorthand from .models import * syntax in one of my files. The issue was that I had a file structure like so:

    apps/
      myapp/
        models/
          __init__.py
          foo.py
          bar.py

and in models/__init__.py I was importing my models using the shorthand syntax:

    from .foo import *
    from .bar import *

In my application I was importing models like so:

    from myapp.models import Foo, Bar

This caused the Django model doesn't declare an explicit app_label when running ./manage.py test.

To fix the problem, I had to explicitly import from the full path in models/__init__.py:

    from myapp.models.foo import *
    from myapp.models.bar import *

That took care of the error.

H/t https://medium.com/@michal.bock/fix-weird-exceptions-when-running-django-tests-f58def71b59a

πŸ‘€inostia

6πŸ‘

In my case, this was happening because I used a relative module path in project-level urls.py, INSTALLED_APPS and apps.py instead of being rooted in the project root. i.e. absolute module paths throughout, rather than relative modules paths + hacks.

No matter how much I messed with the paths in INSTALLED_APPS and apps.py in my app, I couldn’t get both runserver and pytest to work til all three of those were rooted in the project root.

Folder structure:

|-- manage.py
|-- config
    |-- settings.py
    |-- urls.py
|-- biz_portal
    |-- apps
        |-- portal
            |-- models.py
            |-- urls.py
            |-- views.py
            |-- apps.py

With the following, I could run manage.py runserver and gunicorn with wsgi and use portal app views without trouble, but pytest would error with ModuleNotFoundError: No module named 'apps' despite DJANGO_SETTINGS_MODULE being configured correctly.

config/settings.py:

INSTALLED_APPS = [
    ...
    "apps.portal.apps.PortalConfig",
]

biz_portal/apps/portal/apps.py:

class PortalConfig(AppConfig):
    name = 'apps.portal'

config/urls.py:

urlpatterns = [
    path('', include('apps.portal.urls')),
    ...
]

Changing the app reference in config/settings.py to biz_portal.apps.portal.apps.PortalConfig and PortalConfig.name to biz_portal.apps.portal allowed pytest to run (I don’t have tests for portal views yet) but runserver would error with

RuntimeError: Model class apps.portal.models.Business doesn’t declare an explicit app_label and isn’t in an application in INSTALLED_APPS

Finally I grepped for apps.portal to see what’s still using a relative path, and found that config/urls.py should also use biz_portal.apps.portal.urls.

πŸ‘€jbothma

5πŸ‘

None of the answers here addressed my issue and the error message that brought us all here turned out to be a red herring for me – but I did find a solution.

For me, the true cause of the issue is:

  • Django tries to register apps
  • Some exception occurs during app registration (root cause)
  • Something in exception handling tooling pulls in a model somewhere
  • That model lives in an app that hasn’t been registered (because, remember, app registration was broken by the root cause exception above)
  • Finally, as its last act before dying Django spits out the (red herring) complaint that brought us all here – i.e. SomeModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

Instead of caring about this error (i.e. the error that brought us all here) I needed to scroll up and read the first error message.

This might look like something else for you, it can be ANYTHING that breaks app registration. For me, the root cause issue was:

Traceback (most recent call last):
[...SNIP...]                                                                                                                                                                                      
  File "/Users/user/.pyenv/versions/appName_py3/lib/python3.7/site-packages/django/__init__.py", line 24, in setup                   
    apps.populate(settings.INSTALLED_APPS)                                                                                         
  File "/Users/user/.pyenv/versions/appName_py3/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate 
    app_config.import_models()                                                                                                       
[... SNIP ...]                                                                                                    
  File "/Users/user/app_name/api/models/models.py", line 1122, in <module>              
    class SomeObject(models.Model):                                                                                     
  File "/Users/user/dev_alt/app_name/api/models/models.py", line 1134, in SomeObject
    some_property = models.ForeignKey(SomeOtherObject, null=True, blank=True)                         
TypeError: __init__() missing 1 required positional argument: 'on_delete'   

[...SNIP...]
During handling of the above exception, another exception occurred:

<RED HERRING STACK TRACE THAT BROUGHT US ALL HERE>

Again, the "root cause" issue may be different for you – but for me: I was upgrading a legacy Django application from 1.11.x to 3.2.x. Somewhere along the way Django made a backward-compatibility-breaking change requiring that all ForeignKey and OneToOne properties on models have an on_delete argument.

I added this argument for 200+ offending cases in the application and both my root cause issue and the doesn't declare an explicit app_label issue were resolved.

πŸ‘€Rob

3πŸ‘

Most probably you have dependent imports.

In my case I used a serializer class as a parameter in my model, and the serializer class was using this model:
serializer_class = AccountSerializer

from ..api.serializers import AccountSerializer

class Account(AbstractBaseUser):
    serializer_class = AccountSerializer
    ...

And in the β€œserializers” file:

from ..models import Account

class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = (
            'id', 'email', 'date_created', 'date_modified',
            'firstname', 'lastname', 'password', 'confirm_password')
    ...
πŸ‘€Dashko Leonid

3πŸ‘

I got this error today and ended up here after googling. None of the existing answers seem relevant to my situation. The only thing I needed to do was to import a model from my __init__.py file in the top level of an app. I had to move my imports into the functions using the model.

Django seems to have some weird code that can fail like this in so many different scenarios!

πŸ‘€boxed

3πŸ‘

O…M…G
I was getting this error too and I spent almost 2 days on it and now I finally managed to solve it. Honestly…the error had nothing to do with what the problem was.
In my case it was a simple matter of syntax. I was trying to run a python module standalone that used some django models in a django context, but the module itself wasn’t a django model. But I was declaring the class wrong

instead of having

class Scrapper:
    name = ""
    main_link= ""
    ...

I was doing

class Scrapper(Website):
    name = ""
    main_link= ""
    ...

which is obviously wrong. The message is so misleading that I couldn’t help myself but think it was some issue with configuration or just using django in a wrong way since I’m very new to it.

I’ll share this here for someone newbie as me going through the same silliness can hopefully solve their issue.

πŸ‘€Rafael Santos

2πŸ‘

I got this error while trying to upgrade my Django Rest Framework app to DRF 3.6.3 and Django 1.11.1.

For anyone else in this situation, I found my solution in a GitHub issue, which was to unset the UNAUTHENTICATED_USER setting in the DRF settings:

# webapp/settings.py
...
REST_FRAMEWORK = {
    ...
    'UNAUTHENTICATED_USER': None
    ...
}
πŸ‘€Robin Winslow

2πŸ‘

I received this error after I moved the SECRET_KEY to pull from an environment variable and forgot to set it when running the application. If you have something like this in your settings.py

SECRET_KEY = os.getenv('SECRET_KEY')

then make sure you are actually setting the environment variable.

πŸ‘€ameier38

2πŸ‘

I ran into this error when I tried generating migrations for a single app which had existing malformed migrations due to a git merge. e.g.

manage.py makemigrations myapp

When I deleted it’s migrations and then ran:

manage.py makemigrations

the error did not occur and the migrations generated successfully.

πŸ‘€Cerin

2πŸ‘

I just ran into this issue and figured out what was going wrong. Since no previous answer described the issue as it happened to me, I though I would post it for others:

  • the issue came from using python migrate.py startapp myApp from my project root folder, then move myApp to a child folder with mv myApp myFolderWithApps/.
  • I wrote myApp.models and ran python migrate.py makemigrations. All went well.
  • then I did the same with another app that was importing models from myApp. Kaboom! I ran into this error, while performing makemigrations. That was because I had to use myFolderWithApps.myApp to reference my app, but I had forgotten to update MyApp/apps.py. So I corrected myApp/apps.py, settings/INSTALLED_APPS and my import path in my second app.
  • but then the error kept happening: the reason was that I had migrations trying to import the models from myApp with the wrong path. I tried to correct the migration file, but I went at the point where it was easier to reset the DB and delete the migrations to start from scratch.

So to make a long story short:
– the issue was initially coming from the wrong app name in apps.py of myApp, in settings and in the import path of my second app.
– but it was not enough to correct the paths in these three places, as migrations had been created with imports referencing the wrong app name. Therefore, the same error kept happening while migrating (except this time from migrations).

So… check your migrations, and good luck!

πŸ‘€harrouet

2πŸ‘

I’ve got a similar error while building an API in Django rest_framework.

RuntimeError: Model class apps.core.models.University doesn’t declare an explicit > app_label and isn’t in an application in INSTALLED_APPS.

luke_aus’s answer helped me by correcting my urls.py

from

from project.apps.views import SurgeryView

to

from apps.views import SurgeryView

2πŸ‘

In my case I got this error when porting code from Django 1.11.11 to Django 2.2. I was defining a custom FileSystemStorage derived class. In Django 1.11.11 I was having the following line in models.py:

from django.core.files.storage import Storage, DefaultStorage

and later in the file I had the class definition:

class MyFileStorage(FileSystemStorage):

However, in Django 2.2 I need to explicitly reference FileSystemStorage class when importing:

from django.core.files.storage import Storage, DefaultStorage, FileSystemStorage

and voilΓ !, the error dissapears.

Note, that everyone is reporting the last part of the error message spitted by Django server. However, if you scroll up you will find the reason in the middle of that error mambo-jambo.

πŸ‘€user2641103

2πŸ‘

If you have got all the config right, it might just be an import mess. keep an eye on how you are importing the offending model.

The following won’t work from .models import Business. Use full import path instead: from myapp.models import Business

πŸ‘€evanxg852000

2πŸ‘

For PyCharm users: I had an error using not β€œclean” project structure.

Was:

project_root_directory
└── src
    β”œβ”€β”€ chat
    β”‚Β Β  β”œβ”€β”€ migrations
    β”‚Β Β  └── templates
    β”œβ”€β”€ django_channels
    └── templates

Now:

project_root_directory
β”œβ”€β”€ chat
β”‚   β”œβ”€β”€ migrations
β”‚   └── templates
β”‚       └── chat
β”œβ”€β”€ django_channels
└── templates

Here is a lot of good solutions, but I think, first of all, you should clean your project structure or tune PyCharm Django settings before setting DJANGO_SETTINGS_MODULE variables and so on.

Hope it’ll help someone. Cheers.

πŸ‘€paveldroo

2πŸ‘

In my case I was getting this error when trying to run python manage.py runserver when not connected to my project’s virtual environment.

πŸ‘€Ghar

2πŸ‘

In my case, I was trying the same import in manage.py shell. The shell was messed up with the updated db. I mean, I forgot to restart my shell after updating the DB.

To resolve the issue, I had to stop the shell by the following command:

>>> exit()

then restart the shell by the following command:

$ python3 manage.py shell

Hope this will help somebody like me.

1πŸ‘

TL;DR: Adding a blank __init__.py fixed the issue for me.

I got this error in PyCharm and realised that my settings file was not being imported at all. There was no obvious error telling me this, but when I put some nonsense code into the settings.py, it didn’t cause an error.

I had settings.py inside a local_settings folder. However, I’d fogotten to include a __init__.py in the same folder to allow it to be imported. Once I’d added this, the error went away.

1πŸ‘

in my case I was able to find a fix and by looking at the everyone else’s code it may be the same issue.. I simply just had to add β€˜django.contrib.sites’ to the list of installed apps in the settings.py file.

hope this helps someone. this is my first contribution to the coding community

1πŸ‘

If all else fails, and if you are seeing this error while trying to import in a PyCharm β€œPython console” (or β€œDjango console”):

Try restarting the console.

This is pretty embarassing, but it took me a while before I realized I had forgotten to do that.

Here’s what happened:

Added a fresh app, then added a minimal model, then tried to import the model in the Python/Django console (PyCharm pro 2019.2). This raised the doesn't declare an explicit app_label error, because I had not added the new app to INSTALLED_APPS.
So, I added the app to INSTALLED_APPS, tried the import again, but still got the same error.

Came here, read all the other answers, but nothing seemed to fit.

Finally it hit me that I had not yet restarted the Python console after adding the new app to INSTALLED_APPS.

Note: failing to restart the PyCharm Python console, after adding a new object to a module, is also a great way to get a very confusing ImportError: Cannot import name ...

πŸ‘€djvg

1πŸ‘

I’m adding this in case anyone had the same problem after using Django Cookiecutter.

In the app apps.py file where the name of the app is mentioned, be sure to include the name of the project in dot notation form.

eg
if the app is called students, change this to project_name.students

class StudentsConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'project_name.students'

Then in the settings.py file (which would be base.py in cookiecutter)

LOCAL_APPS = [
    ...
    "project_name.students",
]

PS just for reference, LOCAL_APPS would be INSTALLED_APPS in a standard Django project.

πŸ‘€bitFez

0πŸ‘

I got this error also today.
The Message referenced to some specific app of my apps in INSTALLED_APPS. But in fact it had nothing to do with this specific App. I used a new virtual Environment and forgot to install some Libraries, that i used in this project. After i installed the additional Libraries, it worked.

0πŸ‘

Check also that your migrations are working correctly

Python3 manage.py makemigrations
Python3 manage.py migrate
πŸ‘€user14241101

0πŸ‘

In my case, there was an issue with BASE_DIR in settings.py This is the structure of the packages:

project_root_directory
└── service_package
    └── db_package
        β”œβ”€β”€ my_django_package
        β”‚       └── my_django_package
        β”‚       Β Β  β”œβ”€β”€ settings.py
        β”‚       Β Β  └── ...
        └── my_django_app
               β”œβ”€β”€ migrations
               β”œβ”€β”€ models.py
               └── ...

It worked when updated the settings.py with:

INSTALLED_APPS = [
    'some_django_stuff_here...',
    'some_django_stuff_here....',
    ...
    'service_package.db_package.my_django_app'
]

And BASE_DIR pointing to the project root

BASE_DIR = Path(__file__).resolve().parent.parent.parent.parent.parent

Came to this after running django in debug, with breakpoint in registry.py -> def get_containing_app_config(self, object_name)

πŸ‘€Inna Leibman

0πŸ‘

After Reading the other answer. I could understand that. Different approaches are used based on the situation.
Here I explain. How I solved my case. This will help others also

enter image description here

test_model.py
no error or warning is shown in the pycharm and pycharm map to the model class

enter image description here

Error showing like this while test run

python manage.py test cheese

enter image description here

Solution

enter image description here

from everych.cheese.models import Dodavatel

The output without any error:

enter image description here

Conclusion: Most of the answers suggesting import apps model class in test class is the problem . so check the importing correct

πŸ‘€lava

0πŸ‘

For Django 4 this solution helped me:

auth.py

from django.utils.deprecation import MiddlewareMixin


class User:
    is_superuser = True
    is_active = True
    is_staff = True
    id = 1
    pk = 1


User.has_module_perms = lambda *args, **kwargs: True
User.has_perm = lambda *args, **kwargs: True


class AutoAuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        request.user = User()

settings.py\

MIDDLEWARE = [
    ...
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "path.to.auth.AutoAuthMiddleware",
    ...
]
πŸ‘€Gipss

-1πŸ‘

I solve this problem when i installed requirements.txt !!!

-2πŸ‘

The issue is that:

  1. You have made modifications to your models file, but not addedd them yet to the DB, but you are trying to run Python manage.py runserver.

  2. Run Python manage.py makemigrations

  3. Python manage.py migrate

  4. Now Python manage.py runserver and all should be fine.

πŸ‘€Ken Edem

Leave a comment