3,修改hrsDjango\views.py,增加showDept方法:
from django.shortcuts import render, HttpResponse
import pymysql
from pymysql.cursors import DictCursor
def index(request):
return render(request, 'testHello.html')
def showDept(request):
# 部门类
class Dept(object):
def __init__(self, no, name, addr):
self.no = no
self.name = name
self.addr = addr
# 1,创建数据库连接对象
con = pymysql.connect(
host='localhost', port=3306,
database='db_python', charset='utf8',
user='root', password='python3', autocommit=True
)
try:
deptList = []
with con.cursor(cursor=DictCursor) as cur:
cur.execute(
'select deptno as no, deptname as name, deptaddr as addr from tb_dept'
)
deptList = cur.fetchall()
finally:
con.close()
print(deptList)
return render(request, 'testDept.html', {'deptList': deptList})
4,修改hrsDjango\urls.py,添加新的path:
from django.urls import path
from hrsDjango import views
urlpatterns = [
path('', views.index),
path('dept/', views.showDept)
]
5,在emp目录下新增一个html文件:testDept.html
部门信息
部门信息:
编号
名称
地址
{% for dept in deptList %}
{{ dept.no }}
{{ dept.name }}
{{ dept.addr }}
{% endfor %}
6,启动server,打开浏览器,在url栏输入:http://127.0.0.1:8000/hrs/dept
DB内容:
作者:平头哥哥