Django 修改 pip 安装应用的模板
我想知道如何正确地覆盖通过pip安装的应用程序的模板。我的例子是关于django-notifications这个应用。它的结构如下:
notifications
|---- __init__.py
|---- templates
|---- notifications
|---- list.html
|---- notice.html
我在我的应用中复制了这个结构,并相应地修改了.html文件。但是现在我遇到了一个错误:ImportError: cannot import name notify
,这个错误发生在我从另一个应用(profile)中的视图里调用from notifications import notify
的时候。
如果不覆盖模板,我就不会遇到错误。我漏掉了什么吗?我需要在settings.py中添加什么吗?
(我已经完全按照包里的README.md安装说明进行了操作,并且在不覆盖模板的情况下它运行得很好)
追踪信息
File "/projectpath/project/urls.py", line 13, in <module>
url(r'^profile/', include('profile.urls')),
File "/home/user/.virtualenvs/project/local/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 26, in include
urlconf_module = import_module(urlconf_module)
File "/home/user/.virtualenvs/project/local/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module
__import__(name)
File "/projectpath/profile/urls.py", line 2, in <module>
from profile import views
File "/projectpath/profile/views.py", line 17, in <module>
from notifications import notify
ImportError: cannot import name notify
视图
from notifications import notify
def edit(request):
...
notify.send(request.user, recipient=request.user, verb='you reached level 10')
设置
# Project directory root assuming: yunite.settings.base
PROJECT_DIR = Path(__file__).ancestor(3)
#ROOT_PATH = os.path.dirname(__file__)
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.request",
"django.contrib.auth.context_processors.auth",
)
# Directory to find templates
TEMPLATE_DIRS = (
PROJECT_DIR.child("templates"),
)
INSTALLED_APPS = (
...
'notifications',
)
2 个回答
0
抱歉打扰你了:你有没有把“notifications”这个应用添加到INSTALLED_APPS里?听起来像是你重写的模板只是让导入错误变得明显了。
3
在Django中,覆盖一个模板其实很简单。首先,在你的主应用目录下,必须有一个名为templates的文件夹(如果没有,就自己创建一个)。接着,在这个templates文件夹里再创建一个新文件夹,名字可以叫(notifications),就是你这个例子中的名字。然后把模板文件(list.html
和notice.html
)复制到这个新文件夹里。
完成后,你就用自己的模板替换掉了应用里的模板。你可以随意修改它们。