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'
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.
- [Django]-How to convert JSON data into a Python object?
- [Django]-How do you use the django-filter package with a list of parameters?
- [Django]-Redirect to Next after login in Django
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
.
- [Django]-Http POST drops port in URL
- [Django]-What is pip install -q -e . for in this Travis-CI build tutorial?
- [Django]-Django-Forms with json fields
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()
- [Django]-What does on_delete do on Django models?
- [Django]-Is it bad to have my virtualenv directory inside my git repository?
- [Django]-How to change User representation in Django Admin when used as Foreign Key?
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
- [Django]-Table thumbnail_kvstore doesn't exist
- [Django]-Pagination in Django-Rest-Framework using API-View
- [Django]-Check if celery beat is up and running
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'
- [Django]-Can't compare naive and aware datetime.now() <= challenge.datetime_end
- [Django]-Where does pip install its packages?
- [Django]-Django admin file upload with current model id
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'
- [Django]-Django index page best/most common practice
- [Django]-How do I get the object if it exists, or None if it does not exist in Django?
- [Django]-Django-allauth social account connect to existing account on login
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.
- [Django]-Django middleware difference between process_request and process_view
- [Django]-Substring in a django template?
- [Django]-Proper way to handle multiple forms on one page in Django
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
- [Django]-Equivalent of PHP "echo something; exit();" with Python/Django?
- [Django]-Nginx doesn't serve static
- [Django]-Django-way for building a "News Feed" / "Status update" / "Activity Stream"
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
- [Django]-How to get username from Django Rest Framework JWT token
- [Django]-Django limit_choices_to for multiple fields with "or" condition
- [Django]-Suddenly when running tests I get "TypeError: 'NoneType' object is not iterable
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
.
- [Django]-Malformed Packet: Django admin nested form can't submit, connection was reset
- [Django]-Django datefield filter by weekday/weekend
- [Django]-Does django with mongodb make migrations a thing of the past?
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.
- [Django]-Django TextField and CharField is stripping spaces and blank lines
- [Django]-How to format time in django-rest-framework's serializer?
- [Django]-How to use Django ImageField, and why use it at all?
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')
...
- [Django]-Are Django SECRET_KEY's per instance or per app?
- [Django]-How do I run tests against a Django data migration?
- [Django]-How do I reuse HTML snippets in a django view
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!
- [Django]-Timestamp fields in django
- [Django]-Django multiple template inheritance β is this the right style?
- [Django]-Switching to PostgreSQL fails loading datadump
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.
- [Django]-Execute code when Django starts ONCE only?
- [Django]-Django rest framework, use different serializers in the same ModelViewSet
- [Django]-Django β SQL bulk get_or_create possible?
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
...
}
- [Django]-FileUploadParser doesn't get the file name
- [Django]-How to get username from Django Rest Framework JWT token
- [Django]-Django Rest JWT login using username or email?
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.
- [Django]-How to revert the last migration?
- [Django]-How to test auto_now_add in django
- [Django]-Django custom management commands: AttributeError: 'module' object has no attribute 'Command'
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.
- [Django]-Negating a boolean in Django template
- [Django]-Django can' t load Module 'debug_toolbar': No module named 'debug_toolbar'
- [Django]-Detect mobile, tablet or Desktop on Django
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 withmv 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!
- [Django]-Suddenly when running tests I get "TypeError: 'NoneType' object is not iterable
- [Django]-Django model CharField: max_length does not work?
- [Django]-How to get superuser details in Django?
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
- [Django]-"<Message: title>" needs to have a value for field "id" before this many-to-many relationship can be used.
- [Django]-How do you Serialize the User model in Django Rest Framework
- [Django]-How to query as GROUP BY in Django?
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.
- [Django]-How do I create a slug in Django?
- [Django]-How to access Enum types in Django templates
- [Django]-Is there a way to filter a queryset in the django admin?
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
- [Django]-Where can I find the error logs of nginx, using FastCGI and Django?
- [Django]-ValueError: The field admin.LogEntry.user was declared with a lazy reference
- [Django]-Django model constraint for related objects
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.
- [Django]-What's the best way to extend the User model in Django?
- [Django]-How does Django's nested Meta class work?
- [Django]-Why is logged_out.html not overriding in django registration?
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.
- [Django]-Django development server reload takes too long
- [Django]-How to change site title, site header and index title in Django Admin?
- [Django]-How to reset Django admin password?
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.
- [Django]-IOS app with Django
- [Django]-Access web server on VirtualBox/Vagrant machine from host browser?
- [Django]-Difference between User.objects.create_user() vs User.objects.create() vs User().save() in django
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.
- [Django]-Specifying limit and offset in Django QuerySet wont work
- [Django]-Django β what is the difference between render(), render_to_response() and direct_to_template()?
- [Django]-How to change User representation in Django Admin when used as Foreign Key?
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
- [Django]-ModuleNotFoundError: No module named 'grp' on windows
- [Django]-What is related_name used for?
- [Django]-UUID as default value in Django model
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 ...
- [Django]-Default filter in Django model
- [Django]-Django render_to_string missing information
- [Django]-Django TemplateDoesNotExist?
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.
- [Django]-Remove pk field from django serialized objects
- [Django]-Django. A good tutorial for Class Based Views
- [Django]-Multiple annotate Sum terms yields inflated answer
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.
- [Django]-Numeric for loop in Django templates
- [Django]-Adding to the "constructor" of a django model
- [Django]-Celery : Execute task after a specific time gap
0π
Check also that your migrations are working correctly
Python3 manage.py makemigrations
Python3 manage.py migrate
- [Django]-How to implement followers/following in Django
- [Django]-Is it bad to have my virtualenv directory inside my git repository?
- [Django]-Default filter in Django model
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)
- [Django]-Django: Get list of model fields?
- [Django]-How do I filter ForeignKey choices in a Django ModelForm?
- [Django]-Python 3 list(dictionary.keys()) raises error. What am I doing wrong?
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
test_model.py
no error or warning is shown in the pycharm and pycharm map to the model class
Error showing like this while test run
python manage.py test cheese
Solution
from everych.cheese.models import Dodavatel
The output without any error:
Conclusion: Most of the answers suggesting import apps model class in test class is the problem . so check the importing correct
- [Django]-How to debug in Django, the good way?
- [Django]-NumPy array is not JSON serializable
- [Django]-Complete django DB reset
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",
...
]
- [Django]-How do I integrate Ajax with Django applications?
- [Django]-Django Cache cache.set Not storing data
- [Django]-Does django with mongodb make migrations a thing of the past?
- [Django]-What does 'many = True' do in Django Rest FrameWork?
- [Django]-How to upload a file in Django?
- [Django]-How can I get the full/absolute URL (with domain) in Django?
-2π
The issue is that:
-
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.
-
Run Python manage.py makemigrations
-
Python manage.py migrate
-
Now Python manage.py runserver and all should be fine.
- [Django]-Warning: Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'
- [Django]-How to check if a user is logged in (how to properly use user.is_authenticated)?
- [Django]-Django composite unique on multiple model fields