温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

django 模板文件路径设置

发布时间:2020-09-19 10:02:48 来源:网络 阅读:630 作者:AlunE 栏目:编程语言

首先在settings.py文件中配置:

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',

            ],

        },

    },

]

BACKEND:模板引擎类的python路径,内置的模板引擎分别有'django.template.backends.django.DjangoTemplates'和'django.template.backends.jinja2.Jinja2'

DIRS:模板引擎搜索模板的路径,如上,默认搜索project目录下的templates目录

APP_DIRS:告诉模板引擎是否搜索app目录下的templates目录。默认为true,即是默认搜索app目录下的templates目录

'DIRS': [os.path.join(BASE_DIR, 'templates')]  是指到  BASE_DIR/templates文件夹中去取模板

'DIRS': [os.path.join(BASE_DIR, 'app1/templates')] 是指到  BASE_DIR/app1/templates文件夹中去取模板

模板文件查找顺序

如果同时设置

'DIRS': [os.path.join(BASE_DIR, 'templates')],

'APP_DIRS': True,

并且同时存在

mysite\templates\polls\index.html

mysite\polls\templates\polls\index.html

则会访问 mysite\templates\polls\index.html 而不是 mysite\polls\templates\polls\index.html

模板文件的命名空间(其实质是模板文件的本地相对路径)的应用场景是,在每个APP下建立appname/templates/appname/,然后在该目录下再放模板文件(index.html)。然后在需要引用模板文件的地方,采用模板文件相对地址硬编码时,形式如下:appname/index.html.

例如在views.py中

def index(request):
     #return HttpResponse("Hello, world. You're at the polls index.")
     return render(request,'polls/index.html')

或者index.html中

<li><ahref="/polls/xxx.html">{{question.question_text}}</a></li>

这根URL命名空间不一样:URL命名空间是用于模板文件中对URL(所谓URL是浏览器访问时的网络地址)的反向引用,一般会使用模板标签{% url %}

例如在index.html中

{% url 'polls:detail' question.id %}"
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI