简体   繁体   English

如果从Templetetag导入模块,Django无法找到我的模块

[英]Django couldn't find my module if it is imported from a templetetag

I'm upgrading an existing Django project to v1.7 and creating some templatetags to simplify working with templates. 我正在将现有的Django项目升级到v1.7,并创建一些模板标签以简化模板的使用。 I've created some before, but one of them is giving the following error: 我之前创建过一些,但是其中之一给出了以下错误:

ImportError raised loading recaptcha.templatetags.recaptcha: No module named utils . ImportError raised loading recaptcha.templatetags.recaptcha: No module named utils

This module looks like this: 该模块如下所示:

- recaptcha
     |- templatetags
     |         |- __init__.py
     |         |- recaptcha.py
     |
     |- __init__.py
     |- utils.py

The problematic import is in recaptcha.py and I tried from recaptcha import utils , from recaptcha.utils import myfunction and import recaptcha but none of them works. 有问题的导入在recaptcha.py中 ,我尝试from recaptcha import utils尝试, from recaptcha.utils import myfunctionimport recaptcha但是它们都from recaptcha.utils import myfunction If I only import recaptcha and I try to execute dir on it, it shows nothing. 如果我仅导入recaptcha并尝试在其上执行dir ,则它什么也不显示。

The weird thing is that if I import the utils module inside another django app in a view.py or a model.py file it works perfectly. 奇怪的是,如果我在view.py或model.py文件中的另一个django应用程序中导入utils模块,则它可以正常工作。 Also I tried using manage.py shell and it works too. 我也尝试使用manage.py shell ,它也可以工作。

As a clarification, this project does not use virtualenv right now. 为了澄清起见,该项目目前使用virtualenv。

Any ideas? 有任何想法吗? Thank you! 谢谢!

The solution that @catavaran answered before works: using a relative import like from ..utils import myfunction @catavaran回答的解决方案在起作用之前: 使用相对的导入,例如from ..utils import myfunction

The problem was that the templatetag module recaptcha.py and the django app recaptcha had both the same name , so when I type from recaptcha import utils it tries to find it from itself instead of from the recaptcha module . 问题在于templatetag模块recaptcha.py和django应用程序recaptcha 具有相同的名称 ,因此当我from recaptcha import utils键入内容时from recaptcha import utils 它将尝试从自身而不是从recaptcha模块中查找它 I renamed the django app to catpcha and it imports the module without problem. 我将django应用程序重命名为catpcha ,它可以catpcha导入模块。

@catavaran I don't really know why your answer is deleted, but if you post it again I'll mark it as the right one, you deserve the kudos! @catavaran我真的不知道为什么删除您的答案,但是如果您再次发布它,我会将其标记为正确的答案,您应该得到荣誉!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM