2013-10-21 21 views
1

這裏是我的文件夾結構(全部塗黑的只是名稱的項目,只是假設「的myproject」):的Django如何使用模板的網站的首頁

enter image description here

我想設置我的主頁,即http://mydomain.com/,作爲模板HTML。所以下面this SO post,我在myproject項目文件夾設置這是我的url.py

from django.conf.urls import patterns, include, url 
from django.views.generic import TemplateView 

from django.contrib import admin 
admin.autodiscover() 

urlpatterns = patterns('', 
    url(r'^$', TemplateView.as_view(template_name="index.html")), 
    url(r'^events/', include('events.urls', namespace='events')), 
    url(r'^admin/', include(admin.site.urls)), 
) 

但Django的一直嘗試追加此路徑事件的文件夾。從瀏覽器中DEBUG = True輸出表明它無法在

/home/ubuntu/django/myproject/events/templates/templates/myproject/index.html 

找到這個模板這當然不是我試圖指向。我該如何解決?

回答

0

Django會嘗試找到你已經在TEMPLATE_DIRS設置和templates文件夾中的每個應用程序指定不同的文件夾,如果TEMPLATE_LOADERS設置有在Loading Templates

+0

是的,但我已經在應用程序模板文件夾中的其他模板名爲'的index.html '我不想被弄糊塗。有沒有辦法來防止呢? – lollercoaster

+0

@lollercoaster,我不會爲你工作,因爲Django會選擇一個以先到者爲準。所以它總是會選擇一個,即使你想要第二個。除非你通過名稱(使用_home.html_)或通過路徑(放在_templates/project/index.html_中,並且參考爲_project/index.html_) – Rohan

+0

ok,所以我仍然困惑於如何將它包含在我的' 'urls.py'中的urlpatterns',我可以使用inlclude函數嗎? – lollercoaster

0

'django.template.loaders.app_directories.Loader'

更多細節信息index.html模板您需要定義TEMPLATE_DIRS並嘗試使用如下絕對路徑:

PROJECT_PATH = os.path.realpath(os.path.dirname(__file__)) 
... 
TEMPLATE_DIRS = (
    os.path.join(PROJECT_PATH, 'templates'), 
) 
... 

如果您有一些應用和定位爲另一個文件夾模板的文件夾,然後你可以用這種方式定義TEMPLATE_DIRS:

PROJECT_PATH = os.path.realpath(os.path.dirname(__file__)) 
... 
TEMPLATE_DIRS = (
    os.path.join(PROJECT_PATH, 'events', 'templates'), 
    os.path.join(PROJECT_PATH, 'templates'), 
) 
... 

而且不要忘記更改您的視圖來渲染模板,像這樣:

... 
return render_to_response('events/index.html',{},context_instance=RequestContext(request)) 
... 

編輯:

,改變你的項目的網址是這樣的:

from events import urls 
... 

urlpatterns = patterns('', 
    ... 
    url(r'^events/', include('events.urls', namespace='events')), 
    ... 
) 
+0

好的。那麼我在我的項目級別urls.py中放入了什麼? – lollercoaster

0

最簡單的解決方案是將單個模板目錄與應用程序設置在同一級別。
例如:

/home/ubuntu/django/myproject/templates/events
/home/ubuntu/django/myproject/templates/some_other_app

另外,請檢查您的設置文件TEMPLATE_DIRS,這裏是工作示例:

from os.path import abspath, basename, dirname, join, normpath 

DJANGO_ROOT = dirname(dirname(abspath(__file__))) 

SITE_ROOT = dirname(DJANGO_ROOT) 

TEMPLATE_DIRS = (
    normpath(join(SITE_ROOT, 'templates')), 
) 
+0

如果我在應用程序文件夾中有其他模板目錄,我如何確保具有相同名稱的不同模板不會感到困惑?以及我在「urls.py」文件中放入了什麼? – lollercoaster

相關問題