一、首先按添加网页的步骤添加网页,我的网页名为table.html, app名为web
table.html放到相应目录下,
froms文件提前写好
修改views.py
from django.shortcuts import render from web import forms def table(request): table_form=forms.SignupForm() return render(request,'table.html',{'form':table_form})
修改url.py
from django.conf.urls import url,include from django.contrib import admin from web import views urlpatterns = [ url(r'^signup/$',views.signup,name='signup'), url(r'^index/$',views.index,name='index'), url(r'^table/$',views.table,name='table') #这个是table的 ]
至此可以访问
http://127.0.0.1:8000/web/table/(http//127.0.0.1:8000/app/index)
正常显示网页内容。
二、读取mysql内容并显示:
在models.py中创建数据库 Employee,并设置name列(默认会有id列,为主键)
from __future__ import unicode_literals from django.db import models # Create your models here. class Employee(models.Model): name=models.CharField(max_length=20)
保存并同步数据库
python manage.py syncdb
这时进入到mysql中,找到我们django设置的数据库,进入其中,
看到如下表:

最后一个web_employee为我们刚创建的表(web是我的app名字,前缀是自动加的)
使用insert语句插入相应数据,显示如下:

ok数据已经添加完毕,接下来是在网页端显示,网页通过前面的配置已经可以正常显示,现在加入显示数据库信息
首先修改views.py
from django.shortcuts import render from web import forms from models import Employee #插入employee表 from django.shortcuts import HttpResponseRedirect,Http404,HttpResponse,render_to_response # Create your views here. def table(request): table_form=forms.SignupForm() #样式 ,在forms.py里配置好了 names=Employee.objects.all() #获取我们的数据库信息到names里 #return render(request,'table.html',{'form':table_form}) return render_to_response("table.html",locals()) #必须用这个return
变量names读取了我们的数据,接下来到table.html中
<html lang="en"> <head> <meta charset="UTF-8"> <title>Upload Successfully</title> </head> <body> <p>学生名单</p> {% for name in names %} <p>{{name.id}}   :   {{name.name}}</p> <br> {% endfor %} </body> </html>
用循环读取names里面的信息,name.id与name.name 是我们表中的两列,如上面的图。
最终结果如下
