Django创建模板文件和定位当前py文件的路径方法

我们在创建模板文件时一般以对应的app名称来命名并创建一个文件夹。

这样做的好处是和同事一起开发或后期维护时能够快速的定位到相关模板文件

如:

项目文件夹

|——rango(app应用名称)

|——项目脚本文件夹

|——manage.py

|——templates

    |——rango(对应的app模板文件)

新建好模板文件夹之后我们还需要到项目脚本中settings.py中配置文件的相对路径(没有特殊要求就不要配置绝对路径)。

相对路径在settings中已经有一个变量(BASE_DIR)获取到了,我们只需要拼接即可

我们将变量命名为TEMPLATE_DIR(表示模板路径),用os.path.join来进行拼接。

①TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')

②配置TEMPLATE列表中的DIRS键值对  'DIRS': [TEMPLATE_DIR,],

【settings.py文件】

# ...省略...
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') # 重点

# ...省略...

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR,],  # 重点
        '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',
            ],
        },
    },
]

# ...省略...

【定位当前py文件的路径】

PS题外话:BASE_DIR是如何获取到相对路径的?

答:BASE_DIR是用 __file__ 来获取的,并且还使用了os.path.dirname来逐层过滤,os.path.dirname每执行一次就去掉一层目录;可以使用以下代码来测试就知道原理了。

print(__file__)
print(os.path.dirname(__file__))
print(os.path.dirname(os.path.dirname(__file__)))

# __file__是以当前py文件来定位路径的

# E:/GIT/Django_test/workspace/tango/project/settings.py 
# E:/GIT/Django_test/workspace/tango/project
# E:/GIT/Django_test/workspace/tango

可以看出:__file__ 是以当前py文件来定位路径的。

【新建html文件】

新建模板文件,并写入Django标签变量

<!DOCTYPE html>
<html>

	<head>
		<title>Rango</title>
	</head>
	
	<body>
		<h1>Rango says...</h1>
		<div>
			hey there partner! <br />
			<strong>{{ boldmessage }}</strong><br />
		</div>
		<div>
			<a href="/rango/about/">About</a><br />
		</div>
	</body>
</html>

【编写逻辑viws.py的函数】

# -*- coding:utf-8 -*-

from django.shortcuts import render
from django.http import HttpResponse



# Create your views here.

def index(request):
	# 我们构建了一个字典来传递给模板文件中的{{ boldmessage }}变量
	context_dict = {'boldmessage':"嗨!走走走,让我们一起来学Django!"}

	# 返回一个响应给客户端,'rango/index.html'是我们想使用的模板文件,context= 是返回的内容
	return render(request,'rango/index.html', context=context_dict)

def about(request):
	return HttpResponse('Rango says here is the about page!</br><a href="/rango/">Index url</a>')

最后重启一下Django服务器就可以看到效果。

猜你喜欢

转载自blog.csdn.net/qq_40134903/article/details/81273887