阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

模板基本使用

217次阅读
没有评论

共计 1668 个字符,预计需要花费 5 分钟才能阅读完成。

一、概述

模板是 HTML 页面,可以根据传递的数据进行填充

二、模板存放目录

  1. 在应用目录下创建名为 templates 目录来存放模板
  2. 在工程目录下创建名为 templates 目录来存放模板

三、将 templates 标记为模板文件夹

模板基本使用

四、配置模板目录

  1. 目的

    让工程知道哪个目录是存放模板的

  2. 配置

    settings.py 文件中的 TEMPLATES 字段

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

五、定义模板 index.html

  1. 目的

作为主页使用

  1. 模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> 主页 </title>
</head>
<body>
<h1>Lucky is a ver good man</h1>
</body>
</html>
  1. 视图
def index(request):
# 返回主页
# 参数 1:request
# 参数 2:模板路径
return render(request, "index.html")
  1. 路由
path(r'', views.index)
  1. 测试网址

    http://127.0.0.1:8000

六、展示所有用户

  1. 视图
from App.models import User
def user(request):
# 返回所有班级信息
# 告诉模型获取所有班级信息
userData = User.objects.all()
# 将数据传递给模板,模板进行渲染,并返回页面
data = {"userData": userData
}
# 参数 3:字典类型,传递给模板的数据
return render(request, "user.html", data) # 参数 1 request 模板名称 参数 2 模板名称 参数 3 要传递的数据
  1. 路由
path(r'user/', views.user)
  1. 模板 user.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> 用户信息 </title>
<style>
table{border-collapse: collapse; /* 合并单元格 */
margin: auto; /* 居中 */
}
tr>td{width: 150px; /* 宽度 */
border:1px solid chartreuse; /* 边框 */
text-align: center; /* 文字水平居中 */
}
</style>
</head>
<body>
<table>
<caption><h2> 用户信息展示表 </h2></caption>
<tr>
<td>ID</td>
<td> 用户名 </td>
<td> 密码 </td>
<td> 性别 </td>
<td> 年龄 </td>
<td> 简介 </td>
</tr>
{% for user in userData %}
<tr>
<td>{{user.id}}</td>
<td>{{user.username}}</td>
<td>{{user.password}}</td>
<td>{{user.sex}}</td>
<td>{{user.age}}</td>
<td>{{user.info}}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
  1. 测试网址

    http://127.0.0.1:8000/user/

模板基本使用

正文完
星哥玩云-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2022-05-26发表,共计1668字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中