Error importing a python module in Django

回眸只為那壹抹淺笑 提交于 2019-12-06 10:52:52

问题


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?


回答1:


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')



回答2:


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...




回答3:


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:

  • Installation documentation for ElementTree
  • Installation documentation for Django


来源:https://stackoverflow.com/questions/1375382/error-importing-a-python-module-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!