django链接mysql网页显示数据_使用Django连接mysql数据库并显示在网页上
由于使用Django框架來(lái)做網(wǎng)站,需要?jiǎng)討B(tài)顯示數(shù)據(jù)庫(kù)內(nèi)的信息,所以讀取數(shù)據(jù)庫(kù)必須要做
接下來(lái)分兩步來(lái)做這個(gè)事,添加網(wǎng)頁(yè),讀取數(shù)據(jù)庫(kù);
一、添加網(wǎng)頁(yè)
首先需要在工程中新建一個(gè)app
python manage.py startapp appdata
獲得一個(gè)名為appdata的應(yīng)用
首先按添加網(wǎng)頁(yè)的步驟添加網(wǎng)頁(yè),我的網(wǎng)頁(yè)名為table.html, app名為appdata
table.html放到\newpro\templates目錄下
forms.py文件提前寫好放在\newpro\appdata
from django importformsclassFormgood(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里面添加你的數(shù)據(jù)表中的字段,注意聲明Fromgood類下面第一行的tab空格是必須的(由于我數(shù)據(jù)表字段命名時(shí)使用了python的保留字段class,因此python在讀取數(shù)據(jù)時(shí)重新命名了其中的字段)
修改views.py,做好視圖
from django.shortcuts importrenderfrom appdata.models import Goods #insert
from appdata importformsfrom django.shortcuts importrender_to_response#Create your views here.deftable(request):
table_form=forms.Formgood() #web
good_list=Goods.objects.all() #message
return render_to_response("index/table.html",locals())
其中的table.html的路徑是工程的相對(duì)路徑
由于python的默認(rèn)編碼是utf-8編碼,為了方便,我把注釋都改成了英文,如果注釋寫中文在編譯時(shí)會(huì)出錯(cuò),需要把編碼方式改成gbk
修改url.py,添加路徑
from django.contrib importadminfrom django.urls importpathfrom appdata importviews
urlpatterns=[
path(‘a(chǎn)dmin/‘, admin.site.urls),
path(‘table/‘,views.table, name=‘table‘)
]
view.py中的變量good_list讀取了我們的數(shù)據(jù),接下來(lái)到table.html中
Titleshow
{% for number in good_list %}{{number.name}} : {{number.number}}
{% endfor %}
以表中的number為主字段顯示所有數(shù)據(jù)中的2條字段
進(jìn)入http://127.0.0.1:8000/table/網(wǎng)頁(yè)可以得到以下結(jié)果
原文:https://www.cnblogs.com/btc1996/p/9749762.html
總結(jié)
以上是生活随笔為你收集整理的django链接mysql网页显示数据_使用Django连接mysql数据库并显示在网页上的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 广发金卡最高额度
- 下一篇: 股票分红10派10元是什么意思