简体   繁体   English

Django自定义模板标签:打包应用程序的ImportError

[英]Django custom template tags: ImportError for packaged app

I am writing custom template tags, for a reusable django app. 我正在为可重复使用的Django应用程序编写自定义模板标签。
The tag I am defining is referencing a model in the same app, so i need to import it. 我定义的标签在同一应用程序中引用了模型,因此我需要导入它。

Everything works fine if I copy my app code into a django project, but if I package my app with distutils and install it via pip or setup.py install (so the app code gets copied in site-packages), I cannot use it. 如果将我的应用程序代码复制到django项目中,一切都可以正常工作,但是如果我将我的应用程序与distutils打包并通过pip或setup.py install进行安装(这样,应用程序代码将复制到站点程序包中),则无法使用它。

When trying to import my application models in the template tags module, i get an ImportError. 当尝试在模板标签模块中导入我的应用程序模型时,出现了ImportError。 Code raising the error is this: 引发错误的代码是这样的:

from django import template 从Django导入模板
import cms_fragments.models 导入cms_fragments.models

register = template.Library() 注册= template.Library()

Exception raised is this: 引发的异常是这样的:

ImportError raised loading cms_fragments.templatetags.cms_fragments_tags: No module named models ImportError引发了加载cms_fragments.templatetags.cms_fragments_tags的问题:没有名为模型的模块

I am pretty sure that my application layout is correct: 我很确定我的应用程序布局正确:

|-cms_fragments | -cms_fragments

|- _ init _ .py | -_ 初始 _ .py
|-models.py | -models.py
|-templatetags | -templatetags

|- _ init _ .py | -_ 初始 _ .py
|-cms_fragments_tags.py | -cms_fragments_tags.py
|-views.py | -views.py

I have seen all posts related to this, but I never found anyone reporting this difference between an app with code living in the django-project versus code living in site-packages. 我看过所有与此相关的帖子,但是我从未发现有人报告过将代码驻留在django项目中的应用程序与驻留在站点包中的代码之间的差异。

Any hint? 有什么提示吗?

I think the problem is the way you are importing/using the library you want. 我认为问题在于您导入/使用所需库的方式。 It should work if you import "models" like this: 如果您像这样导入“模型”,它应该可以工作:

from cms_fragments import models

But it will be better if you post the piece of code where you use this "models" package, because i'm just guessing how did you use it. 但是,如果将代码段放在使用“模型”包的位置,那会更好,因为我只是在猜测您是如何使用它的。 Reading the error you got, it seems to be that you are trying to reference "models" module like this: 阅读您收到的错误,似乎是您正在尝试像这样引用“模型”模块:

models.some_thing_inside_models...

but as you import like this: 但是当您像这样导入时:

import cms_fragments.models

you must reference it this way: 您必须以这种方式引用它:

cms_fragments.models.some_thing_inside_models...

Here is some documentation that may help you and that explains well how to work with your proyect directory tree. 这里有一些文档可以为您提供帮助,并且很好地解释了如何使用proyect目录树。

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

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