在django项目中放置模板的最佳位置是什么?

Vis*_*hal 82 django

在django项目中放置模板的最佳位置是什么?

dlr*_*ust 81

放置在<PROJECT>/<APP>/templates/<APP>/template.html特定于应用程序的模板中,以帮助使应用程序在其他地方重用.

对于我将它们放入的一般"全局"模板 <PROJECT>/templates/template.html

  • 第一个/ app/templates只是用他们的相关应用程序对模板进行分组.第二个应用程序是防止名称冲突.(据推测,你会指出TEMPLATE_DIRS指向这些目录中的每一个,但最后,Django将它们整合到一个巨大的目录中.)参见:https://docs.djangoproject.com/en/dev/ref/templates使用的子目录/ API /# (15认同)
  • 想知道`<PROJECT>/<APP>/templates/<APP>/template.html`中2` <APP>的原因? (11认同)
  • 这个答案很古老,但不知何故我到了这里。作为记录,`TEMPLATE_DIRS` 现在已弃用 - 您应该将 `DIRS=[os.path.join(BASE_DIR, "templates")]` 添加到 `TEMPLATES` - 请参阅 /sf/ask/2080759271/ /django-cant-find-template-directory (5认同)
  • 为了工作(django 1.6),我不得不为文件系统模板加载器添加指令:`TEMPLATE_DIRS =(os.path.join(BASE_DIR,"templates"))` (3认同)

Dom*_*ger 49

从Django书中,第4章:

如果您无法想到放置模板的明显位置,我们建议您在Django项目中创建一个模板目录(例如,在第2章中创建的mysite目录中,如果您一直关注我们的示例).

这正是我的工作,对我来说非常有用.

我的目录结构如下所示:

/media我所有的CSS/JS /图像等
/templates
/projectname的主项目代码模板(即Python代码)

  • 当您将模板放入 /templates 中时,有没有办法告诉模板加载器加载它,而无需在 TEMPLATE_DIRS 中指定 /template 的完整路径来使用 django.template.loaders.filesystem.Loader 加载?使用相对路径来做到这一点会很棒,并且在 1.4 下我的加载程序不会在 &lt;project&gt;/templates 下查找 (2认同)

小智 9

跟随多米尼克和dlrust,

我们使用setuptools源代码分发(sdist)来打包我们的django项目和应用程序,以便在我们的不同环境中进行部署.

我们发现模板和静态文件需要位于django应用程序目录下,以便它们可以通过setuptools打包.

例如,我们的模板和静态路径如下所示:

PROJECT/APP/templates/APP/template.html
PROJECT/APP/static/APP/my.js
Run Code Online (Sandbox Code Playgroud)

为此,需要修改MANIFEST.in(请参阅http://docs.python.org/distutils/sourcedist.html#the-manifest-in-template)

MANIFEST.in的一个例子:

include setup.py
recursive-include PROJECT *.txt *.html *.js
recursive-include PROJECT *.css *.js *.png *.gif *.bmp *.ico *.jpg *.jpeg
Run Code Online (Sandbox Code Playgroud)

此外,您需要在django设置文件中确认app_directories加载程序位于TEMPLATE_LOADERS中.我认为它在django 1.4中默认存在.

django设置模板加载器的示例:

# 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',
)
Run Code Online (Sandbox Code Playgroud)

万一你想知道为什么我们使用sdists而不是仅仅处理rsync文件; 它是我们配置管理工作流程的一部分,我们将单个构建tarball与PIP一起部署到测试,验收和生产环境中.


小智 7

DJANGO 1.11

添加manage.py所在的模板文件夹,这是您的基本目录.在settings.py中更改模板的DIRS,如下所示

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

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, 'templates')],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},
Run Code Online (Sandbox Code Playgroud)

]

现在使用代码使用模板,

def home(request):
    return render(request,"index.html",{})
Run Code Online (Sandbox Code Playgroud)

在views.py中.这对于django 1.11来说完全没问题