views:

228

answers:

3

In my Django project, the following line throws an ImportError: "No module named elementtree".

  from elementtree import ElementTree

However, the module is installed (ie, I can run an interactive python shell, and type that exact line without any ImportError), and the directory containing the module is on the PYTHONPATH. But when I access any page in a browser, it somehow can't find the module, and throws the ImportError. What could be causing this?

A: 

Go into your installation directory

Example:

C:\Python26\Lib\site-packages

And check if both elementtree and django are in there.

If they are both not there, then you probably have multiple installation directories for different versions of Python.


In any case, you can solve your problem by running this command:

python setup.py install

Run it twice, once inside the download for django and once inside the download for elementtree. It will install both of the downloads into whatever your current default python is.

References:

Brian R. Bondy
elementtree is in my installation directory ($HOME/lib/python/), but I think I have multiple installation directories (all of which are on the PYTHONPATH, but I don't know if I need to do anything beyond that). I'm also using a local python (`which python` gives me $HOME/local/bin/python, rather than the usual /usr/bin/python).
raviv
added some more details on how to possibly fix.
Brian R. Bondy
A: 

I've also run into cross-platform issues where ElementTree was available from different modules on different systems... this ended up working for me:

try:
    import elementtree.ElementTree as ET
except:
    import xml.etree.ElementTree as ET

May or may not help for you...

Gabriel Hurley
+1  A: 

Can you import elementtree within the django shell:

python manage.py shell

Assuming you have multiple python versions and do not know which one is being used to run your site, add the following to your view and push python_ver to your template, it will show you the Python version you are using:

import sys
python_ver = sys.version

You can also explicitly add the path to elementtree programatically in your settings.py:

import sys
sys.path.append('path to where elementtree resides')
Thierry Lam
Thanks! Manually adding elementtree to the python path with `sys.path.append()` did the trick.
raviv