Django learning little note 3- ① student management database

Creating a database first think good correspondence between each table: one to one, one to many, many to many;

Table structure: class, student, teacher

 

 Based on this relationship, create the following databases:

 

1. Show the data: 

First class to class operation to try:

Before we write programs on urls.py file, it is complex and not very professional! So we can create a directory such as call / app01 /, then create a new views.py (path automatically add, pay attention to check the good)

So that later you can  urls.py write:

from app01 import views
...
urlpatterns = [
#path('admin/', admin.site.urls),
path('classes',views.classes)
]

That is not what we need in  views.py  define a function in the classes:

# ! / Usr / bin / Python the env 
# - * - Coding: UTF-. 8 - * - 

from django.shortcuts Import the render 

# show class 
DEF classes (Request):
     Import pymysql 
    Conn = pymysql.connect (= Host ' 10.0.4 .x ' , Port = 3306, = User ' the root ' , the passwd = ' 123 ! 123 @ ' , DB = ' oldboys ' , charset = ' UTF8 ' ) 
    Cursor = conn.cursor (Cursor = pymysql.cursors.DictCursor) # create a cursor 
    cursor.execute ( "ID SELECT, from class title " ) # execute the SQL 
    class_list = cursor.fetchall () 
    cursor.close () # close the cursor 
    conn.close () # close the connection 
    return the render (Request, ' classes.html ' , { ' class_list ' : class_list})

Link the truth : more database operations see Wu SIR- Python development Chapter 19. []: Python operations MySQL  |  Python development [first post]

On the realization that the above database connection made operational data, that show how out of it? That is to create a return of class.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>班级</title>
</head>
<body>
    <h1>班级列表</h1>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>班级名称</th>
            </tr>
        </thead>
        <tbody>
            {% for row in class_list %}
            <tr>
                <td>{{ row.id }}</td>
                <td>{{ row.title }}</td>
           </tr>
            {% endfor %}
        </tbody>
    </table>
</body>
</html>

Look, the final implementation process is: Djando find new directory function classes views.py imported by urls.py route that corresponds to where the function is then rendered classes.html display page that contains the specially marked. Display Form implemented in circulation.

The final way, to achieve timely database data show:

 

 这样不算完,我们还有一个添加数据的需求:

2.添加数据:

就是在展示界面,添加一个<a>标签,实现增加一个班级的操作。(页面跳转)

