Django 用于定位和加载模板的路径是什么? [英] What is the path that Django uses for locating and loading templates?

查看:25
本文介绍了Django 用于定位和加载模板的路径是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Windows 上关注此教程7 环境.

I'm following this tutorial on a Windows 7 environment.

我的设置文件有这样的定义:

My settings file has this definition:

TEMPLATE_DIRS = (
    'C:/django-project/myapp/mytemplates/admin'
)

我从模板 admin/base_site.html 中获得了 base_template 来自 Django 本身源代码 (django/contrib/admin/templates) 进入 myapp 目录的 admin 子目录,按照教程的指示,但由于某种原因它似乎没有生效.

I got the base_template from the template admin/base_site.html from within the default Django admin template directory in the source code of Django itself (django/contrib/admin/templates) into an admin subdirectory of myapp directory as the tutorial instructed, but it doesn't seem to take affect for some reason.

有什么可能是什么问题的线索吗?

Any clue of what might be the problem?

推荐答案

我知道这不在 Django 教程中,对他们感到羞耻,但最好为路径变量设置相对路径.你可以这样设置:

I know this isn't in the Django tutorial, and shame on them, but it's better to set up relative paths for your path variables. You can set it up like so:

import os.path

PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))

...

MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media/')

TEMPLATE_DIRS = [
    os.path.join(PROJECT_PATH, 'templates/'),
]

这样你就可以移动你的 Django 项目,你的路径根将自动更新.这在您设置生产服务器时很有用.

This way you can move your Django project and your path roots will update automatically. This is useful when you're setting up your production server.

其次,您的 TEMPLATE_DIRS 路径存在可疑之处.它应该指向模板目录的根目录.此外,它也应该以 / 结尾.

Second, there's something suspect to your TEMPLATE_DIRS path. It should point to the root of your template directory. Also, it should also end in a trailing /.

我只是在这里猜测 .../admin/ 目录不是您的模板根目录.如果你仍然想写绝对路径,你应该去掉对管理模板目录的引用.

I'm just going to guess here that the .../admin/ directory is not your template root. If you still want to write absolute paths you should take out the reference to the admin template directory.

TEMPLATE_DIRS = [
    'C:/django-project/myapp/mytemplates/',
]

话虽如此,默认情况下模板加载器应设置为递归遍历您的应用目录以定位模板文件.

With that being said, the template loaders by default should be set up to recursively traverse into your app directories to locate template files.

TEMPLATE_LOADERS = [
    'django.template.loaders.filesystem.load_template_source',
    'django.template.loaders.app_directories.load_template_source',
    # 'django.template.loaders.eggs.load_template_source',
]

除非您特别想覆盖某些内容,否则您不需要复制管理模板.

You shouldn't need to copy over the admin templates unless if you specifically want to overwrite something.

如果您尚未运行同步数据库,则必须运行它.如果您通过 runserver 托管 django,您还需要静态地为您的媒体文件提供服务.

You will have to run a syncdb if you haven't run it yet. You'll also need to statically server your media files if you're hosting django through runserver.

这篇关于Django 用于定位和加载模板的路径是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