django+mysql实现增删改查

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/')

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值