233

After a dozen hours of troubleshooting, I thought I was finally in business, but then I got:

Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label 

There is so little info on this on the web, and no solution out there has resolved my issue.

I'm using Python 3.4 and Django 1.10.

From my settings.py:

INSTALLED_APPS = [
    'DeleteNote.apps.DeletenoteConfig',
    'LibrarySync.apps.LibrarysyncConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

And my apps.py files look like this:

from django.apps import AppConfig


class DeletenoteConfig(AppConfig):
    name = 'DeleteNote'

and

from django.apps import AppConfig


class LibrarysyncConfig(AppConfig):
    name = 'LibrarySync'
halfer
  • 19,824
  • 17
  • 99
  • 186
Slbox
  • 10,957
  • 15
  • 54
  • 106
  • 3
    You don't have django.contrib.contenttypes in INSTALLED_APPS. – RemcoGerlich Oct 23 '16 at 18:45
  • Thank you, but unfortunately I do. I've updated my post to reflect that. – Slbox Oct 23 '16 at 18:47
  • 3
    Then the other likely thing is that you imported it before its models were loaded, is some app that is listed before contenttypes in INSTALLED_APPS using it? – RemcoGerlich Oct 23 '16 at 18:48
  • Unfortunately it's the default order of apps, and only the default apps. I works fine on another environment I have. I have not run 'migrate' or 'makemigration' on this installation, if that matters, because doing so produces the exact same error. – Slbox Oct 23 '16 at 18:49
  • 1
    That's unusual, you have no project or app of your own at all? – RemcoGerlich Oct 23 '16 at 18:50
  • I have two (I think?) that are part of my project, but I didn't need to add it to that list in my previous environment. I'm a bit of a noob, if that wasn't obvious by now. Under my project root I have 2 apps, if I'm using the term app correctly. How would I go about adding those, if that is what I need to do? Thanks a lot for your time and your help. – Slbox Oct 23 '16 at 18:56
  • 3
    Everything that has a models.py should be in INSTALLED_APPS; and if one of them uses contenttype (because of a generic foreign key, say) then it needs to be under contenttypes in the list. – RemcoGerlich Oct 23 '16 at 18:59
  • Thanks, that's an easy way to tell what needs to be there. Unfortunately though, whether I put my apps at the top or the bottom of the list, I get an identical error. – Slbox Oct 23 '16 at 19:11
  • 1
    Frustrating, it's likely to be something very small but hard to tell from here where. Do you import any of your stuff in settings.py or so? – RemcoGerlich Oct 23 '16 at 19:13
  • Haha thank you! Previously I was running into some sort of AppRegistry problem and added an `import django django.setup()` That fixed it, but gave me this new problem. The changes you advised, plus moving that down below the INSTALLED_APPS entry seems to have my in business. I really appreciate it. My "dozen hours" spent troubleshooting was honestly probably closer to two dozen, and I think that this is the final piece to the puzzle. Thanks so much. – Slbox Oct 23 '16 at 19:19
  • 1
    You're welcome, have fun :) – RemcoGerlich Oct 23 '16 at 19:29
  • @Slbox, can you share how did you solve it. I'm facing the same error while upgrading from 1.8 to 1.11 – Ankush Dec 07 '17 at 11:38
  • Have you restarted IPython? My changes took effect after i did this – Preston Jun 03 '18 at 21:18
  • So was there a resolution to this? There are no accepted answers and every answer suggests something different. I'm not even using models and I get this – dudemonkey Aug 07 '19 at 10:20
  • The top answer is accepted. – Slbox Aug 09 '19 at 16:59
  • @Slbox how did u solve this i tried all possibilities except `import django django.setup()` what it is & where should i implement it. – Rahul Verma Jul 03 '20 at 23:37
  • Good question. Python module gotchas. – user2290820 Jul 08 '20 at 20:51
  • Oh thank you so much @RemcoGerlich. I can't think that much at 11:34, so thank you again. I was declaring my django apps before the `django.contrib.contenttypes',`. – theProCoder Jul 13 '21 at 13:36
  • check you have a `__init__.py` file in your apps directories, `DeleteNote` and `LibrarySync` – Euribates Mar 28 '22 at 15:04

35 Answers35

159

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'
ggorlen
  • 44,755
  • 7
  • 76
  • 106
Xeberdee
  • 1,887
  • 1
  • 14
  • 19
  • Okay so this makes a lot of sense to me with the example, and I've implemented the changes now based on my understanding of the syntax, but I'm still hitting 100% the exact same error. I've updated my post to elaborate. – Slbox Oct 23 '16 at 19:09
  • I also tried putting my apps below the django.contrib ones, same message. – Slbox Oct 23 '16 at 19:11
  • 5
    Thanks to @xeberdee and @RemcoGerlich for their help with this. In the end, my solution was to load my apps below the django.contrib apps, and to move my entry of `import django django.setup()` in my settings.py, to beneath the `INSTALLED_APPS` entry. – Slbox Oct 23 '16 at 19:20
  • 2
    Just out of curiosity - why import django django.setup() in the settings file? Also, your apps should load even if they are the first in the installed apps list. – Xeberdee Oct 25 '16 at 17:39
  • 2
    What's the difference between this and what he wrote in his question? – Matt Jul 04 '17 at 01:15
  • 1
    This solution doesn't make sense to me. An app config goes in an app. It's not an app unto itself. The error is complaining about ContentTypes not having an app_label or app config, not OP's custom app. – Cerin Oct 10 '17 at 16:23
  • 1
    The point was how the the app is discovered in settings INSTALLED_APPS thru the name field of the class in the config file. The post has been edited. – Xeberdee Oct 11 '17 at 11:20
  • What should I do in the case of 'ImportError: No module named myAppName.apps' ? – KasparTr Nov 15 '17 at 12:59
  • 2
    @Xeberdee I tried all these but still get the same error what is this `import django django.setup()` and where should i keep it. – Rahul Verma Jul 03 '20 at 23:33
92

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 file solved my problem.

letsintegreat
  • 3,328
  • 4
  • 18
  • 39
Samuel Knoch
  • 1,113
  • 8
  • 9
  • I'm trying to generate documentation using pydoc, and my app hidden without init.py – Serg Smyk May 21 '20 at 11:02
  • 4
    For me app ran file but unit tests failed. When running tests, with the `__init__.py` file it ran 101 tests, and the last one failed with an import error. After deleting the `__init__.py` file it ran 100 tests, all passing. – run_the_race Oct 27 '20 at 07:55
  • I thought this was the issue, but it wasn't. See next answer by @farid-chowdhury. I was using python's shell, not django's python shell. Needed to adjust a bunch of paths but now everything works and likely needs the __init__'s. – DonkeyKong Aug 18 '21 at 15:05
53

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
  • 2,758
  • 1
  • 16
  • 29
  • 3
    Had this problem running Pycharm Tests although running server through Pycharm did not require me to add settings. Manually adding DJANGO_SETTINGS_MODULE to configuration for test solved if for me. – PhoebeB Apr 21 '18 at 13:42
  • 2
    Also, when editing configurations, it's useful to edit the templates. – Yngve Høiseth Dec 19 '18 at 11:14
  • 3
    Settings -> Languages & Frameworks -> Django -> Adding a value under settings will automatically set `DJANGO_SETTINGS_MODULE` for each new Django and Django test run configuration. – Tobias Ernst Jun 13 '19 at 09:15
  • FYI, I did exactly as indicated by this solution and it didn't work the first time. Turns out, PyCharm didn't save the `DJANGO_SETTINGS_MODULE` the first time when I clicked `Apply` then `OK`. I did it a second time and now it works. Seems like a bit of PyCharm weirdness. – MikeyE Sep 12 '19 at 01:12
  • I had to make sure I declared imports correctly: from `. import ` - PyCharm auto import was missing ``. Once I corrected this (also checked dependent modules) then it worked ok. – Matthew Hegarty Jul 19 '20 at 12:46
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
  • 11,465
  • 7
  • 50
  • 60
26

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
  • 1,582
  • 14
  • 16
  • 15
    Welcome to stackoverflow! I feel compelled to mention that your answer is unrelated to the OP's question. As a noob, you should be careful proposing solutions without first verifying their correctness. But please keep coming back, and post concrete answers when you can—thanks! – evadeflow Jul 06 '17 at 14:14
  • 4
    I wish more comments on Stack were like yours Xeon Phil. Too often new users are chased off by rabid commenters unhappy that they are not Stack experts on day one. – Slbox Jul 09 '17 at 15:55
  • 1
    You are right, @evadeflow , my first answer looks really unrelated, I try to clarify the answer.Anyway,just hope the answer might be useful. – rpstw Jul 11 '17 at 10:08
  • It was a similar issue in my case. 'from ..core.models import CommonInfo' had to become 'from apps.core.models import CommonInfo' – user42488 Apr 25 '18 at 11:53
  • This was my issue, obscured because it was happening in 2 separate files. Dang you, nested imports! Dang you, my foolish rejection of 2to3's sensible changes! – 9999years Oct 19 '18 at 12:43
  • Your answer is what worked. In Django start project, pls don't remove __init__ next to manage if its present. This is complete related. – user2290820 Jul 08 '20 at 20:51
  • Maybe we are not noobs, dude. I got the same error due to wrong import as my project includes different parts. So absolute import resolved my problem. from core.models import AuthProviderModel - wrong from my_project_name.core.models import AuthProviderModel - right – Ivan Vinitskyi Jun 23 '23 at 14:08
21

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
  • 2,186
  • 1
  • 33
  • 53
  • 1
    plus maybe: `label = 'sales_client'` – mirek Feb 19 '21 at 16:02
  • Yes this solved my issue. I used django cookiecutter project and created a subapp because that was the level where my users app was. So the app was in ```project_dir.app.sub_app``` and my name was ```sub_app``` when it needed to be ```app.sub_app```. This was because to generate the app I used ```python ../manage.py startapp app```. – Moemars May 11 '22 at 03:42
  • Out of the hundreds of suggested fixes to the issue, this is the one that finally got me up and running. – lime Aug 30 '22 at 04:39
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'
Benjamin Andoh
  • 285
  • 2
  • 8
  • Thanks Benjamin! In my Django project, I am using Sphinx to generate documentation, and the ::autoclass directive was giving the "app_label" error until I added it to the Model's Meta class as you suggested. – Stefan Musarra Jul 09 '20 at 22:02
  • This helped me to add a custom app as a dependency of my app. It meant that the dependency didn't need to be written in 'installed_apps" in settings. Really helpful. https://docs.djangoproject.com/en/4.1/ref/models/options/#app-label – miller the gorilla Oct 16 '22 at 11:38
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
  • 5,706
  • 8
  • 44
  • 63
  • juliocesar you're a champ. Thanks. This was a ridiculous error. – Kirk Jul 27 '19 at 22:06
  • 4
    Took me longer than expected to find this. I was using a relative import in my test.py file. Got the error when using `from .models import MyModel`. Changing to `from myapp.models import MyModel` fixed the issue. – monkut May 01 '20 at 02:07
  • 1
    @monkut same here. I wonder why is this happening. I use custom apps folder by the way. "/apps" in the project root, added to the path. –  May 31 '20 at 21:52
  • I have to admin, i was thinking no way i did that, it was an auto import from IntelliJ. Thanks for the answer. – ekydfejj Dec 08 '20 at 02:23
10

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
  • 498
  • 5
  • 12
  • this is the solution that works for me, this issue arose after generating a bootstrap django project with django cookie cutter and I later added an app with the startapp management command. – Brian Obot May 12 '23 at 11:59
7

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
  • 7,777
  • 3
  • 30
  • 33
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
  • 93
  • 1
  • 7
4

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
  • 53
  • 6
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')
    ...
Doug Harris
  • 3,169
  • 5
  • 29
  • 31
Dashko Leonid
  • 111
  • 1
  • 2
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,895
  • 2
  • 24
  • 26
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
  • 293
  • 3
  • 18
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
  • 10,908
  • 8
  • 62
  • 91
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
  • 166
  • 3
  • 5
  • Tried running a single test via Pycharm and got hit by `django tests RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.`. Turns out this is because Pycharm uses it's own manage.py that doesn't know about my environment variables. – Lauri Elias Nov 19 '21 at 14:03
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
  • 60,957
  • 96
  • 316
  • 522
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
  • 179
  • 8
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
Mohammad
  • 21,175
  • 15
  • 55
  • 84
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
  • 704
  • 9
  • 25
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
  • 249
  • 3
  • 6
  • If you are importing a model from models.py which is not in the same directory or same as your views.py, then you specify the name of the app and then import that model. from NAME_OF_APP.models import modelname – Gajendra D Ambi Dec 23 '22 at 16:35
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
  • 828
  • 9
  • 14
  • Thanks for reminding me about setting up the integration! For reference, go into `Settings => Languages & Frameworks => Django` and set the `Settings:` property to be the name of the file (or directory/module). This is usually something like `myproj.settings` – Andrew Apr 25 '22 at 11:40
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
  • 625
  • 1
  • 7
  • 19
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.

Farid Chowdhury
  • 2,766
  • 1
  • 26
  • 21
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.

James Bradbury
  • 1,708
  • 1
  • 19
  • 31
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
  • 11,722
  • 5
  • 72
  • 103
  • Thanks for this answer, I forgot to source my `.env` file and I was doing my best to make things work with an obsolete configuration :/ – sodimel Dec 17 '19 at 14:09
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.

black_hole_sun
  • 908
  • 11
  • 41
0

Check also that your migrations are working correctly

Python3 manage.py makemigrations
Python3 manage.py migrate
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)

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
  • 6,020
  • 2
  • 31
  • 28
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
  • 13
  • 3
-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.

Dharman
  • 30,962
  • 25
  • 85
  • 135