Python3:初次使用Django创建web应用并实现增删改查(使用sqlite3作为数据库)

1.前言

使用Django开发web应用的时候需要,先使用pip安装才可以使用

2.关于当前Django框架的结构理解

在这里插入图片描述
1.setting.py是web应用的基本设置,其中定义了使用的数据库以及认证模块(非常重要)

2.urls.py就是用于管理当前的访问的url对应的调用的模块所使用的方法
在这里插入图片描述
在使用当前的模块方法之前需要导入当前的模块:使用web路径为.

3.templates文件就是用于存放当前所需要的静态的html页面的

3.sqlite3数据展示

在这里插入图片描述

4.功能的基本展示

用户信息的列表展示
在这里插入图片描述
添加用户
在这里插入图片描述
修改用户
在这里插入图片描述
删除操作使用a标签实现

5.操作中遇到的问题

1.不能使用post请求的问题:解决在当前的form标签的下一行添加 {% csrf_token %}
在这里插入图片描述
2.重定向页面的问题:需要使用/结尾就可以了
在这里插入图片描述

6.web的基本操作

1.转发需要使用:from django.shortcuts import render

render(request, “updateUser.html”, model)
这里的第二个参数是html页面,model就是一个简单的dict字典数据

2.重定向需要使用:from django.shortcuts import redirect

redirect(to="…/users/") # 这里的user后面一定要加斜杠(/)

7.创建需要的user.py组件

class User:
    def __init__(self, _id=None, _username=None, _password=None):
        self.id = _id
        self.username = _username
        self.password = _password
        

8.创建usersController.py组件

from django.shortcuts import render
from django.shortcuts import redirect
import sqlite3
from .user import User  # 如果是web环境需要通过from . 的方法是导入本地的模块类


def to_add_user_page(request):
    print("访问当前的添加用户页面")
    return render(request, "adduser.html")


# 重定向需要使用当前的redirect模块来实现定向操作、
def add_user(request):
    request.encoding = 'utf-8'
    if 'username' in request.POST and request.POST['username']:
        username = request.POST["username"]
    if 'password' in request.POST and request.POST['password']:
        password = request.POST["password"]
    if username and password:
        print("当前添加的数据为:username:{0},password:{1}".format(username, password))
        try:
            conn = sqlite3.connect("db.sqlite3")
            cursor = conn.cursor()
            cursor.execute("insert into users(username,password) values(?,?)", (username, password))
            conn.commit()
        except Exception as e:
            print("出现了错误:{0}".format(e))
        finally:
            close_database(cursor, conn)
        print("执行添加用户信息操作")
    else:
        print("没有数据如何添加用户信息")
    return redirect(to="../users/")


def to_update_user_page(request):
    model = {}
    if "id" in request.GET and request.GET["id"]:
        id = request.GET["id"]
    if id:
        try:
            conn = sqlite3.connect("db.sqlite3")
            cursor = conn.cursor()
            cursor.execute("select * from users where id=?", id)
            user_data = cursor.fetchone()
            model["updateUser"] = convert_to_user(user_data)
        except Exception as e:
            print("出现了错误:{0}".format(e))
        finally:
            close_database(cursor, conn)
    else:
        print("没有id如何执行查找操作!")
    return render(request, "updateUser.html", model)


# 通过当前的id编号更新用户
def update_user(request):
    if "id" in request.POST and request.POST['id']:
        id = request.POST["id"]
        username = request.POST["username"]
        password = request.POST["password"]
        try:
            conn = sqlite3.connect("db.sqlite3")
            cursor = conn.cursor()
            cursor.execute("update users set username=? ,password=? where id=?", (username, password,
                                                                                  id))
            conn.commit()
        except Exception as e:
            print("出现了错误:{0}".format(e))
        finally:
            close_database(cursor, conn)
    else:
        print("没有id如何更新?")
    return redirect(to="../users/")


