Python Web实战:Python+Django+MySQL实现基于Web版的增删改查

项目实战

1.创建项目(sms)

File->New Project->Django

稍等片刻,项目的目录结构如下图

项目创建后确认是否已安装Django和mysqlclient解释器,如何确认?file->Settings

如果没有请在Terminal终端输入以下命令完成安装

pip install django
pip install mysqlclient

领资料、源码,戳一戳

领资料、源码,戳一戳

如果在执行pip install 报错Read time out请设置延长下超时时间,默认15s,网络不好情况下很易超时

pip --default-timeout=180 install -U django
pip --default-timeout=180 install -U mysqlclient

参数-U是--upgrade简写,把安装的包升级到最新版本

2.创建应用(sims)

打开Pycharm的Terminal终端,输入以下命令创建sims应用

python manage.py startapp sims

应用创建后要在项目的settings.py文件里的INSTALLED_APPS下面添加smis完成应用注册

3.Django配置MySQL

在本地MySQL创建sms数据库,修改项目的settings连接信息由默认的sqlite修改为MySQL

DATABASES = {
     'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME':  'sms',
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST': '127.0.0.1',
        'PORT': 3306
     }
}

测试连接,依次点击Pycharm右上角的Database->±>Data Source->MySQL

下载连接驱动和配置数据库连接信息

点击Test Connection测试连接,连接通过点击OK出现如下的结构信息表示连接本地MySQL成功

4.数据模型创建(M)

在应用sims下models.py添加Student模型

class Student(models.Model):
    student_no = models.CharField(max_length=32, unique=True)
    student_name = models.CharField(max_length=32)

5.数据模型迁移

Terminal终端输入以下两条命令,其作用第一条生成文件记录模型的变化;第二条是将模型变化同步至数据库,我们可以在数据库生成对应的表结构。

python manage.py makemigrations sims

python manage.py migrate sims

生成数据表结构如下所示


领资料、源码,戳一戳

6.路由配置

本质可以理解请求路径url和处理方法的映射配置,首先在项目sms的urls.py文件中添加sims的路由配置

from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^sims/', include('sims.urls'))
]

然后在sims添加一个名为urls.py的文件,添加路由配置如下

# coding=utf-8
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index),
    url(r'^add/$', views.add),
    url(r'^edit/$', views.edit),
    url(r'^delete/$', views.delete)
]

7.处理函数(V)

在应用sims的视图层文件views.py添加对应学生信息增删改查的处理函数,这里我使用的原生SQL,便于深入理解其执行过程。后面有时间我会在github上添加Django框架提供的操作数据库方式。

import MySQLdb
from django.shortcuts import render, redirect


# Create your views here.
# 学生信息列表处理函数
def index(request):
    conn = MySQLdb.connect(host="localhost", user="root", passwd="123456", db="sms", charset='utf8')
    with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
        cursor.execute("SELECT id,student_no,student_name FROM sims_student")
        students = cursor.fetchall()
    return render(request, 'student/index.html', {'students': students})

# 学生信息新增处理函数
def add(request):
    if request.method == 'GET':
        return render(request, 'student/add.html')
    else:
        student_no = request.POST.get('student_no', '')
        student_name = request.POST.get('student_name', '')
        conn = MySQLdb.connect(host="localhost", user="root", passwd="123456", db="sms", charset='utf8')
        with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
            cursor.execute("INSERT INTO sims_student (student_no,student_name) "
                           "values (%s,%s)", [student_no, student_name])
            conn.commit()
        return redirect('../')

# 学生信息修改处理函数
def edit(request):
    if request.method == 'GET':
        id = request.GET.get("id")
        conn = MySQLdb.connect(host="localhost", user="root", passwd="123456", db="sms", charset='utf8')
        with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
            cursor.execute("SELECT id,student_no,student_name FROM sims_student where id =%s", [id])
            student = cursor.fetchone()
        return render(request, 'student/edit.html', {'student': student})
    else:
        id = request.POST.get("id")
        student_no = request.POST.get('student_no', '')
        student_name = request.POST.get('student_name', '')
        conn = MySQLdb.connect(host="localhost", user="root", passwd="123456", db="sms", charset='utf8')
        with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
            cursor.execute("UPDATE sims_student set student_no=%s,student_name=%s where id =%s",
                           [student_no, student_name, id])
            conn.commit()
        return redirect('../')

# 学生信息删除处理函数
def delete(request):
    id = request.GET.get("id")
    conn = MySQLdb.connect(host="localhost", user="root", passwd="123456", db="sms", charset='utf8')
    with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
        cursor.execute("DELETE FROM sims_student WHERE id =%s", [id])
        conn.commit()
    return  redirect('../')

8.模板页面(T)

  • 学生信息列表页

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>学生列表</title> </head> <body> 添加学生 {% for student in students %} {% endfor %}
    编号 姓名 学号 操作
    {{ forloop.counter }} {{ student.student_name }} {{ student.student_no }} 编辑 删除
    </body> </html>
  • 学生信息新增页

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>学生添加</title> <style> form { margin: 20px auto; width: 500px; border: 1px solid #ccc; padding: 20px } </style> </head> <body> <form method="post" action="../add/"> {% csrf_token %}
    姓名
    学号
    </form> </body> </html>
  • 学生信息编辑页

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>学生编辑</title> <style> form { margin: 20px auto; width: 500px; border: 1px solid #ccc; padding: 20px } </style> </head> <body> <form method="post" action="../edit/"> {% csrf_token %}
    姓名
    学号
    </form> </body> </html>

9.启动web服务测试

Terminal终端输入以下命令启动web服务

python manage.py runserver

![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pLmxvbGkubmV0LzIwMjAvMDUvMTAvTTRlZ242NWsyTmhPekxWLnBuZw?x-oss-process=image/format,

#png#pic_cente
领资料、源码,戳一戳

相关推荐
DisonTangor几秒前
Mozilla Firefox正在尝试集成ChatGPT等帮助用户总结或改写网页内容
前端·chatgpt·firefox
蓝天扶光16 分钟前
小白学python(第四天)顺序与分支篇
python
立秋678919 分钟前
使用Python绘制极坐标图
开发语言·python
信息科技云课堂31 分钟前
在 Python 中将字典内容保存到 Excel 文件
开发语言·python·excel
文 丰32 分钟前
python基础_类
开发语言·python
用哲学编程35 分钟前
每日一题——Python实现PAT乙级1090 危险品装箱(举一反三+思想解读+逐步优化)4千字好文
开发语言·python·算法·职场和发展
中科院提名者44 分钟前
mybatisplus新增数据时生成的雪花id太长前端接收不准确怎么办?
java·前端
无语听梧桐_April1 小时前
vue3中使用Antv G6渲染树形结构并支持节点增删改
前端·vue.js·数据可视化
易迟1 小时前
来自工业界的知识库 RAG 服务(五),模块化知识库 GoMate 实现方案详解
人工智能·python·gpt
亦黑迷失1 小时前
水印的攻防战
前端·javascript·canvas