python-38-简单的表操作

106 阅读4分钟

参考:http://www.cnblogs.com/yuanchenqi/articles/6083427.html

1.目录结构

2.setting.py

DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.mysql',

        'NAME': 'Django_demo1_new',    #你的数据库名称

        'USER': 'root',   #你的数据库用户名

        'PASSWORD': 'root', #你的数据库密码

        'HOST': '', #你的数据库主机,留空默认为localhost

        'PORT': '3306', #你的数据库端口

    }

}

3.urls.py

from django.contrib import admin
from django.urls import path
from app01.views import classes
from app01.views import students
from app01.views import teachers
from app01.views import ajax
urlpatterns = [
    path('admin/', admin.site.urls),

    path('classes.html/', classes.get_classes),
    path('add_classes.html/', classes.add_classes),
    path('del_classes.html/', classes.del_classes),
    path('edit_classes.html/', classes.edit_classes),
    path('set_teacher.html', classes.set_teacher),

    path('students.html', students.get_students),
    path('add_students.html', students.add_students),
    path('del_students.html', students.del_students),
    path('edit_students.html', students.edit_students),
    path('ajax1.html', ajax.ajax1),
    path('ajax2.html', ajax.ajax2),
    path('ajax4.html', ajax.ajax4),

]

4.classes.py

from django.shortcuts import render,HttpResponse,redirect
from app01 import models

def get_classes(request):
    cls_list=models.Classes.objects.all()

    return render(request,"get_classes.html",{"cls_list":cls_list})

def add_classes(request):
    if request.method=="GET":
        return render(request,"add_classes.html")
    elif request.method=="POST":
        title=request.POST.get("title")
        models.Classes.objects.create(title=title)
        return redirect("/classes.html")

def del_classes(request):
    nid=request.GET.get("nid")
    models.Classes.objects.filter(id=nid).delete()
    return redirect("/classes.html")

def edit_classes(request):
    if request.method=="GET":
        nid = request.GET.get("nid")
        obj = models.Classes.objects.filter(id=nid).first()
        return render(request, "edit_classes.html", {"obj": obj})
    elif request.method=="POST":
        nid=request.POST.get("nid")
        title=request.POST.get("xx")
        models.Classes.objects.filter(id=nid).update(title=title)
        return redirect("/classes.html")

def set_teacher(req):
    if req.method=="GET":
        nid=req.GET.get("nid")
        cls_obj=models.Classes.objects.filter(id=nid).first()
        cls_teacher_list=cls_obj.m.all().values_list("id","name")
        if list(zip(*cls_teacher_list)):
            id_list = list(zip(*cls_teacher_list))[0]
        else:
            id_list=[]


        all_teacher_list=models.Teachers.objects.all()
        return render(
            req,
            "set_teacher.html",
            {
                "id_list":id_list,
                "all_teacher_list":all_teacher_list,
                "nid":nid
            }
        )
    elif req.method=="POST":
        nid=req.GET.get("nid")
        ids=req.POST.getlist("teacher_ids")
        c=models.Classes.objects.filter(id=nid).first()
        c.m.set(ids)
        return redirect("/classes.html")

5.students.py

from django.shortcuts import render
from django.shortcuts import redirect
from app01 import models
def get_students(request):
    stu_list=models.Student.objects.all()
    return render(request,"get_students.html",{"stu_list":stu_list})
def add_students(req):
    if req.method=="GET":
        cs_list = models.Classes.objects.all()
        return render(req, "add_students.html", {"cs_list": cs_list})
    elif req.method=="POST":
        u=req.POST.get("username")
        a=req.POST.get("age")
        g=req.POST.get("gender")
        c=req.POST.get("cs")
        models.Student.objects.create(
            username=u,
            age=a,
            gender=g,
            cs_id=c
        )
        return redirect("/students.html")

def del_students(req):
    nid=req.GET.get("nid")
    models.Student.objects.filter(id=nid).delete()
    return redirect("/students.html")
def edit_students(req):
    if req.method=="GET":
        nid = req.GET.get("nid")
        obj = models.Student.objects.filter(id=nid).first()
        cls_list = models.Classes.objects.values("id", "title")
        return render(req, "edit_students.html", {"obj": obj, "cls_list": cls_list})
    elif req.method=="POST":
        nid=req.POST.get("id")
        u=req.POST.get("username")
        a=req.POST.get("age")
        g=req.POST.get("gender")
        c=req.POST.get("class_id")
        print(nid,u,a,g,c)
        models.Student.objects.filter(id=nid).update(username=u,age=a,gender=g,cs_id=c)
        return redirect("/students.html")


6.models.py

from django.db import models

# Create your models here.
"""
老师表
"""
class Teachers(models.Model):
    name=models.CharField(max_length=32)
"""
班级表
"""
class Classes(models.Model):
    title=models.CharField(max_length=32)
    m = models.ManyToManyField(Teachers)

class Student(models.Model):
    username=models.CharField(max_length=32)
    age=models.IntegerField()
    gender=models.BooleanField()
    cs=models.ForeignKey(Classes,on_delete=models.CASCADE,)

7.add_classes.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>add_classes</title>
</head>
<body>
<form action="/add_classes.html" method="post">
    {% csrf_token %}
    <input type="text" name="title">
    <input type="submit" value="提交">
</form>
</body>
</html>

