Dynamically display the contents of the MySQL database on the web page under the Python Django framework

            Dynamically display the contents of the MySQL database on the web page under the Python Django framework

Requirement: Display the data of a single table in a database in the database on the homepage of the web page. The table has three columns: id column, name column, and student number column, and has simple logic: the name and student number in a single row can be modified. Any row can be deleted, and it will automatically jump to the display page after modification and deletion. There is no pagination, permission management and other functions, just a simple display,

After deleting:

 Modifying:

 

============================================================================

Let's start to explain:

First, create a new project, the project name is sims. Run the command: Python manage.py startproject sims

Register the app in the settings.py file in the project directory. The app name is user.

 

 

Note that the library is best to be created first. The template folder is in the next level of the project. Right-click the folder named sims and create a new folder named template. Right-click the template folder and create a folder named student. After the above preparations are complete, run the command: python manage.py startapp user (write which name is registered). At this point, the basic project environment is ready.

============================================================================

Run the command: Python manage.py startapp user

After the execution is completed, there will be an additional level directory under the project and this directory is the name of the previously registered APP, and there are five files under it.

Next, start editing the  models.py file

This class name is the name of the newly created table. The name of the table generated in the final data is app name_class name, so please pay attention to this class name and try to have some meaning as much as possible.

Execute two commands: Python manage.py makemigrations

Python manage.py migrate

After execution, the tables used in the database will be initialized and generated. Of course, the table is temporarily empty, there is no data in it,

 This is the successful initialization.

===========================================================================

Configure routing:

user/urls.py file:

from django.conf.urls import url
from . import views
urlpatterns = [ url(r'^$', views.index),
                url(r'^add/$', views.add),
                url(r'^edit/$', views.edit),
                url(r'^delete/$', views.delete),
                ]

 

sims/urls.py:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('user.urls')),
]

============================================================================

Configuration view (all logical functions are inside):

user/views.py

#这个文件是视图功能的实现,
# Create your views here.
from django.http import HttpResponse
import MySQLdb
from django.shortcuts import render, redirect # Create your views here.
#学生信息列表处理函数,直接读取数据库的内容,将内容渲染到静态展示页面,算是查这个功能的实现。
def index(request):
    conn = MySQLdb.connect(host="数据库的ip",
    user="root",
    passwd="数据库的密码",
    db="要连接的数据库库名,settings.py里所设置的那个库名",
    charset='utf8')
    with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
        cursor.execute("SELECT id,student_no,student_name FROM user_student")
        students = cursor.fetchall()
        return render(request, 'student/index.html', {'students': students}) 
# 学生信息新增处理函数,这是增功能函数,注意返回的路由,增加动作完毕后自动跳转到查页面
def add(request):
    if request.method == 'GET':
        return render(request, 'student/add.html')
    else:
        student_no = request.POST.get('student_no', '')
        student_name = request.POST.get('student_name', '')
        conn = MySQLdb.connect(host="数据库ip", user="root", passwd="数据库密码", db="库名", charset='utf8')
        with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
            cursor.execute("INSERT INTO user_student (student_no,student_name) " "values (%s,%s)", [student_no, student_name])
    conn.commit()
    return redirect('../') 
# 学生信息修改处理函数,同上,只是sql语句不一样而已,换成了update语句。
def edit(request):
    if request.method == 'GET':
        id = request.GET.get("id")
        conn = MySQLdb.connect(host="要连的数据库ip", user="root", passwd="数据库密码", db="要连接的数据库库名,settings.py里所设置的那个库名", charset='utf8')
        with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
            cursor.execute("SELECT id,student_no,student_name FROM user_student where id =%s", [id])
            student = cursor.fetchone()
        return render(request, 'student/edit.html', {'student': student})
    else:
        id = request.POST.get("id")
        student_no = request.POST.get('student_no', '')
        student_name = request.POST.get('student_name', '')
        conn = MySQLdb.connect(host="数据库的ip", user="root", passwd="数据库密码", db="要连接的数据库库名,settings.py里所设置的那个库名", charset='utf8')
        with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
            cursor.execute("UPDATE user_student set student_no=%s,student_name=%s where id =%s", [student_no, student_name, id])
    conn.commit()
    return redirect('../') 
# 学生信息删除处理函数,同上,SQL语句改变而已。
def delete(request):
    id = request.GET.get("id")
    conn = MySQLdb.connect(host="数据库ip", user="root", passwd="数据库密码", db="要连接的数据库库名,settings.py里所设置的那个库名", charset='utf8')
    with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
        cursor.execute("DELETE FROM user_student WHERE id =%s", [id])
    conn.commit()
    return redirect('../')
#返回上层url

==============================================================================

Three HTML files:

template/student/.index.html:


<!DOCTYPE html>
<html lang="en">
<head> <meta charset="UTF-8">
    <title>学生列表</title>
</head>
<body> <table border="1px" width="100%" style="border-collapse: collapse;">
    <a href="../add">添加学生</a> <tr>
    <th>编号</th>
    <th>姓名</th>
    <th>学号</th>
    <th>操作</th>
</tr> {% for student in students %}
    <tr>
        <td align="center">{
   
   { forloop.counter }}
        </td> <td align="center">{
   
   { student.student_name }}
    </td>
        <td align="center">{
   
   { student.student_no }} </td>
        <td align="center">
            <a href="../edit/?id={
   
   { student.id }}"> 编辑 </a>
            <a href="../delete/?id={
   
   { student.id }}"> 删除 </a>
        </td> </tr> {% endfor %}
</table>
</body>
</html>

 

template/student/add.html:

<!DOCTYPE html>
<html lang="en">
<head> <meta charset="UTF-8">
    <title>学生添加</title>
    <style>
     form { margin: 20px auto; width: 500px; border: 1px solid #ccc; padding: 20px }
</style>
</head>
<body> <form method="post" action="../add/"> {% csrf_token %}
    <table> <tr> <th>姓名</th> <td><input name="student_name"></td>
    </tr>
        <tr> <th>学号</th>
            <td><input name="student_no"/></td>
        </tr> <tr>
            <td colspan="2">
            <input type="submit"/> </td>
        </tr>
    </table>
</form>
</body>
</html>

template/student/edit.html:

<!DOCTYPE html>
<html lang="en">
<head> <meta charset="UTF-8">
    <title>学生编辑</title>
    <style> form { margin: 20px auto; width: 500px; border: 1px solid #ccc; padding: 20px }
</style>
</head> <body>
<form method="post" action="../edit/"> {% csrf_token %}
    <input type="hidden" name="id" value="{
   
   { student.id }}"/>
    <table> <tr> <th>姓名</th> <td><input name="student_name" value="{
   
   { student.student_name }}"></td>
    </tr> <tr> <th>学号</th> <td><input name="student_no" value="{
   
   { student.student_no }}"/></td> </tr> <tr>
        <td colspan="2"> <input type="submit"/> </td>
    </tr>
    </table>
</form>
</body>
</html>

Because after deleting the data, it jumps directly to the viewing page, so there is no need to write it separately. You only need to refresh the index page after the front-end and back-end data are synchronized, and you can see it on the display page, which is index.html. Adding and modifying functions is another logic, so it needs to be written separately.

 

So, now you can run the command: Python manage.py runserver,

The program will start the development server so that you can use the browser to test the operation of your APP.

 

Guess you like

Origin blog.csdn.net/alwaysbefine/article/details/106086542