django增删改查

1.创建名为Stu的模型类

from django.db import models

# 增删改查练习
class Stu(models.Model):
    stu_name = models.CharField(max_length=10)
    stu_age = models.IntegerField(default=22)
    stu_sex = models.CharField(max_length=1)
    stu_phone = models.CharField(max_length=11)
    add_time = models.DateTimeField(auto_now_add=True)

    class Meta():
        db_table = 'student'

    def __str__(self):
        return self.stu_name

2.在项目名下生成并执行迁移文件:

  D:Django/mysite_02>python manage.py makemigrations

  D:Django/mysite_02>python manage.py migrate

3.相应模板templates下的html文件

  show.html用于显示添加过的信息

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>显示数据</title>
        <style type="text/css">
            td {text-align: center;}
        </style>
    </head>
    <body>
        <h1>学生信息名单</h1>
        <table border="1" cellspacing="0" width="1000px">
            <tr>
                <th>编号</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>性别</th>
                <th>电话</th>
                <th style=" 350px;">添加时间</th>
                <th>操作</th>
            </tr>
            {% for i in stu_info %}    
            <tr>
                <td>{{i.id}}</td>
                <td>{{i.stu_name}}</td>
                <td>{{i.stu_age}}</td>
                <td>{{i.stu_sex}}</td>
                <td>{{i.stu_phone}}</td>
                <td>{{i.add_time}}</td>
                <td>
                    <a href="{% url 'del_info' %}?sid={{i.id}}">删除</a>
                    <a href="{% url 'update_info' i.id %}">修改</a>                    
                </td>
             </tr>
            {% endfor %}
        </table>
        <a href="{% url 'add_info' %}">添加数据</a>
        
    </body>
</html>

  addition.html用于添加信息

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>添加数据</title>
    </head>
    <body>
        <form action="{% url 'save_info' %}" method="get" style="margin-top: 100px;margin-left: 200px;">
            <label>
            姓名: <input type="text" name="stu_name" placeholder="姓名" />
            </label><br/>
            <label>
            年龄: <input type="text" name="stu_age" placeholder="年龄" />
            </label><br/>
            <label>
            电话: <input type="text" name="stu_phone" placeholder="电话" />
            </label><br/>
            性别: <label><input type="radio" name="stu_sex" value="1" /></label><br/>
            
                <label><input type="radio" name="stu_sex" value="0" style="margin-left: 46px;"/></label><br/>
            
            <input type="submit" value="提交" style=" 100px;">
        </form>
        
    </body>
</html>

  update.html用于修改信息

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>添加数据</title>
    </head>
    <body>
        <form action="{% url 'edit_info_post' %}" method="post" style="margin-top: 100px;margin-left: 200px;">
            <!-- Django的post安全提交措施:会分配一个密钥 -->
            {% csrf_token %}
            编号: <input type="text" name="id" value="{{update_info.id}}" readonly="readonly" />
            <br/>
            <label>
            姓名: <input type="text" name="stu_name" value="{{update_info.stu_name}}" />
            </label><br/>
            <label>
            年龄: <input type="text" name="stu_age" value="{{update_info.stu_age}}" />
            </label><br/>
            <label>
            电话: <input type="text" name="stu_phone" placeholder="{{update_info.stu_phone}}" />
            </label><br/>
            
            {% if update_info == '1' %}
            性别: <label><input type="radio" name="stu_sex" value="1" checked="checked" /></label><br/>        
                <label><input type="radio" name="stu_sex" value="0" style="margin-left: 46px;"/></label><br/>
            {% else %}
            性别: <label><input type="radio" name="stu_sex" value="1" /></label><br/>
                <label><input type="radio" name="stu_sex" value="0" style="margin-left: 46px;" checked="checked" /></label><br/>
            {% endif %}
            
            <input type="submit" value="提交" style=" 100px;">
        </form>
        
    </body>
</html>

4.根路由

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('app/', include('myapp.urls')),
]

5.子路由

from django.urls import path, re_path
from . import views

urlpatterns = [
    # 增删改查练习
    path('showinfo/', views.showinfo, name='show_info'),
    path('addinfo/', views.addinfo, name='add_info'),
    path('saveinfo/', views.saveinfo, name='save_info'),
    path('delinfo/', views.delinfo, name='del_info'),
    re_path(r'updateinfo/([0-9]+)/$', views.updateinfo, name='update_info'),
    path('edit_info_post/', views.edit_info_post, name='edit_info_post')
]

6.视图函数

from django.shortcuts import render
from django.http import HttpResponse, Http404
from django.urls import reverse
from . import models

def showinfo(request):
    all_info = models.Stu.objects.all()
    info_list = []
    for i in all_info:
        info_list.append(i)
    return render(request, 'show.html', {'stu_info': info_list})

def addinfo(request):
    return render(request, 'addition.html')

def saveinfo(request):
    # 接收数据
    stu_info = request.GET.dict()
    # 存入数据库
    info_database = models.Stu(**stu_info)
    info_database.save()
    return HttpResponse('<script>alert("数据已添加");location.href="' + reverse('show_info') + '"</script>')

def delinfo(request):
    #先接收到要删除的数据的id
    sid = request.GET.dict()['sid']
    # 查询数据作删除
    delete_info = models.Stu.objects.get(id=sid)
    delete_info.delete()
    return HttpResponse('<script>alert("数据已删除");location.href="' + reverse('show_info') + '"</script>')

def updateinfo(request, sid):
    update_info = models.Stu.objects.get(id=sid)
    return render(request, 'update.html', {'update_info': update_info})

def edit_info_post(request):
    # 接收修改后的数据
    modified_info = request.POST.dict()
    # 修改数据库中的数据
    stu_dict = models.Stu.objects.get(id=modified_info['id'])
    stu_dict.stu_name = modified_info['stu_name']
    stu_dict.stu_age = modified_info['stu_age']
    stu_dict.stu_sex = modified_info['stu_sex']
    stu_dict.stu_phone = modified_info['stu_phone']
    stu_dict.save()
    return HttpResponse('<script>alert("数据已修改");location.href="' + reverse('show_info') + '"</script>')

7.启动服务器

  D:Django/mysite_02>python manage.py runserver

原文地址:https://www.cnblogs.com/glz666/p/django_of_zhi.html