Python入门 页面和传参

逻辑:

  1. 在career\career\settings.py配置模板路径,系统自动去该路径查找HTML模板(项目名career)
  2. 定义页面函数使用render渲染关联到index模板,传入context参数
  3. 在模板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. 运行,打开浏览器测试

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值