<body>
    <h1>班级列表</h1>
    <div>
        <a href="/add_class/">添加</a>
    </div>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>班级名称</th>
            </tr>
        </thead>
        <tbody>
            {% for row in class_list %}
            <tr>
                <td>{{ row.id }}</td>
                <td>{{ row.title }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</body>

我们在templates下新建一个add_class.html的简单增加界面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加班级</title>
</head>
<body>
    <h1>增加班级</h1>
    <form method="POST" action="/add_class/">
        <p>班级名称:</p>
        <input type="text" name="title" required autofocus /><br>
        <input type="submit" value="提交" />
    </form></body>
</html>

这样再修改路由urls

urlpatterns = [
    #path('admin/', admin.site.urls),
    path('classes/',views.classes),
    path('add_class',views.add_class),

]

然后再在views.py里创建一个add_class的函数:

...

#添加班级
def add_class(request):
    #判断提交方式来区分什么操作
    if request.method == "GET":
        return render(request,'add_class.html')
    else:
        #print(request.POST)
        v = request.POST.get('title')
        #将title值添加到数据库
        import pymysql
        conn = pymysql.connect(host='10.0.4.x', port=3306, user='root', passwd='X123!@#123', db='oldboys', charset='utf8')
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        cursor.execute("insert into class(title) values(%s)",[v,])
        conn.commit()  #提交
        cursor.close()
        conn.close()
        #提交完再跳转到展示页
        return redirect('/classes/')

3. 删除数据

假设要删除一行数据,是不是需要把ID拿到,请求发过去就是告诉服务端要删除谁。那怎么传递这个id参数呢?

用到/?nid={{row.id}}

所以改的classes,html展示页:

<body>
    <h1>班级列表</h1>
    <div>
        <a href="/add_class/">添加</a>
    </div>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>班级名称</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            {% for row in class_list %}
            <tr>
                <td>{{ row.id }}</td>
                <td>{{ row.title }}</td>
                <td><a href="/del_class/?nid={{ row.id }}">删除</a></td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</body>

对应我们要在路由urls.py再增加对应:

path('del_class/',views.del_class),

再在views.py增加del_class函数:

...
#删除班级
def del_class(request):
    nid = request.GET.get('nid')
    # 数据库操作
    import pymysql
    conn = pymysql.connect(host='10.0.4.x', port=3306, user='root', passwd='123!@#123', db='oldboys', charset='utf8')
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    cursor.execute("delete from class where id=%s", [nid, ])
    conn.commit()  # 提交
    cursor.close()
    conn.close()
    # 提交完再跳转到展示页
    return redirect('/classes/')

由此可见http是一次请求一次响应。

4.编辑数据

这个时候我们发现光有删除是不够的,还需要一个编辑,修改class.html文件:

        <tbody>
            {% for row in class_list %}
            <tr>
                <td>{{ row.id }}</td>
                <td>{{ row.title }}</td>
                <td>
                    <a href="/edit_class/?nid={{ row.id }}">编辑</a>
                    |
                    <a href="/del_class/?nid={{ row.id }}">删除</a>
                </td>
            </tr>
            {% endfor %}
        </tbody>

这样有了点击按钮,我们就要设置下路由urls.py

    path('edit_class/',views.edit_class),

再在templates下增加一个edit_class.html

添加默认值放到表格的value中,就相当于添加原始值了;

id和titlle要一起发过去,不然不知道修改谁。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>编辑班级</title>
</head>
<body>
    <h1>编辑班级</h1>
    <!--<form method="POST" action="/edit_class/" >>-->
     <form method="POST" action="/edit_class/?nid={{ result.id }}"
        <p>班级名称:</p>
        <!--<input style="display: none" name="id" value="{{ result.id }}"/><br>>-->
        <input type="text" name="title" value="{{ result.title }}" autofocus /><br>
        <input type="submit" value="提交" />
    </form>
</body>
</html>

 然后对应到views.py写个edit_class的函数:

...
#编辑班级
def edit_class(request):
    if request.method == "GET":
        nid = request.GET.get('nid')
        # 数据库操作
        import pymysql
        conn = pymysql.connect(host='10.0.4.x', port=3306, user='root', passwd='123@#123', db='oldboys', charset='utf8')
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        cursor.execute("select id,title from class where id=%s", [nid, ])
        result = cursor.fetchone()  # 获取原始值
        cursor.close()
        conn.close()
        return render(request, 'edit_class.html', {'result': result})
    else:
        #是POST请求时,提交新的数据到数据库
        #nid = request.POST.get('id')  这个对应隐藏标签操作
        nid = request.GET.get('nid')
        title = request.POST.get('title')
        import pymysql
        conn = pymysql.connect(host='10.0.4.x', port=3306, user='root', passwd='123@#123', db='oldboys', charset='utf8')
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        cursor.execute("update class set title=%s where id=%s", [title,nid, ])
        conn.commit()
        cursor.close()
        conn.close()
        return redirect('/classes/')

注:值得注意的是,此时提交编辑的数据是要连带id一起提交的,因为提交操作又是一种新的请求,不然服务器不知道对应的哪个修改。

所以带id提交有两种方式可以实现:

1.POST提交表单时也写入<input>id 只不过利用dispaly=none属性将其隐藏用户看不到了,但实际他就在那然后一起提交给数据库了,这个时对应的操作数据库提取的就都是POST.get

2,也可以不隐藏,因为可以在url中携带nid,所以<form method="POST" action="/edit_class/?nid={{ result.uid }}">,然后提交数据库nid就从GET.get取,title还是POST.get中取。

这样就完成数据库的增删改查操作!

 

原创文章!转载请在明显处注明出处及链接,多谢合作~

Guess you like

Origin www.cnblogs.com/ethtool/p/12123038.html