day49作业
结合前端,django,MySQL,pymysql模块实现数据库数据动态展示到前端
效果图:

数据交互流程

urls.py代码:
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/',views.index)
]
app01/views.py代码:
from django.shortcuts import render,HttpResponse,redirect
# Create your views here.
def index(request):
'''
先从数据库中查出来所有的数据,利用模板语法,将结果发送给前端,展示在web端。
:param request:
:return:
'''
import pymysql
conn = pymysql.connect(
host="192.168.32.130",
password="123",
user="root",
charset="utf8",
database="test"
)
cursor = conn.cursor(pymysql.cursors.DictCursor)
sql = "select * from user"
cursor.execute(sql)
res = cursor.fetchall()
print(res)
# return HttpResponse("OK")
return render(request,"index.html",{"res":res})
templates/index.html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<h1 class="text-center" style="font-size: 50px;font-weight: bold">数据展示</h1>
<div class="container">
<div class="row">
<table class="table-striped table table-bordered table-hover">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>salay</th>
</tr>
</thead>
<tbody>
{% for re in res %}
<tr class="success">
<td>{{ re.id }}</td>
<td>{{ re.name }}</td>
<td>{{ re.salary }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</body>
</html>

浙公网安备 33010602011771号