逻辑:
- 在career\career\settings.py配置模板路径,系统自动去该路径查找HTML模板(项目名career)
- 定义页面函数使用render渲染关联到index模板,传入context参数
- 在模板html代码插入context,两个大括号引用{{ context }}
1. 配置模板路径
- 按需修改,以下代码有省略, ‘DIRS’: [os.path.join(BASE_DIR, ‘mbti/view’)],//添加模板路径
import os//添加os包,否则会报错
from pathlib import Path
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.staticfiles',
'mbti',
]
ROOT_URLCONF = 'career.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'mbti/templates')],//添加模板路径
'APP_DIRS': True,
},
},
]
2. 在mbti/views.py添加函数
from django.http import HttpResponse # 引入响应对象
from django.shortcuts import render, reverse, redirect
def index(request):
context = {}
context['hello'] = 'Hello World!'
return render(request, 'index.html', context)
3. 添加mbti/templates文件夹并创建index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MBTI</title>
</head>
<body>
<h3>{{ hello }}
</body>
</html>
4. 运行,打开浏览器测试
- python manage.py runserver 0.0.0.0:8001
- http://127.0.0.1:8001/mbti/index