I have installed Django AND Oscar by running the commands in given order:
virtualenv eshop_env
eshop_env/Scripts/Activate
pip install django-oscar
django-admin.py startproject eshop
cd eshop
manage.py migrate
The settings.py file in eshop directory has these two lines a the top:
import os
from oscar.default import *
The os module is importe without any error. However, there is a red wavy line under from.
I am using Visual Studio Code. When I hover over the line, it says unable to import oscar.default. The same error appears on all my import statement involving django and oscar.
This also results in the follwing error in Command line after i run the migrate command:
ModuleNotFoundError: No module named 'oscar.default'
I tried running
pip install oscar.default
pip install oscar
but both of them show an error.
However, I was able to successfully run the pip install django-oscar command again. But, he error about the module does not change.
What am I doing wrong?
This is my project directory structure:
D:\Python Websites\Example\eshop\
D:\Python Websites\Example\eshop_env\
D:\Python Websites\Example\eshop\manage.py
D:\Python Websites\Example\eshop\eshop\settings.py, urls.py etc.
The import error occurs with all other modules as well:
from django.apps import apps
from django.urls import include, path # > Django-2.0
from django.contrib import admin
from oscar.app import applications
Visual Studio Code shows a red way line for all of them with an error that starts like Unable to Import ....
I think you have installed django-oscar in the virtual environment and that is not the problem. I think you have to 'tell' the VS Code to use the specific virtualenv named eshop_env.
Please check this link for details instructions on how to tell vscode which virtualenv to use: https://code.visualstudio.com/docs/python/environments.
Good luck.
To check where Python is looking for your files, copy this code in settings.py
import os
import environ
import oscar
# To check where is looking Python
env = environ.Env()
from os.path import dirname, abspath
ROOT = dirname(abspath(__file__)).replace('\\', '/') + '/'
print ("self.__name__: " + __name__)
print ("self.__file__: " + __file__)
print ("ROOT: " + ROOT)
import django
print (django.__path__)
print (oscar.__path__)
print (environ.__path__)
...
Then type 'python manage.py runserver' in console. I hope this will help you.
I'm following the Flask Mega Tutorial, and I'm running into an issue once I get to the second part and restructure my folder structure to match theirs, I cannot import Flask.
My current folder structure is as follows
/FlaskTest
/app
/static, templates etc
/flask
/virtualenv folders etc
/tmp
run.py
as far as I can tell, the folder structures are identical other than naming of the top level directory.
in my __init__.py file (/app/__init__.py), I'm doing as instructed in the tutorial,
from flask import Flask
app = Flask(__name__)
from app import views
I'm getting an Import Error that "cannot import name 'Flask'". I'm guessing the issue is because the flask package was installed to /flask/lib/site-packages.
My question: How can I reference the sub folder of flask/site-packages?
I've read through the python import system documentation and from what I can make of it through the first pass of reading it over, I would need to likely do something like from flask import flask.Flask or something to that effect.
UPDATE: So after cd'ing around the directory and checking pip list, I realized that flask wasn't accessible to my app directory. I ran pip install flask in the app directory. Now my site runs, but I'm not sure if this is the best practice of doing things with Python. Please provide some clarity as what the best practice is for installing packages and where the packages reside.
UPDATE 2: After creating a directory called standalone. In this folder, I created a virtual environment called standalone-test. Once, I did that, I also mkdir'ed app and copied it's contents from FlaskTest so that way the code would be identical. I was able to run the run.py script by using python run.py, but I can't run python -m app like you had said without running into an error. The error is as follows if it helps.
"No module name app.main; 'app' is a package and cannot be directly executed.
I am able to run python run.py as I mentioned, but I'm not able to run the python -m app command as you had mentioned
I think something went wrong in your execution environment. Here are some explanations.
The virtualenv
See the documentation of virtualenv
If you have followed the tutorial:
The flask directory is your virtualenv,
On posix system, you have a flask/bin subdirectory, or
On Windows system, you have a flask\Scripts subdirectory.
I make the assumption that you are on posix system.
To activate your virtualenv, run:
source flask/bin/activate
Your prompt should change to something like: (flask)$.
To list the installed libraries use pip:
pip list
Make sure you see Flask. The tutorial encourages you to install a lot of Flask plugins, so there are a lot of Flask-Something…
If Flask is missing, install it:
pip install Flask
Run your app
Your application is in the app directory, it has an __init__.py file (it's a Python package).
In this file, you have:
from flask import Flask
app = Flask(__name__)
from app import views
From your FlaskTest/ directory, try to run this script like this:
cd FlaskTest/ # if not in this directory
python -m app
This should import Flask, instanciate your app (but don't run it), import the views module.
If app/views.py exist you should have no error.
=> at this point, we have simulated what run.py imports…
Now write run.py in your FlaskTest/ directory:
#!flask/bin/python
from app import app
app.run(debug=True)
Run it like this:
python run.py
Note that the shebang #!flask/bin/python is unusual, but should work in the context of the tutorial.
This should start your http server…
When upgraded to django 1.9 from 1.8 I got this error. I checked answers for similar questions, but I didn't think this is an issue with any 3rd party packages or apps.
Traceback (most recent call last):
File "manage.py", line 10, in <module> execute_from_command_line(sys.argv)
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
utility.execute()
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 342, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 176, in fetch_command
commands = get_commands()
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/utils/lru_cache.py", line 100, in wrapper
result = user_function(*args, **kwds)
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 71, in get_commands
for app_config in reversed(list(apps.get_app_configs())):
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/apps/registry.py", line 137, in get_app_configs
self.check_apps_ready()
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
I'd modified the Installed apps for 'django.contrib.auth'.
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.
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.
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.
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).
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 like pip 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.
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.
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
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
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
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.
For me commenting out
'grappelli.dashboard',
'grappelli',
in INSTALLED_APPS worked
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()
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
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):
...
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
This issue is also observed for inconsistent settings.py for incorrectly writing INSTALLED_APPS, verify if you correctly included apps and separated with "," .
When I change my django version to 1.9, it don't arise the error.
pip uninstall django
pip install django==1.9
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
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
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
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
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.
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.
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.
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')
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.
i faced the same issue when i used
from django.urls import reverse
Solution:
from django.urls import reverse_lazy
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.
Try activating the virtual env.
In my case, using the git command line tool:
source scripts/activate
Solves my problem.
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.
Trying to run django project, installed all stuff from requirements.txt but still getting error
from django.contrib.admin import ModelAdmin, actions
ImportError: cannot import name actions
Can't find anything useful about it. Does anybody know how to fix it?
UPDATE:
I've found that there is no settings.py file but settings folder instead of it and it contains common.py and production.py and no settings.py. May be that's the problem?
I've tried to run import manually in python shell like this:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "chipped.settings.common")
from django.contrib.admin import ModelAdmin, actions
And it told me that there is no postgresql_psycopg2 module. I changed database engine to django.db.backends.sqlite3 and now it works.
i got this error when i upgraded my os x to mavericks
as quux mentioned, you can get real error from python shell and indeed it was _psycopg.so referencing some library that's not available.
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
from django.contrib.admin import ModelAdmin, actions
Library not loaded: /usr/local/lib/libpq.5.6.dylib
Referenced from: /Users/nreeves/venvs/gd_api_env/lib/python2.7/site-packages/psycopg2/_psycopg.so
Reason: image not found
so i need to have library link to where _psycopg.so look for.
first I need to locate the lib itself
i installed with brew so my lib is here:
/usr/local/Cellar/postgresql/9.3.4/lib/libpq.5.6.dylib
then I created symlink to /usr/lib (or /usr/local/lib)
sudo ln -s /usr/local/Cellar/postgresql/9.3.4/lib/libpq.5.6.dylib /usr/lib
and all fixed.
This happened to me, turns out I had my database password wrong in settings.py
It happened with me on the one of my projects. I used last version of psycopg2.
I installed to psycopg2==2.5.3 (my other projects use it version) and now it works.
What is actions? You get this error because it isn't present in the admin module