53๐
Iโd a custom function written on one of my models __init__.py
file. It was causing the error. When I moved this function from __init__.py
it worked.
177๐
Try to add this lines to the top of your settings file:
import django
django.setup()
And if this will not help you try to remove third-party applications from your installed apps list one-by-one.
- [Django]-Django-rest-framework returning 403 response on POST, PUT, DELETE despite AllowAny permissions
- [Django]-Django Installed Apps Location
- [Django]-Iterating over related objects in Django: loop over query set or use one-liner select_related (or prefetch_related)
52๐
My problem was that I tried to import a Django model before calling django.setup()
This worked for me:
import django
django.setup()
from myapp.models import MyModel
The above script is in the project root folder.
- [Django]-Django, creating a custom 500/404 error page
- [Django]-Django REST Framework: how to substitute null with empty string?
- [Django]-Django-Forms with json fields
18๐
In my case, the error occurred when I made python manage.py makemigrations
on Django 2.0.6
.
The solution was to run python manage.py runserver
and see the actual error (which was just a missing environment variable).
- [Django]-Pylint "unresolved import" error in Visual Studio Code
- [Django]-How can I enable CORS on Django REST Framework
- [Django]-Django error when installing Graphite โ settings.DATABASES is improperly configured. Please supply the ENGINE value
14๐
I think this wasnโt mentioned yet, but is a common cause for the error: The error occurs when you specify startup code that uses models. If you follow this approach and put it into your AppConfig
you must not import models at the top of the file, but inside the ready()
method. For example as follows:
# works as models are imported in the ready() method
from django.apps import AppConfig
class MatcherConfig(AppConfig):
name = 'matcher'
verbose_name = 'Match-Making'
def ready(self):
from matcher.background_tasks import close_timeout_games
from matcher.models import FourPlayerGame
# check if a player is not responding every 5 seconds
close_timeout_games(FourPlayerGame, repeat=5)
However, the following would be wrong:
# won't work as models are imported at the beginning
from django.apps import AppConfig
from matcher.background_tasks import close_timeout_games
from matcher.models import FourPlayerGame
class MatcherConfig(AppConfig):
name = 'matcher'
verbose_name = 'Match-Making'
def ready(self):
# check if a player is not responding every 5 seconds
close_timeout_games(FourPlayerGame, repeat=5)
For more information also see this answer.
- [Django]-How to get an ImageField URL within a template?
- [Django]-How to mix queryset results?
- [Django]-Creating email templates with Django
12๐
This error may occur when you are adding an app in INSTALLED_APPS
in the settings.py
file but you do not have that app installed in your computer. You have two solution:
Install
that app using package managers likepip
in ubuntu- Or Comment out that installed app in the
settings.py
file
This error may also arise if you are not in your virtual environment
which you may have created for your project.
- [Django]-Django DRF with oAuth2 using DOT (django-oauth-toolkit)
- [Django]-Difference between User.objects.create_user() vs User.objects.create() vs User().save() in django
- [Django]-How to view corresponding SQL query of the Django ORM's queryset?
9๐
First import and run django.setup() before importing any models
All the above answers are good but there is a simple mistake a person could do is that (In fact in my case it was).
I imported Django model from my app before calling django.setup()
. so proper way is to doโฆ
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings')
import django
django.setup()
then any other import like
from faker import Faker
import random
# import models only after calling django.setup()
from first_app.models import Webpage, Topic, AccessRecord
- [Django]-Itertools.groupby in a django template
- [Django]-Django CSRF check failing with an Ajax POST request
- [Django]-How to Unit test with different settings in Django?
7๐
For me, the problem came from the fact that I was importing an app in INSTALLED_APPS
which was itself importing a model in its __init__.py
file
I had :
settings.py
INSTALLED_APPS = [
...
'myapp',
...
]
myapp.__init__.py
from django.contrib.sites.models import Site
commenting out import models
in myapp.__init__.py
made it work :
# from django.contrib.sites.models import Site
- [Django]-Django set default form values
- [Django]-How to check if a user is logged in (how to properly use user.is_authenticated)?
- [Django]-Python + Django page redirect
5๐
Try removing the entire settings.LOGGING
dictConfig and restart the server. If that works, rewrite the setting according to the v1.9 documentation.
https://docs.djangoproject.com/en/1.9/topics/logging/#examples
- [Django]-Django, creating a custom 500/404 error page
- [Django]-What's the best way to store a phone number in Django models?
- [Django]-Django-way for building a "News Feed" / "Status update" / "Activity Stream"
5๐
You may get this error if youโve started normal Python shell by mistake and trying to import your Django models in that.
You should instead use python manage.py shell
for that.
- [Django]-Django values_list vs values
- [Django]-How can I build multiple submit buttons django form?
- [Django]-How can I filter a Django query with a list of values?
3๐
For me commenting out
'grappelli.dashboard',
'grappelli',
in INSTALLED_APPS worked
- [Django]-Django CSRF check failing with an Ajax POST request
- [Django]-Django โ makemigrations โ No changes detected
- [Django]-Django admin TabularInline โ is there a good way of adding a custom html column?
3๐
django.setup() in the top will not work while you are running a script explicitly.
My problem solved when I added this in the bottom of the settings file
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
import sys
if BASE_DIR not in sys.path:
sys.path.append(BASE_DIR)
os.environ['DJANGO_SETTINGS_MODULE'] = "igp_lrpe.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "igp_lrpe.settings")
import django
django.setup()
- [Django]-Django โ how to unit test a post request using request.FILES
- [Django]-Separation of business logic and data access in django
- [Django]-Django: For Loop to Iterate Form Fields
2๐
I put the User
import into the settings
file for managing the rest call token like this
# settings.py
from django.contrib.auth.models import User
def jwt_get_username_from_payload_handler(payload):
....
JWT_AUTH = {
'JWT_PAYLOAD_GET_USERNAME_HANDLER': jwt_get_username_from_payload_handler,
'JWT_PUBLIC_KEY': PUBLIC_KEY,
'JWT_ALGORITHM': 'RS256',
'JWT_AUDIENCE': API_IDENTIFIER,
'JWT_ISSUER': JWT_ISSUER,
'JWT_AUTH_HEADER_PREFIX': 'Bearer',
}
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
}
Because at that moment, Django libs are not ready yet. Therefore, I put the import
inside the function and it started to work. The function needs to be called after the server is started
- [Django]-Django admin: how to sort by one of the custom list_display fields that has no database field
- [Django]-Django override save for model only in some cases?
- [Django]-How to use MySQLdb with Python and Django in OSX 10.6?
2๐
I get that error when I try to run test.py
(not full scripts, I donโt want to use python manage.py test
)
and the following method is working for me.
import os
import django
if 'env setting':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'YourRoot.settings')
django.setup()
from django.test import TestCase
...
class SomeTest(TestCase):
def test_one(self): # <-- Now, I can run this function by PyCharm
...
def test_two(self):
...
- [Django]-ImportError: No module named 'django.core.urlresolvers'
- [Django]-Adding a user to a group in django
- [Django]-How to implement followers/following in Django
1๐
My problem was:
django-reversion>=1.8.7,<1.9
for django 1.9.7 you should use:
django-reversion==1.10.0
I were upgraded django-cms 3.2 to 3.3, and found it by commenting apps, then uncommenting back.
Correct answer here:
https://stackoverflow.com/a/34040556/2837890
- [Django]-On Heroku, is there danger in a Django syncdb / South migrate after the instance has already restarted with changed model code?
- [Django]-Django ManyToMany filter()
- [Django]-Django DB Settings 'Improperly Configured' Error
1๐
This issue is also observed for inconsistent settings.py for incorrectly writing INSTALLED_APPS, verify if you correctly included apps and separated with โ,โ .
- [Django]-When saving, how can you check if a field has changed?
- [Django]-Django datetime issues (default=datetime.now())
- [Django]-What's the difference between CharField and TextField in Django?
1๐
When I change my django version to 1.9, it donโt arise the error.
pip uninstall django
pip install django==1.9
- [Django]-How to access request body when using Django Rest Framework and avoid getting RawPostDataException
- [Django]-How to combine multiple QuerySets in Django?
- [Django]-How to update an existing Conda environment with a .yml file
1๐
I was in trouble with such matter
my problem was because of having this piece of code in settings.py
import myapp.models
when I removed this code problem fixed
I recommend check your settings.py and remove such code
- [Django]-Django error: got multiple values for keyword argument
- [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?
0๐
In my case one of my settings, โCORS_ORIGIN_WHITELISTโ was set in the settings.py file but was not available in my .env file. So Iโll suggest that you check your settings, especially those linked to .env
- [Django]-Adding to the "constructor" of a django model
- [Django]-Constructing Django filter queries dynamically with args and kwargs
- [Django]-Trying to migrate in Django 1.9 โ strange SQL error "django.db.utils.OperationalError: near ")": syntax error"
0๐
As others have said this can be caused when youโve not installed an app that is listed in INSTALLED_APPS
.
In my case, manage.py
was attempting to log the exception, which led to an attempt to render it which failed due to the app not being initialized yet. By
commenting out the except
clause in manage.py
the exception was displayed without special rendering, avoiding the confusing error.
# Temporarily commenting out the log statement.
#try:
execute_from_command_line(sys.argv)
#except Exception as e:
# log.error('Admin Command Error: %s', ' '.join(sys.argv), exc_info=sys.exc_info())
# raise e
- [Django]-Iterating over related objects in Django: loop over query set or use one-liner select_related (or prefetch_related)
- [Django]-Django: Record with max element
- [Django]-Django: Grab a set of objects from ID list (and sort by timestamp)
0๐
I tried tons of things, but only downgrading Django to 1.8.18 fixed this issue for me:
pip install django==1.8.18
It is one of the installed apps that is failing, but I could not find which one.
- [Django]-Django โ getting Error "Reverse for 'detail' with no arguments not found. 1 pattern(s) tried:" when using {% url "music:fav" %}
- [Django]-Get user profile in django
- [Django]-Why does DEBUG=False setting make my django Static Files Access fail?
0๐
I get that error when i try to run:
python manage.py makemigrations
i tried so many things and realized that i added some references to โsettings.pyโ โ โINSTALLED_APPSโ
Just be sure what you write there is correct. My mistake was โ.model.โ instead of โ.app.โ
Corrected that mistake and itโs working now.
- [Django]-Specifying limit and offset in Django QuerySet wont work
- [Django]-Setting DEBUG = False causes 500 Error
- [Django]-Django switching, for a block of code, switch the language so translations are done in one language
0๐
Iโve run into this problem and it was rooted in asgi.py. weโve loaded the below module:
from channels.auth import AuthMiddlewareStack
but we didnโt use it in the ProtocolTypeRouter. apparently, we have to use
websocket or other protocols when we call the AuthMiddlewareStack module.
- [Django]-Django related_name for field clashes
- [Django]-Laravel's dd() equivalent in django
- [Django]-Suddenly when running tests I get "TypeError: 'NoneType' object is not iterable
0๐
For others that might stumble upon this in future:
If you encounter this issue while running Python 3.8 and trying to use multiprocessing package, chances are that it is due to the sub processed are โspawnedโ instead of โforkedโ. This is a change with Python 3.8 on Mac OS where the default process start method is changed from โforkโ to โspawnโ.
This is a known issue with Django.
To get around it:
import multiprocessing as mp
mp.set_start_method('fork')
- [Django]-How do I get the class of a object within a Django template?
- [Django]-Mixin common fields between serializers in Django Rest Framework
- [Django]-Django: Arbitrary number of unnamed urls.py parameters
0๐
I faced this problem when I was trying to load a function in the init file (__init__.py
) of my settings package.
The cause of this error
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
is that, before settings were loaded, I wanted to load another module (e.g. rest_framework
).
To solve this, I put functions in another module (file) in settings package
(e.g. common.py
), and it solved the problem.
- [Django]-Separating form input and model validation in Django?
- [Django]-How to run a celery worker with Django app scalable by AWS Elastic Beanstalk?
- [Django]-How to manage local vs production settings in Django?
0๐
The reason I got this error appregistrynotready
is That I accidentally Register User model
in app.py
instead of admin.py
This is how itโs looked like
app.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import User
@admin.register(User)
class UserAdmin(BaseUserAdmin):
pass
- [Django]-UUID as default value in Django model
- [Django]-How to merge consecutive database migrations in django 1.9+?
- [Django]-Django delete FileField
0๐
i faced the same issue when i used
from django.urls import reverse
Solution:
from django.urls import reverse_lazy
- [Django]-Reducing Django Memory Usage. Low hanging fruit?
- [Django]-Separating form input and model validation in Django?
- [Django]-Get count of related model efficiently in Django
-1๐
Late to the party, but grappelli was the reason for my error as well. I looked up the compatible version on pypi and that fixed it for me.
- [Django]-Execute code when Django starts ONCE only?
- [Django]-How do I POST with jQuery/Ajax in Django?
- [Django]-Create Django model or update if exists
-1๐
Try activating the virtual env.
In my case, using the git command line tool:
source scripts/activate
Solves my problem.
- [Django]-Extend base.html problem
- [Django]-How to use MySQLdb with Python and Django in OSX 10.6?
- [Django]-Class has no objects member
-1๐
Got this error while trying to access model objects in apps.py
:
class QuizConfig(AppConfig):
name = 'quiz'
def ready(self):
print('===============> Django just started....')
questions_by_category = Question.objects.filter(category=2) # <=== Guilty line of code.
Trying to access Question
before the app has loaded the model class caused the error for me.
- [Django]-Django QuerySet order
- [Django]-What does on_delete do on Django models?
- [Django]-Django โ Rotating File Handler stuck when file is equal to maxBytes
-2๐
If your setting.py files fill are correct๏ผyou can try to arrive manage.py files proceed call danjgo.setup() in main method . Then run manage.py ,finally again run project ,the issue could disappear.
- [Django]-How to automate createsuperuser on django?
- [Django]-Django โ getting Error "Reverse for 'detail' with no arguments not found. 1 pattern(s) tried:" when using {% url "music:fav" %}
- [Django]-Creating a dynamic choice field
-2๐
In the โadminโ module of your app package, do register all the databases created in โmodelsโ module of the package.
Suppose you have a database class defined in โmodelsโ module as:
class myDb1(models.Model):
someField= models.Charfiled(max_length=100)
so you must register this in the admin module as:
from .models import myDb1
admin.site.register(myDb1)
I hope this resolve the error.
- [Django]-Django.contrib.auth.logout in Django
- [Django]-Python Asyncio in Django View
- [Django]-Where to put business logic in django