# 删除数据操作
def del_user_by_id(request):
    if "id" in request.GET and request.GET['id']:
        id = request.GET["id"]
        try:
            conn = sqlite3.connect("db.sqlite3")
            cursor = conn.cursor()
            cursor.execute("delete from users where id=?", id)
            conn.commit()
        except Exception as e:
            print("出现了错误:{0}".format(e))
        finally:
            close_database(cursor, conn)
    else:
        print("没有id如何删除?")
    return redirect(to="../users/")


# 用于向当前的数据库中查询所有的数据
def user_list(request):
    print("访问当前的所有的用户信息数据")
    try:
        conn = sqlite3.connect("db.sqlite3")
        cursor = conn.cursor()
        cursor.execute("select * from users")
        users = [convert_to_user(item) for item in cursor.fetchall()]
        # 开始添加视图数据
        model = {"users": users}
        return render(request, "index.html", model)
    except Exception as e:
        print("出现异常:{0}".format(e))
    finally:
        close_database(cursor, conn)


# 用于将当前的数据库的数据转换称对应的用户信息对象
def convert_to_user(user_data=[]):
    return User(user_data[0], user_data[1], user_data[2])


# 关闭数据库连接和关闭游标的操作
def close_database(cursor, conn):
    if cursor in locals():
        cursor.close()
    if conn in locals():
        conn.close()

9.其他的html页面

当前的页面放在templates文件中
1.index.html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用于管理界面</title>
</head>
<body>
<table border="1">
    <tr>
        <td colspan="4"><h1>欢迎使用用户管理系统</h1></td>
    </tr>
    <tr>
        <td colspan="4"><a href="../toAddUserPage/">添加用户</a></td>
    </tr>
    <tr>
        <th>用户编号</th>
        <th>用户名</th>
        <th>用户密码</th>
        <th>操作</th>
    </tr>
    {% for user in users %}
        <tr>
            <td>{{ user.id }}</td>
            <td>{{ user.username }}</td>
            <td>{{ user.password }}</td>
            <td><a href="../toUpdateUserPage?id={{ user.id }}">修改</a>
                <a href="../delUser?id={{ user.id }}">刪除</a>
            </td>
        </tr>
    {% endfor %}
</table>
</body>
</html>

2.当前的adduser.html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加用户界面</title>
</head>
<body>

<form action="../addUser/" method="post">
    {% csrf_token %}
    <table border="1">
        <tr>
            <td colspan="2"><h1>添加用户操作</h1></td>
        </tr>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username"/></td>
        </tr>
        <tr>
            <td>用户密码:</td>
            <td><input type="text" name="password"/></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="保存"/>
                <input type="button" value="返回" onclick="history.back()"/>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

3.当前的updateUser.html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加用户界面</title>
</head>
<body>

<form action="../updateUser/" method="post">
    {% csrf_token %}
    <table border="1">
        <tr>
            <td colspan="2"><h1>修改用户操作</h1></td>
        </tr>
        <input type="hidden" name="id" value="{{ updateUser.id }}"/>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username" value="{{ updateUser.username }}"/></td>
        </tr>
        <tr>
            <td>用户密码:</td>
            <td><input type="text" name="password" value="{{ updateUser.password }}"/></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="保存"/>
                <input type="button" value="返回" onclick="history.back()"/>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

10.结果

测试成功,所有的跳转页面和添加修改删除查询数据都成功!这里不显示页面了

11.总结

1.在使用当前的Django中需要注意它的表达式{%%}

2.在重定向的时候一定要在路径的后面加斜杠

3.访问数据需要从当前的request.GET和request.POST中去取,这里数据集就是一个dict字典,需要先判断在取出数据

4.需要使用{{参数}}的方式显示dict中的数据迭代需要使用{%for %}{%endfor%}

以上纯属个人见解,如有问题请联系本人!

发布了215 篇原创文章 · 获赞 39 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_45492007/article/details/103239328