一个Django项目
先要有一台DB,创建库 t1,并创建表 classes,有如下记录:
mysql> select * from classes; +----+------------+ | id | title | +----+------------+ | 1 | 全栈4期 | +----+------------+
创建Django项目:

在新窗口中打开:

注释掉 settings.py 文件中的这一行:
'django.middleware.csrf.CsrfViewMiddleware',
在此文件的最后添加:
STATICFILES_DIR = (
os.path.join(BASE_DIR, 'static'),
)
在 Test01 下添加 App01,再在 App01 里创建文件 views.py,内容如下:
from django.shortcuts import render
import pymysql
def classes(request):
conn = pymysql.connect(host='192.168.153.128',port=3306,user='root',passwd='redhat',db='t1')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute('select id,title from classes')
class_list = cursor.fetchall()
cursor.close()
conn.close()
print(class_list)
return render(request, 'classes.html',{'class_list':class_list})
在 templates 下创建 classes.html,内容如下:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>班级列表</h1>
<table border="1">
<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>

浙公网安备 33010602011771号