django模板路径设置

django模板路径默认设置

在项目的同名文件夹下找到settings.py中settings.py中默认参数如下

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]
1. 根目录添加templates

其中DIRS表示根目录中模板的查找位置,APP_DIRS表示各APP中模板的查找位置

如果有不属于任何APP的html页面,我们可以在DIRS中添加模板位置为根目录,如下

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

那么就可以在此文件夹中添加html文件,然后在view中访问了

2. APP内添加templates

如果在APP内创建templates文件,添加html时, 在views中可以直接访问,不需要做其他额外操作

def orgs(request):
  orgs = org.objects.all()
  return render(request, "./show-org.html", locals())
  # html的位置写成  "/show-org.html" 会报错

如果html文件是放在了templates目录下的子目录,比如web子目录

def orgs(request):
  orgs = org.objects.all()
  return render(request, "web/show-org.html", locals())
posted @ 2022-12-01 15:11  坚强的小蚂蚁  阅读(634)  评论(0编辑  收藏  举报