首先1: 新建项目userproject, 新建应用childName
2: 这是childName文件目录,templates文件夹放insert.html 与 show.html
3: insert.html 与 show.html
/**insert.html**/
用户登录1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Title信息展示
用户名 | 密码 |
---|
{% for line in people_list %}
{{line.username}}{{line.password}}{% endfor %}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
4: Setting配置等
找到INSTALLED_APPS,添加应用
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'childName' //添加
]1
2
3
4
5
6
7
8
9
找到MIDDLEWARE
注释 ‘django.middleware.csrf.CsrfViewMiddleware’
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]1
2
3
4
5
6
7
8
9
数据库配置
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'ENGINE': 'django.db.backends.mysql',
'NAME': 'monitorprogram',
'USER': 'root',
'PASSWORD': '123456',
'HOST': 'localhost',
'PORT': '3306'
}
}1
2
3
4
5
6
7
8
9
10
11
12
5: childName/views.py
from childName.models import message
from django.shortcuts import render
# Create your views here.
def insert(request):
if request.method == "POST":
message2 = message()
message2.username = request.POST.get("username")
message2.password = request.POST.get("password")
message2.save()
return render(request,'insert.html')
def list(request):
# message3 = message()
people_list = message.objects.all()
return render(request,"showuser.html",{"people_list": people_list})1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
6: 添加路径,userproject/urls.py
from django.contrib import admin
from django.urls import include,path
from childName import views
urlpatterns = [
path('admin/', admin.site.urls),
path('show/',views.list), //添加
path('insert/',views.insert) //添加
]1
2
3
4
5
6
7
8
9
7: 数据模型
from django.db import models
# Create your models here.
class message(models.Model):
username = models.CharField(max_length=20)
password = models.CharField(max_length=15)1
2
3
4
5
6
8: 执行迁移
数据模型有了,需要映射到数据库中,并实现指定表的创建
Django中数据模型和数据库的操作称为 迁移
在项目根目录下执行下面两行命令
python3 manage.py makemigrations
python3 manage.py migrate
执行成功后就会在数据库中创建相应的表
9:运行项目
python3 manage.py runserver
输入0987654321 1234点击提交,
查看mysql多出了这条记录
显示
ok!