Django installed, but can't import django in python
I've installed Django multiple ways, via apt-get
and pip install
. They all say I have the most recent version of Django. Now whenever I run python in Terminal and type in import django, I receive
ImportError: No module named django
However, when I run django-admin --version
I receive
1.4.3
I know it's installed, but why is python not finding the django module?
Solution 1:
python
is not finding django
because it's not on its path. You can see the list of paths python
looks for modules like this:
$ python
>>> import sys
>>> sys.path
You can import django
if you find the location it is installed, and add that location to python
's path, for example like this:
$ PYTHONPATH=/path/to/django/parent/dir python
>>> import django # should work now
But your real problem is that something's wrong with your python
installation. If you have installed both python
AND django
using apt-get
, then django
should certainly be on python
's path without dirty hacks like above.
That said, when working with Django, your best bet is to NOT use apt-get
but create a virtual environment using virtualenv
(you can install virtualenv
itself using apt-get
), and install Django and other modules your Django site might need using pip
within the virtual environment. That way you can have multiple Django projects side by side, with precisely the Python modules and versions it requires. It's just a few extra steps to do, but definitely worth it and will save you from much frustration in the future.
Solution 2:
I had the same problem when I was using PyCharm Community Edition for making Django projects.
For me, the following steps worked:
It turns out that python wants you to create a virtual environment, install django in that and then run the server. To do this,
Create a Virtual Environment
1) Install virtual environment using
pip install virtualenv
.2) Navigate to the project folder and type
virtualenv env
(Hereenv
is the name of the virtual environment.) This will create a new folder namedenv
inside the project folder.3) Navigate to
env/Scripts
inside your Project Folder usingcd env/Scripts
.4) Type
activate
and press Enter. This should start the virtual environment. You can verify this as(env)
would be prefixed to your current path.
Install Django
1) Once inside the virtual environment, head back to your project folder using
cd ../..
and typepip install django
.2) You can verify its installation by typing
django-admin --version
. It should display the django version number installed inside the virtual environment.
Now type python manage.py runserver
to start the python server.