8.add_students.py

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>add_students</title>
</head>
<body>
<h3>添加用户</h3>
<form action="/add_students.html" method="post">
{% csrf_token %}
    <p><input type="text" name="username" placeholder="用户名"></p>
    <p><input type="text" name="age" placeholder="年龄"></p>
    <p>
        男 <input type="radio" name="gender" value="1">
        女 <input type="radio" name="gender" value="0">
    </p>
    <p>
        <select name="cs">
            {% for row in cs_list %}
                <option value="{{ row.id }}">{{ row.title }}</option>
            {% endfor %}
        </select>
    </p>
    <input type="submit" value="提交">
</form>
</body>
</html>

9.edit_classes.py

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>edit_classes</title>
</head>
<body>
<form action="/edit_classes.html" method="post">
    {% csrf_token %}
    <input type="text" name="nid" value="{{ obj.id }}" style="display: none">
    <input type="text" name="xx" value="{{ obj.title }}">
    <input type="submit" value="提交">
</form>

</body>
</html>

10.get_classes.py

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>get_classes</title>
</head>
<body>
    <div>
        <a href="/add_classes.html">添加</a>
    </div>
    <div>
        <table border="1">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>名称</th>
                    <th>老师</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                {% for row in cls_list %}

                      <tr>
                        <td>
                            {{ row.id }}
                        </td>
                          <td>
                            {% for f11 in row.m.all %}
                                    <span>{{ f11.name }}</span>
                            {% endfor %}

                        </td>
                         <td>
                            {{ row.title }}
                        </td>
                        <td>
                            <a href="/del_classes.html?nid={{ row.id }}">删除</a>
                            |
                            <a href="/edit_classes.html?nid={{ row.id }}">编辑</a>
                            |
                            <a href="/set_teacher.html?nid={{ row.id }}">分配老师</a>
                        </td>
                      </tr>
                {% endfor %}

            </tbody>
        </table>
    </div>



</body>
</html>

11.get_students.py

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>get_classes</title>
</head>
<body>
    <div>
        <a href="/add_students.html">添加</a>
    </div>
    <div>
        <table border="1">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>性别</th>
                    <th>班级</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                {% for row in stu_list %}
                      <tr  nid="{{ row.id }}">
                        <td>
                            {{ row.id }}
                        </td>
                         <td>
                            {{ row.username }}
                        </td>
                          <td>
                            {{ row.age }}
                        </td>
                          <td>
                              {% if row.gender %}
                                  <p>男</p>
                                  {% else %}
                                  <p>女</p>
                              {% endif %}

                        </td>
                           <td>
                            {{ row.cs.title }}
                        </td>
                        <td>
                            <a href="/del_students.html?nid={{ row.id }}">删除</a>
                            |
                             <a href="javascript:void();" onclick="removestudent(this);">ajax删除</a>
                            |
                            <a href="/edit_students.html?nid={{ row.id }}">编辑</a>
                        </td>
                      </tr>
                {% endfor %}

            </tbody>
        </table>
    </div>
<script src="/static/jquery-3.1.1.js"></script>
    <script>
        function removestudent(mimi) {
            var nid = $(mimi).parent().parent().attr("nid")
            console.log(nid)
            $.ajax({
                url:"/ajax4.html",
                    type:"GET",
                    data:{nid:nid},
                success:function (arg) {
                    if(arg=="成功"){
                        {#window.location.reload();#}
                        $(mimi).parent().parent().remove()
                    } else {
                        alert(arg);
                    }

                }
            })

        }
    </script>
</body>
</html>


12edit_students.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>edit_classes</title>
</head>
<body>
<form action="/edit_students.html" method="post">
    {% csrf_token %}
    <p style="display: none"><input type="text" name="id" value="{{ obj.id }}"></p>

    <p><input type="text" name="username" value="{{ obj.username }}"></p>
    <p><input type="text" name="age" value="{{ obj.age }}"></p>
    <p>
        {% if obj.gender %}
            男 <input type="radio" name="gender" checked="checked" value="1">
            女 <input type="radio" name="gender" value="0">
            {% else %}
            男 <input type="radio" name="gender"  value="1">
            女 <input type="radio" name="gender" checked="checked" value="0">
        {% endif %}
    </p>
    <p>
        <select name="class_id">
            {% for row in cls_list %}
                {% if row.id == obj.cs_id %}
                    <option value="{{ row.id }}" selected="selected">{{ row.title }}</option>
                {% else %}
                    <option value="{{ row.id }}">{{ row.title }}</option>
                {% endif %}
            {% endfor %}

        </select>
    </p>
    <input type="submit" value="提交">
</form>

</body>
</html>

13.ajax1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax</title>
    <style>
        .btn{
            display: inline-block;
            padding: 5px 15px;
            background: green;
            color: red;
            text-align: center;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div>
       用户名: <input type="text" placeholder="用户名" id="username"><br>
         密码: <input type="password" placeholder="密码" id="password"><br>
                <div class="btn" onclick="submitForm();">提交</div>
    </div>
    <script src="/static/jquery-3.1.1.js"></script>
    <script>
        function submitForm() {
            var u=$("#username").val()
            var p=$("#password").val()
            $.ajax({
                url:"/ajax2.html",
                type:"GET",
                data:{username:u,password:p},
                success:function (arg) {
                    console.log(arg)
                }
            })

        }
    </script>
</body>
</html>

14.ajax.py

from django.shortcuts import render,HttpResponse,redirect
def ajax1(req):
    return render(req,"ajax1.html")
def ajax2(req):
    user=req.GET.get("username")
    pwd=req.GET.get("password")
    import time
    time.sleep(4)
    return HttpResponse("ok")

from app01 import models

def ajax4(req):
    nid=req.GET.get("nid")
    msg="成功"
    try:
        models.Student.objects.filter(id=nid).delete()
    except Exception as e:
        msg=str(e)
    return HttpResponse(msg)

13.表结构