Django模板文件夹

Kev*_*gst 28 django django-templates django-urls

我正在尝试使用Django,并弄清楚如何设置urls.py,以及url如何工作.我已经在项目的根目录中配置了urls.py,以指向我的博客和管理员.但现在我想在我的家中添加一个页面,所以在localhost:8000.

所以我已经将以下代码添加到项目根目录中的urls.py:

from django.views.generic.simple import direct_to_template

urlpatterns = patterns('',
    (r"^$", direct_to_template, {"template": "base.html"}),
)
Run Code Online (Sandbox Code Playgroud)

问题是它在blog/templates /中搜索模板而不是我的根目录中的模板文件夹.其中包含base.html

完整的urls.py:

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

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()


urlpatterns = patterns('',
    (r"^$", direct_to_template, {"template": "base.html"}),
    url(r'^blog/', include('hellodjango.blog.urls')),
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
    (r'^tinymce/', include('tinymce.urls')),
)
Run Code Online (Sandbox Code Playgroud)

编辑:添加完整的urls.py :)

我忽略了什么吗?

Nge*_*tor 58

你装TEMPLATE_DIRS进去了settings.py吗?检查并确保使用绝对路径正确设置.这是我确保正确设置的方式:

settings.py

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(PROJECT_ROOT, 'templates').replace('\\','/'),
)

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)
Run Code Online (Sandbox Code Playgroud)

这样,templates我的项目根目录中有一个用于非应用程序模板的templates/appname文件夹,每个应用程序在应用程序内部都有一个文件夹.

如果要使用根模板文件夹中的模板,只需给出模板的名称,'base.html'如果要使用应用程序模板,则使用'appname/base.html'

文件夹结构:

project/
  appname/
    templates/ 
      appname/  <-- another folder with app name so 'appname/base.html' is from here
        base.html
    views.py
    ...

  templates/    <-- root template folder so 'base.html' is from here
    base.html

  settings.py
  views.py
  ...
Run Code Online (Sandbox Code Playgroud)

  • 这很好,对于django 1.9你想要更新的变量是位于"TEMPLATES ="中的"DIRS",并且由于默认项目根目录是BASE_DIR,它在TEMPLATES dict中应该如下所示:'DIRS':[os.path. join(BASE_DIR,'templates').replace('\\','/'),], (7认同)