Django的model模型(增删改查)2

1. 创建一个模版目录
mkdir -p ./templates/myapp

2.执行数据库连接配置,网站配置
vim /myweb/settings.py

1)添加应用名字
INSTALLED_APPS 添加app名字
结果如下

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
]

  

2)添加模板路径
TEMPLATES -->DIRS-->templates
结果如下

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

  

3)数据库换成mysql
结果如下

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

  

3.开发流程
1)在models.py中定义模型类,要求继承models.Model
vim myapp/models.py

内容如下

from django.db import models

# Create your models here.
from datetime import datetime
class Users(models.Model):  # model类里面有增删改查操作
    # id = models.AutoField(primary_key=True) # 主键可省略不写
    name = models.CharField(max_length=32)
    age = models.IntegerField(default=20)
    phone = models.CharField(max_length=16)
    addtime = models.DateTimeField(default=datetime.now)

#class Meta:
#   db_table = "myapp_users"  # 指定表名,也可不写,默认是app名+下划线+表名

  

2)生成迁移文件(自动创建表,自动创建INSTALLED_APPS下的所有app表)
python3 manage.py makemigrations

3)执行迁移
python3 manage.py migrate

4)配置首页动作(添加动作)
内容如下

from django.shortcuts import render
from django.http import HttpResponse
from myapp.models import Users
def index(request):
    #执行Model操作
    # 添加
    ob = Users
    ob.name = '张三'
    ob.age = 20
    ob.phone = '1234567890'
    ob.save
    return  HttpResponse("Hello World!")


 

执行python3 manage.py runserver 0:8899后添加内容到数据库


 

5)配置首页动作(删除动作)
内容换成如下

from django.shortcuts import render
from django.http import HttpResponse
from myapp.models import Users
def index(request):
    mod = Users.objects
    user = mod.get(id=1)
    user.delete()
    return  HttpResponse("Hello World!")

  

执行python3 manage.py runserver 0:8899后删除内容

 

6)配置首页动作(修改动作)
内容换成如下

from django.shortcuts import render
from django.http import HttpResponse
from myapp.models import Users
def index(request):
    mod = Users.objects
    ob = mod.get(id=1)
    ob.name = '李四'
    ob.age = 11
    ob.phone = '0123456789'
    ob.save
    return  HttpResponse("Hello World!")

  

执行python3 manage.py runserver 0:8899后删除内容

 

 

7)其他功能参考官方文档
https://www.djangoproject.com/
https://docs.djangoproject.com/zh-hans/5.2/

 

8)配置首页动作(查询动作)

获取所有数据
内容换成如下

from django.shortcuts import render
from django.http import HttpResponse
from myapp.models import Users
def index(request):
    mod = Users.objects
    ulist = mod.all()
    for u in ulist:
        print(u.id,u.name,u.age,u.phone)
    return  HttpResponse("Hello World!")


#获取过滤后的所有数据
内容换成如下
from django.shortcuts import render
from django.http import HttpResponse
from myapp.models import Users
def index(request):
    mod = Users.objects
    ulist = mod.filter(age_gt=20)   #年龄大于20的;age_gte大于等于
    for u in ulist:
        print(u.id,u.name,u.age,u.phone)
    return  HttpResponse("Hello World!")

  

 

4.整体增删改查
1)配置url路由
vim myapp/urls.py
内容如下

from django.urls import path
from . import views
urlpatterns = [
        path('', views.index, name='index'),
        #配置User表
        path('users', views.indexUsers, name='indexusers'),
        path('users/add', views.addUsers, name='addusers'),
        path('users/insert', views.insertUsers, name='insertusers'),
        path('users/del/<int:uid>', views.delUsers, name='delusers'),
        path('users/edit/<int:uid>', views.editUsers, name='editusers'),
        path('users/update', views.updateUsers, name='updateusers'),
        ]

  

 

2)编写视图函数(myapp/views.py)

from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from myapp.models import Users
def index(request):
    return  HttpResponse("Hello World! <br/> <a href='/myapp/users'>用户信息管理</a>")

def indexUsers(request):
   ulist = Users.objects.all()
   context = {"userslist":ulist}
   return render(request,"myapp/users/index.html",context) # 加载模板
def addUsers(request):
   return render(request,"myapp/users/add.html") 
def insertUsers(request):
    try:
        ob = Users()
        ob.name = request.POST["name"]
        ob.age = request.POST["age"]
        ob.phone = request.POST["phone"]
        ob.save()
        context = {"info":"添加成功!"}
    except:
        context = {"info":"添加失败!"}
    return render(request,"myapp/users/info.html",context) 
def delUsers(request,uid=0):
    try:
        ob = Users.objects.get(id=uid)
        ob.delete()
        context = {"info":"删除成功!"}
    except:
        context = {"info":"删除失败!"}
    return render(request,"myapp/users/info.html",context) 
def editUsers(request,uid=0):
    try:
        ob = Users.objects.get(id=uid)
        context = {"user":ob}
        return render(request,"myapp/users/edit.html",context) 
    except:
        context = {"info":"没有找到要编辑数据"}
        return render(request,"myapp/users/info.html",context) 
