Django(2.1.2)對資料庫MySQL操作
阿新 • • 發佈:2018-11-03
Django(2.1.2)對資料庫MySQL操作
Django(2.1.2)對資料庫MySQL操作
今天結合一個學生表,說一下Django(2.1.2)對資料庫MySQL基本操作,包括資料庫的建表,資料庫的增刪改。在這工程中我使用了PyCharm工具,在資料重新整理方面我用來後端重新整理。
1.建一張表
在此次專案中我主要實現對學生資訊的增刪改查,所以先建一張學生表。
在建立一個應用(student),在工程目錄(mysite)的settings.py完成以下操作
資料庫預設SQLite3,因為資料庫MySQL要使用PyMySQL,所以在__int__.py檔案中完成
建一張學生表,在應用(student)目錄下的models.py中完成
在終端輸入命令
python manage.py makeigrations
和python manage.py migrate
建立學生表如下:2.檢視資料
3.增加資料
4.刪除資料
5.修改資料
6.路由設定
7.HTML設定
主介面的index.html的設定
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>學生資訊首頁</title> </head> <body> <h1>學生資訊首頁</h1> <div> {% if student %} <ul> {% for item in student %} <li> 學號:{{ item.sid }} 姓名:{{ item.sname }} 年齡:{{ item.sage }} {% if item.ssex == 'm' %} <span>性別:男</span> {% elif item.ssex == 'f' %} <span>性別:女</span> {% endif %} <a href="{% url 'editpage' %}?id={{ item.id }}">編輯</a> <a href="{% url 'del' %}?id={{ item.id }}">刪除</a> </li> {% endfor %} </ul> {% endif %} <a href="{% url 'add' %}">新增學生</a> </div> </body> </html>
新增學生資訊介面的adddata.html的設定
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ title }}資訊</title> </head> <body> <div> <form action="{% url urlname %}" method="post"> {% csrf_token %} <input type="text" name="name" placeholder="姓名" required value="{{ stu.sname }}"><br> <input type="text" name="age" placeholder="年齡" required value="{{ stu.sage }}"><br> {% if stu.ssex == 'm' %} <input type="text" name="sex" placeholder="性別" required value="男"><br> {% elif stu.ssex == 'f' %} <input type="text" name="sex" placeholder="性別" required value="女"><br> {% else %} <input type="text" name="sex" placeholder="性別" required value=""><br> {% endif %} <input type="submit" value="儲存"> <input type="text" name="id" value="{{ stu.id }}" style="display: none"> </form> </div> </body> </html>
修改介面繼承了新增學生資訊介面的edit.html的設定
{% extends 'adddata.html' %}```