一、定义模型
(1) 创建模型类,必须要继承自 models.Model
python
from django.db import models
# Create your models here.
#设计数据库
#创建模型
class UserModel(models.Model):
name=models.CharField(max_length=30) #对应于SQL name varchar(30)
age=models.PositiveIntegerField() #非负数
#数据迁移
(2) 数据迁移,刷新数据库,查找到user_usermodel表,并打开,添加数据

二、Admin 后台管理
(1)编写admin.py文件
python
from django.contrib import admin
from user.models import * #导入模型包
# Register your models here.
#后台管理系统使用
#1.注册对应的模型
admin.site.register(UserModel)
#2.创建超级管理员的账号和密码
# 在终端写:python manage.py createsuperuser
#3.根据路由urls.py中添加页面路由

(2)在终端 创建超级管理员的账号和密码 amdin/admin

(3) 打开数据库auth_user表查看
(4)启动项目,访问页面http://127.0.0.1:8000/admin,进行登录

(5)登录成功后,查看到用户模型User models

(6)添加这个表的数据

(7)添加成功后页面

(8) 可以修改或删除

(9)查看数据库表的数据是否同步

三、展示数据列表
(1)在views.py文件中编写视图函数
python
from django.shortcuts import render
# Create your views here.
#视图函数
from user.models import UserModel
def index(request):
#获取所有的数据
users=UserModel.objects.all()
return render(request,template_name='index.html',context={'users':users})
(2)模板文件(html文件)
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>主页</title>
<style type="text/css">
li{
list-style: none;
line-height: 30px;
}
</style>
</head>
<body>
<div>
<h1>显示学生信息</h1>
<ul>
{% for user in users %}
<li>{{ user.name }} {{ user.age }}</li>
{% endfor %}
</ul>
</div>
</body>
</html>

(3)在子应用user配置urs.py文件
(4)主路由配置urls.py

效果: http://127.0.0.1:8000/user/index/
