2014-12-08 68 views
1

我如何從其他應用TemplateDoesNotExist。加載靜態文件和模板Django項目結構

這裏產生的模板有點糊塗是我的項目結構的圖片:

enter image description here

我得到這個錯誤:

TemplateDoesNotExist at/
home.html 

家/ views.py:

class HomeView(generic.TemplateView): 
    template_name = "home.html" 

Settings.py

STATIC_URL = '/static/' 
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"), 
    os.path.join(BASE_DIR, "home/static/home/js"), 
    os.path.join(BASE_DIR, "home/static/home/images"), 
    os.path.join(BASE_DIR, "home/static/home/css"), 
) 


TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates'), 
) 

項目的/ home/urls.py:

from django.conf.urls import patterns, url 

from home.views import HomeView 

urlpatterns = patterns('', 
    url(r'^$', HomeView.as_view(), name="home"), 
) 

項目/ urls.py

from django.conf.urls import patterns, include, url 
from django.contrib import admin 

urlpatterns = patterns('', 
    url(r'^admin/', include(admin.site.urls)), 
    url(r'', include("home.urls", namespace="home")), 

) 

項目/模板/家庭/ index.html的

<!DOCTYPE html> 
<html> 
<head lang="en"> 
    ... 
    <!-- Fonts --> 
    <link href='http://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'> 
    <!-- Custom CSS --> 
    <link href="{{ STATIC_URL }}boothie.css" rel="stylesheet"> 
    <!-- Custom JS--> 
    <script src="{{ STATIC_URL }}boothie.js"></script> 

    <title>Boothie</title> 
</head> 
<body> 
<div class="container"> 
    ... 
</div> 
</head> 
    {% block content %}{% endblock %} 
</body> 
</html> 

項目的/ home /模板/家/ home.html的:

{% extends index.html %} 

{% block content %} 
    ... 
    <script src="{{ STATIC_URL }}js/jquery.easing.1.3.js"></script> 
    <script src="{{ STATIC_URL }}js/boothie.js"></script> 
{% endblock %} 
+2

除非它有錯字,否則你的模板被稱爲'home/index.html'而不是'home.html'。 – 2014-12-08 04:40:49

+0

@BurhanKhalid我在我的'家'應用程序中有一個名爲home.html的文件。我想我的命名習慣很糟糕。在我的項目/模板中,有一個名爲home的目錄,其文件爲'index.html' – Liondancer 2014-12-08 04:45:38

+0

它位於'home/templates/home.html'中嗎? – 2014-12-08 04:49:08

回答

2

Django的停在它找到匹配請求的文件名的第一個模板,它會在應用程序文件夾中的templates目錄啓動。

如果它在這裏找不到它,它會上鍊,直到它搜索到TEMPLATE_DIRS設置中的所有位置,然後纔會打印出找不到模板的錯誤。它搜索模板的方式由TEMPLATE_LOADERS setting定義。

在您的項目佈局中,您想要的模板位於home應用程序的模板目錄中,並位於此目錄下的home目錄下。因此,模板路徑應該是home/home.html在您的視圖:

class HomeView(generic.TemplateView): 
    template_name = "home/home.html" 
+0

我做了一些修改,並添加了這個'TEMPLATE_DIRS =( os.path.join(BASE_DIR,'templates/index'), os.path。加入(BASE_DIR,'home/templates/home'), )'不知道這是否是好的做法,雖然=/ – Liondancer 2014-12-08 08:01:14

+0

不這樣做,默認情況下[應用程序中名爲'templates'的任何目錄都會自動搜索] (https://docs.djangoproject.com/en/1.7/ref/templates/api/#django.template.loaders.app_directories.Loader)。 – 2014-12-08 08:03:07

+0

會不會具體增加搜索時間? – Liondancer 2014-12-08 08:07:01

1

如果你的模板目錄是在項目的根,你必須將它添加到setitngs.py

如果它是一個應用程序的子目錄(即在settings.py中的INSTALLED_APPS中),那麼應用模板加載器(默認啓用)將加載它。

如果你的應用程序被稱爲home,那麼你將有模板目錄在主目錄內,而不是在模板下的home,因爲它位於模板目錄的home子目錄下。 py