使用Django连接mysql数据库并显示在网页上

由于使用Django框架来做网站,需要动态显示数据库内的信息,所以读取数据库必须要做

接下来分两步来做这个事,添加网页,读取数据库;

一、添加网页

首先需要在工程中新建一个app

python manage.py startapp appdata

获得一个名为appdata的应用

首先按添加网页的步骤添加网页,我的网页名为table.html, app名为appdata

table.html放到\newpro\templates目录下

forms.py文件提前写好放在\newpro\appdata

from django import forms 
class Formgood(forms.Form):           
    brand = forms.CharField(required=True,max_length=20)
name = forms.CharField(required=True,max_length=20)
number = forms.CharField(required=True,max_length=20)
version = forms.CharField(required=True,max_length=40)
class_field = forms.CharField( required=True,max_length=20)  # Field renamed because it was a Python reserved word.
price = forms.FloatField(required=True)

forms.py里面添加你的数据表中的字段,注意声明Fromgood类下面第一行的tab空格是必须的(由于我数据表字段命名时使用了python的保留字段class,因此python在读取数据时重新命名了其中的字段)

修改views.py,做好视图

from django.shortcuts import render
from appdata.models import Goods  #insert
from appdata import forms
from django.shortcuts import render_to_response
# Create your views here.def table(request):
    table_form=forms.Formgood()    #web
    good_list=Goods.objects.all()      #message
    return render_to_response("index/table.html",locals())

其中的table.html的路径是工程的相对路径

由于python的默认编码是utf-8编码,为了方便,我把注释都改成了英文,如果注释写中文在编译时会出错,需要把编码方式改成gbk

修改url.py,添加路径

from django.contrib import admin
from django.urls import path
from appdata import views

urlpatterns = [
path('admin/', admin.site.urls),
path('table/',views.table, name='table')
]

 view.py中的变量good_list读取了我们的数据,接下来到table.html中

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Title</title>
</head>
<body>
<p>show</p>
{% for number in good_list %}
<p> {{number.name}} : {{number.number}} 
</p>
<br />
{% endfor %}
</body>
</html>

以表中的number为主字段显示所有数据中的2条字段

进入http://127.0.0.1:8000/table/网页可以得到以下结果

 

猜你喜欢

转载自www.cnblogs.com/btc1996/p/9749762.html