def updateUsers(request):
    try:
        uid = request.POST["id"]
        ob = Users.objects.get(id=uid)
        ob.name = request.POST["name"]
        ob.age = request.POST["age"]
        ob.phone = request.POST["phone"]
        ob.save()
        context = {"info":"修改成功!"}
    except:
        context = {"info":"修改失败!"}
    return render(request,"myapp/users/info.html",context) 

  

3)编写users模版
mkdir -p templates/myapp/users
①index模版(templates/myapp/users/index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>users</title>
</head>
    <center>
        <h1>用户信息管理</h1>
        <a href="{% url 'indexusers' %}"> 浏览信息 </a>
        <a href="{% url 'addusers' %}"> 添加信息 </a>
        <hr />
        <h3>浏览用户信息</h3>
        <table width="800" border="1">
            <tr>
                <td>ID号</td>
                <td>姓名</td>
                <td>年龄</td>
                <td>电话</td>
                <td>添加时间</td>
                <td>操作</td>
            </tr>
            {% for user in userslist %}
                <tr>
                    <td>{{ user.id }}</td>
                    <td>{{ user.name }}</td>
                    <td>{{ user.age }}</td>
                    <td>{{ user.phone }}</td>
                    <td>{{ user.addtime }}</td>
                    <td>
                        <a href="{% url 'editusers' user.id %}">编辑</a>
                        <a href="{% url 'delusers' user.id %}">删除</a>
                    </td>
                </tr>
            {% endfor %}
        </table>
    </center>
<body>

</body>
</html>

  

②add模版(templates/myapp/users/add.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>users</title>
</head>
    <center>
        <h1>用户信息管理</h1>
        <a href="{% url 'indexusers' %}"> 浏览信息 </a>
        <a href="{% url 'addusers' %}"> 添加信息 </a>
        <hr />
        <h3>添加用户信息</h3>
        <form action="{% url 'insertusers' %}" method="post">
            {% csrf_token %}
            <table width="280" border="0">
                <tr>
                    <td>姓名:</td>
                    <td><input type="text" name="name"></td>
                </tr>
                <tr>
                    <td>年龄:</td>
                    <td><input type="text" name="age"></td>
                </tr>
                <tr>
                    <td>电话:</td>
                    <td><input type="text" name="phone"></td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <input type="submit" value="添加"/>
                        <input type="reset" value="重置"/>
                    </td>
                </tr>
            </table>
        </form>
    </center>
<body>

</body>
</html>

  

③info模版(templates/myapp/users/info.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>users</title>
</head>
    <center>
        <h1>用户信息管理</h1>
        <a href="{% url 'indexusers' %}"> 浏览信息 </a>
        <a href="{% url 'addusers' %}"> 添加信息 </a>
        <hr />
        <h3>操作提示信息</h3>
        <h4>{{ info }}</h4>

    </center>
<body>

</body>
</html>

  

④edit模版(templates/myapp/users/edit.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>users</title>
</head>
    <center>
        <h1>用户信息管理</h1>
        <a href="{% url 'indexusers' %}"> 浏览信息 </a>
        <a href="{% url 'addusers' %}"> 添加信息 </a>
        <hr />
        <h3>编辑用户信息</h3>
        <form action="{% url 'updateusers' %}" method="post">
            {% csrf_token %}
            <input type="hidden" name="id" value="{{ user.id }}">
            <table width="280" border="0">
                <tr>
                    <td>姓名:</td>
                    <td><input type="text" name="name" value="{{ user.name }}"></td>
                </tr>
                <tr>
                    <td>年龄:</td>
                    <td><input type="text" name="age" value="{{ user.age }}"></td>
                </tr>
                <tr>
                    <td>电话:</td>
                    <td><input type="text" name="phone" value="{{ user.phone }}"></td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <input type="submit" value="修改"/>
                        <input type="reset" value="重置"/>
                    </td>
                </tr>
            </table>
        </form>
    </center>
<body>

</body>
</html>

  

⑤删除时xss弹窗提醒下(修改index.html如下)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>users</title>
</head>
    <center>
        <h1>用户信息管理</h1>
        <a href="{% url 'indexusers' %}"> 浏览信息 </a>
        <a href="{% url 'addusers' %}"> 添加信息 </a>
        <hr />
        <h3>浏览用户信息</h3>
        <script>
            function doDel(uu){
                if(confirm("确定要删除吗?")){
                    window.location=uu;
                }
            }
        </script>
        <table width="800",border="1">
            <tr>
                <td>ID号</td>
                <td>姓名</td>
                <td>年龄</td>
                <td>电话</td>
                <td>添加时间</td>
                <td>操作</td>
            </tr>
            {% for user in userslist %}
                <tr>
                    <td>{{ user.id }}</td>
                    <td>{{ user.name }}</td>
                    <td>{{ user.age }}</td>
                    <td>{{ user.phone }}</td>
                    <td>{{ user.addtime }}</td>
                    <td>
                        <a href="{% url 'editusers' user.id %}">编辑</a>
                        <a href="javascript:doDel('{% url 'delusers' user.id %}')">删除</a>
                    </td>
                </tr>
            {% endfor %}
        </table>
    </center>
<body>

</body>
</html>

  

 

posted @ 2025-04-20 22:17  铿锵有力自信且坚定  阅读(21)  评论(0)    收藏  举报