Python/Django is importing the wrong module (relative when it should be absolute)
I'm using Django 1.2 pre-alpha and Python 2.4. Yeah, I know, but I'm stuck with it. We can't upgrade at the moment and I doubt that's the answer anyway.
I've got two template tag libraries, foo
and bar
. However, foo
is also the name of a top-level package, and it happens to be the package of bar
:
foo-1.2.3/
foo/
conf/
settings.py
templatetags/
bar.py
bar-4.5/
somepackage/
templatetags/
foo.py
The tag library bar.py
开发者_运维技巧contains a line like this:
from foo.conf import settings
...and you would expect it to load foo-1.2.3/foo/conf/settings.py
.
But no:
TemplateSyntaxError: 'bar' is not a valid tag library: Could not load template library from django.templatetags.bar, No module named conf
Unfortunately, Django performs a little magic and binds all template tag libraries to django.templatetags.*
. Thus, bar
is being imported as django.templatetags.bar
, and when it calls from foo.conf import settings
it ends up importing bar-4.5/somepackage/templatetags/foo.py
. Ugh!
Do you have any ideas how to fix this?
I've set a breakpoint right before the import, and I've confirmed that foo-1.2.3
is at the beginning of sys.path
, but the import
keyword still finds the wrong foo
.
If it helps, note that I can modify the foo-1.2.3
package (because it's been checked in locally and is being phased out), but I refuse to modify the bar-4.5
package (because it's an open-source package and has been installed system-wide).
After a few more hours of hacking, this did the trick.
Original code:
from foo.conf import settings
New code:
foo = __import__('foo')
conf = __import__('foo.conf').conf
settings = __import__('foo.conf.settings').conf.settings
(I probably don't need the second line.)
Ewww.
精彩评论