概述
1. 自定义数据模板,从数据库后台取数,在View显示的结果为 元组 即('表的列对应的值 ')
2. 如何在页面中显示
定义数据库连接 oledb.py
Import pymysql;
Def connectdb():
print('连接到mysql服务器......')
Db = pymysql.connect(host="localhost",user="root",password="root",db="workdb",port=3306,charset='utf8')
print('连接上了!')
Return db;
-----------------------------------------------------------------------------------------------------
Models.py内容
From django.db import models
Import pymysql;
From xibei import oledb
#Createyourmodelshere.
Def Get_Works():
sql="select id,title from work_works where type='01'ORDER by pub_date desc"
db=oledb.connectdb()
try:
cur=db.cursor()#oledb.db.cursor()
cur.execute(sql)
results=cur.fetchall()
Return results
Except Exception as e:
Raise e
finally:
db.close()
Views内容
#-*-coding:utf-8-*-
#encoding=utf-8
From django.shortcuts import render
From django.http import HttpResponse
From django.shortcuts import redirect
From django.template.loader import get_template
From datetime import datetime
From xibei import models
Import time
#Createyourviewshere.
Def Get_result(request):
obj=models.Get_Works()
For row in obj:
html=row[2]
print(html)
Return HttpResponse('helloworld!')
Def home(request):
template=get_template('home.html')
posts=models.Get_Works()
For row in posts:
html=row[0]
#list.append(html)
print(html)
Return HttpResponse(render(request,"home.html",context={"posts":posts}))
#html=template.render(locals())
#return HttpResponse(html)
网页显示内容
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<title>Title</title>
</head>
<body>
helloworld!!!
{% for post in posts %}
<p>{{
post.1}}</p>
{%endfor%}
</body>
</html>
最后
以上就是温柔冥王星为你收集整理的Django-Web 元组在模板页中的显示的全部内容,希望文章能够帮你解决Django-Web 元组在模板页中的显示所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复