ImportError: Couldn't import Django. PYTHONPATH - python

There was an error account.User that has not been installed
but I solved this problem. After that, another error says The SECRET_KEY setting must not be empty.
I don't know whether my method to solve this problem is correct or not, I applied some solutions with Google.
But now, there is an error ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
But I already installed django and virtualenv. I don't know how to do it.
Recent error:
Traceback (most recent call last):
File "/Users/leejunseo/PycharmProjects/ITM coding/manage.py", line 10, in main
from django.core.management import execute_from_command_line
File "/Users/leejunseo/PycharmProjects/ITM coding/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 12, in <module>
from django.conf import settings
File "/Users/leejunseo/PycharmProjects/ITM coding/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 21, in <module>
from .base import *
ModuleNotFoundError: No module named 'django.conf.base'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/leejunseo/PycharmProjects/ITM coding/manage.py", line 21, in <module>
main()
File "/Users/leejunseo/PycharmProjects/ITM coding/manage.py", line 12, in main
raise ImportError(
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
MY code manage.py
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tothegemList.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
__init__.py
import functools
import os
import pkgutil
import sys
from argparse import _SubParsersAction
from collections import defaultdict
from difflib import get_close_matches
from importlib import import_module
import django
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import (
BaseCommand, CommandError, CommandParser, handle_default_options,
)
from django.core.management.color import color_style
from django.utils import autoreload
def find_commands(management_dir):
"""
Given a path to a management directory, return a list of all the command
names that are available.
"""
command_dir = os.path.join(management_dir, 'commands')
return [name for _, name, is_pkg in pkgutil.iter_modules([command_dir])
if not is_pkg and not name.startswith('_')]
.
.
.
conf/__init__py
import warnings
from pathlib import Path
import django
from django.conf import global_settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.deprecation import RemovedInDjango40Warning
from django.utils.functional import LazyObject, empty
from .base import *
env_name = os.getenv('ENV_NAME', 'local')
if env_name == 'prod':
from .prod import *
elif env_name == 'stage':
from .stage import *
else:
from .local import *
ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE"

Your traceback is telling you exactly what is wrong :
Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
So you should relaunch your IDE or activate your environnement, as Django cannot be launch

I am using a Mac OSX 10.13.6. I have Python 3.9 installed.
I activated my venv, then installed Django. When I use 'pip list' or 'pip3 list', it lists Django as one of the Python packages that are installed. In addition, I was able to create a project using "django-admin startproject . If Django was not installed or I was not using venv, then I could not execute the django-admin command.
Also, I checked the venv/lib/python3.9/site-packages and django and other Python packages are installed in that directory. AND I did
'export PYTHONPATH=/Library/Frameworks/Python.framework/Versions/3.9'.
So, it is somewhat confusing why python3 is not finding Django. Any suggestions?

I installed django through this command
pip install django

Related

multipledispatch ModuleNotFoundError running from command-line

Running a locust (locust.io) script from the command line.
locust calls main.py which has the following imports:
from locust import HttpUser, between, task
from StreamLoader.stream_generator import * # thought this brings in everything
Packer.py has these imports:
from multipledispatch import dispatch
from PackedItem import PackedItem
StreamGenerator.py has:
import hashlib
from StreamLoader.Packer import Packer
from aes_encryption import AesEncryption
I used pip to install multipledispatch and when I run from within PyCharm it works fine, but from the command line I get the following.
File "C:\Users\guyl\PycharmProjects\engine-load-tests\engine_load_tester_locust\main.py", line 2, in <module>
from StreamLoader.stream_generator import *
File "C:\Users\guyl\PycharmProjects\engine-load-tests\StreamLoader\stream_generator.py", line 2, in <module>
from StreamLoader.Packer import Packer
File "C:\Users\guyl\PycharmProjects\engine-load-tests\StreamLoader\Packer.py", line 1, in <module>
from multipledispatch import dispatch
ModuleNotFoundError: No module named 'multipledispatch'
Here is what I have tried so far:
Add directories to the PYTHONPATH environment variable
Add empty __init__.py files in each package
This all seems unnecessary if I actually pip installed the module, though.
Answer below caused me to no longer see the error with multipledispatch. However, I now see a missing module error:
File "C:\Users\guyl\PycharmProjects\engine-load-tests\engine_load_tester_locust\main.py", line 2, in <module>
from StreamLoader.stream_generator import *
File "C:\Users\guyl\PycharmProjects\engine-load-tests\StreamLoader\stream_generator.py", line 2, in <module>
from Packer import Packer
ModuleNotFoundError: No module named 'Packer'
For clarity, I am running the code from locust which calls the Python code as depicted here. [Moderators - this question is getting quite long. Is that all right?]
PyCharm uses the virtual environment automatically but when you run from the command line the virtual environment isn't turned on.
Just follow the steps:
cd your_working_directory
environment_name/Scripts/activate if on Windows where environment_name is the name of the PyCharm virtual environment
Or environment_name/bin/activate if on MacOS
-------------EDIT------------------------
To answer the new question, try using pip freeze then see which packages are installed. Then install any dependencies which you want which are missing.

Google App Engine: ImportError: No module named appengine.ext

I am trying to write a test for my GAE programme which uses the datastore.
Following Google's Documentation, I see that I should be adding the path to my SDK into my PYTHONPATH.
I did this using:
import sys
sys.path.remove('/usr/local/lib/python2.7/dist-packages') # Has a 'google' module, which I want to be sure isn't interfering.
sys.path.insert(1,'/home/olly/google-cloud-sdk/platform/google_appengine')
sys.path.insert(1, '/home/olly/google-cloud-sdk/platform/google_appengine/lib/yaml/lib')
Then when the file is run:
Traceback (most recent call last):
File "myapp_tests.py", line 20, in <module>
from google.appengine.ext import ndb
ImportError: No module named appengine.ext
I have installed the SDK in the location above, and looking in /home/olly/google-cloud-sdk/platform/google_appengine/ I found the google folder, which has an __init__.py in it, along with appengine. Basically, the folder structure looks good to me, with them all being named correctly and having __init__.py files.
In an interactive console, after running the commands above, I found that I could run:
import google
no problem, but when I tried
import google.appengine
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named appengine
It was my understanding that having the __init__.py() files in the directories meant that they could be imported as above.
I also did a sudo find / --name "google", and the only thing that showed up that is also in my PYTHONPATH was the /usr/local/lib/python2.7/dist-packages, which I explicitly removed, and also inserted the rest of my paths in front of anyway.
I tried using GAE's own method of:
import dev_appserver
dev_appserver.fix_sys_path()
which added a whole lot of paths to sys.path, but still didn't help me make it work.
I also found that when I add '/home/olly/Servers/google_appengine/google' to my paths, I can run:
import appengine.ext
but running:
from appengine.ext import ndb
causes:
Traceback (most recent call last):
File "booking_function_tests.py", line 16, in <module>
from appengine.ext import ndb
File "/home/olly/Servers/google_appengine/google/appengine/ext/ndb/__init__.py", line 7, in <module>
from tasklets import *
File "/home/olly/Servers/google_appengine/google/appengine/ext/ndb/tasklets.py", line 69, in <module>
from .google_imports import apiproxy_stub_map
File "/home/olly/Servers/google_appengine/google/appengine/ext/ndb/google_imports.py" , line 11, in <module>
from google3.storage.onestore.v3 import entity_pb
ImportError: No module named google3.storage.onestore.v3
Am I missing something really obvious? How should I go about importing ndb?
EDIT:
I'm running the latest SDK (1.9.34), but I have the following code in my google_imports.py:
try:
from google.appengine.datastore import entity_pb
normal_environment = True
except ImportError:
try:
from google3.storage.onestore.v3 import entity_pb
normal_environment = False
except ImportError:
# If we are running locally but outside the context of App Engine.
try:
set_appengine_imports()
from google.appengine.datastore import entity_pb
normal_environment = True
except ImportError:
raise ImportError('Unable to find the App Engine SDK. '
'Did you remember to set the "GAE" environment '
'variable to be the path to the App Engine SDK?')
Also, google.__path__ gives me the '/usr/local/lib/python2.7/dist-packages' path which I thought I removed earlier. Here is an excerpt of how I'm removing it:
import sys
sys.path.insert(1, '/home/olly/Servers/google_appengine')
sys.path.insert(1, '/home/olly/Servers/google_appengine/lib/yaml/lib')
sys.path.remove('/usr/local/lib/python2.7/dist-packages')
import google
print google.__path__
print sys.path
['/usr/local/lib/python2.7/dist-packages/google']
['/home/olly/Servers/google_appengine/myapp', '/home/olly/Servers/google_appengine/lib/yaml/lib', '/home/olly/Servers/google_appengine/google', '/home/olly/Servers/google_appengine', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode']
So my sys.path is updated, but import google seems to still be importing from the no-longer-there path, which would be the crux of my problem I guess. Do I need to reload the path or something?
I run into these problems a lot less by always running inside a virtualenv.
I agree with snakecharmerrb you should get print google.__file__ or google.__path_ to figure out exactly what you're importing.
This snippet might also solve your problem:
import google
gae_dir = google.__path__.append('/path/to/appengine_sdk//google_appengine/google')
sys.path.insert(0, gae_dir) # might not be necessary
import google.appengine # now it's on your import path`
Which version of app engine SDK are you using? I am using the latest SDK (1.9.34). I find the below snippet in my ~/google_appengine/google/appengine/ext/ndb/google_imports.py file
try:
from google3.storage.onestore.v3 import entity_pb
normal_environment = False
except ImportError:
# If we are running locally but outside the context of App Engine.
try:
set_appengine_imports()
from google.appengine.datastore import entity_pb
normal_environment = True
except ImportError:
raise ImportError('Unable to find the App Engine SDK. '
'Did you remember to set the "GAE" environment '
'variable to be the path to the App Engine SDK?')
But in your stack trace, after google3.storage import it doesn't seem to go inside the except clause.
So try the same code with latest SDK.

ImportError: works on osx not on ubuntu

I have a strange import problem with python. The same code works on OSX, but it doesn't work on precise 12.04.
test.py
lib/
twitter/
twitterstream.py
__init__.py
The twitterstream.py has a class TwitterStream.
test.py:
import sys
sys.path.append('./lib')
import twitter.twitterstream
tw = twitter.twitterstream.TwitterStream()
tweets = tw.fetchsamples()
print tweets
I am getting following error:
> python test.py
Traceback (most recent call last):
File "test.py", line 3, in
import twitter.twitterstream
ImportError: No module named twitterstream
You have another module twitter installed on your Ubuntu machine.
You put the ./lib path at the end of the module search path; the other twitter module is installed in a location listed on the sys.path search path before that.
Insert ./lib at the start instead:
sys.path.insert(0, './lib')

python manage.py run server return ImportError

Traceback (most recent call last):
File "manage.py", line 2, in <module>
from django.core.management import execute_manager
ImportError: cannot import name execute_manager
I downloaded a django blog project from github and i want to see if work, then i got this, what's it means?
I have checked the manage.py ,here is the code:
#!/usr/bin/env python
from django.core.management import execute_manager
import imp
try:
imp.find_module('settings') # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
sys.exit(1)
import settings
if __name__ == "__main__":
execute_manager(settings)
some kind of difference from defaults. So if do i have not enough authority to import execute_manager which may not exist?
what should i do?
Sounds like you are using Django 1.6 or newer where execute_manager() was deprecated and removed:
The functions setup_environ() and execute_manager() will be removed
from django.core.management. This also means that the old (pre-1.4)
style of manage.py file will no longer work.
This django blog project you are using is probably not actively maintained and doesn't support 1.6.
Use execute_from_command_line() instead:
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
Also see this manage.py template for Django 1.6 from the django sources.

ImportError: No module named test_data, but test_data.py in same directory as test.py under PyCharm using virtualenv

In test.py, I am trying to import test_data:
import unittest2
import re
from test_data import receipt1_example
test_data.py is in the same directory as test.py. I get the following error:
/Users/ahammond/.virtualenvs/ric2.6/bin/python2.6
/Applications/PyCharm.app/helpers/pycharm/utrunner.py
/Users/ahammond/src/hackfest_spring_2012/parse_me/test.py::test true
Testing started at 11:30 AM ... Traceback (most recent call last):
File "/Applications/PyCharm.app/helpers/pycharm/utrunner.py", line
121, in
module = loadSource(a[0]) File "/Applications/PyCharm.app/helpers/pycharm/utrunner.py", line 44, in
loadSource
module = imp.load_source(moduleName, fileName) File "/Users/ahammond/src/hackfest_spring_2012/parse_me/test.py", line 4,
in
from test_data import receipt1_example ImportError: No module named test_data
Process finished with exit code 1
As you can see, I am running this under pycharm using a virtualenv. Here's a screenshot of the configuration:
The work around i use is:
import sys
import os
try:
import test_data
except ImportError:
sys.path.append(os.path.dirname(__file__))
try:
import test_data
finally:
sys.path.remove(os.path.dirname(__file__))
A friend told me that one can also add the directory entries to some include directories.
Please try PyCharm 2.5.1 RC, there was a bug with sys.path building (it contained incorrect, duplicated project source directory).
If it's not the case, you can mark additional directories as Source in Preferences | Project Structure or add them to the Paths in the Python Interpreters.

Categories