1,在pycharm中创建django项目
2,新建app
python manage.py startapp web
3,新建static文件夹
4,修改settings
1. 在INSTALLED_APPS = []中添加web(app)
2. 注释# 'django.middleware.csrf.CsrfViewMiddleware',
3. 修改数据库配置
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':'ecstest_db',
'USER': 'root',
'PASSWORD': 'root',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
4. 连接static
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
4,安装mysqlclient
pip install mysqlclient
5,Navicat创建数据库ecstest_db
6,编写处理逻辑
1. 新建index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/css/pintuer.css">
</head>
<body>
<div class="container">
<div>
<a href="/add/"><p>插入(song 123)</p></a>
<a href="/remove/"><p>删除所有满足pwd=123456的记录</p></a>
<a href="/update/"><p>修改所有记录的pwd为123456</p></a>
</div>
<div>
<table class="table table-striped">
<thead>
<th>用户名</th>
<th>密码</th>
</thead>
<tbody>
{% for line in user_list %}
<tr>
<td>{{ line.name }}</td>
<td>{{ line.pwd }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</body>
</html>
2. 添加url
path('index/', views.index),
3. 添加处理函数
def index(request):
return render(request, "index.html", {})
7,创建models
from django.db import models
# Create your models here.
class UserInfo(models.Model):
name = models.CharField(max_length=16)
pwd = models.CharField(max_length=32)
8,构建数据库结构,执行操作到数据库
# 构建数据库结构
python manage.py makemigrations
# 执行操作到数据库
python manage.py migrate
9,增删改查
def index(request):
user_list = models.UserInfo.objects.all()
return render(request, "index.html", {"user_list": user_list})
def add(request):
models.UserInfo.objects.create(
name='song',
pwd='123',
)
return redirect('/index/')
def remove(request):
models.UserInfo.objects.filter(pwd='123456').delete()
return redirect('/index/')
def update(request):
models.UserInfo.objects.all().update(pwd='123456')
return redirect('/index/')