[Django]-Error importing external library within Django template tag library

2👍

✅

This looks like one of those annoying relative path issues – solved in Python 2.6 and higher (where you can do import ..feedparser etc) but often a bit tricky on older versions. One cheap and cheerful way to fix this could be just to move feedparser.py in to your templatetags directory, as a sibling to twitterfeed.py

5👍

I solve this kind of problem (shipping libraries that are dependencies for my overall project) in the following way. First, I create an “ext” directory in the root of my project (in your case that would be myproject/ext). Then I place dependencies such as feedparser in that ext directory – myproject/ext/feedparser

Finally, I change my manage.py script to insert the ext/ directory at the front of sys.path. This means both ./manage.py runserver and ./manage.py shell will pick up the correct path:

# manage.py
import os, sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'ext'))
# ... rest of manage.py

I find this works really well if you don’t want to mess around with things like virtualenvs. When you deploy your project you have to make sure the path is correct as well – I usually solve this by adding the same sys.path.insert line to the start of my mod_wsgi app.wsgi file.

Leave a comment