• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

django如何将mysql中表的内容通过models.py在网页端显示

mysql 搞代码 4年前 (2022-01-09) 17次浏览 已收录 0个评论

djangomodels.pymysqldjango viewssettings.py

各位朋友们好,mysql数据库中有1张表student包含了name,age两个字段,共1000条数据,现在我想通过django在网页端展示这些数据。看了网上的教程,我在models.py中添加了:
from django.db import models
import MySQLdb
import mysite.settings
class student(models.Model):
name = models.CharField(max_length = 20)
age = models.CharField(max_length = 20)

<code>def __str__(self):    return self.name</code>

并且在views.py中编写以下代码:

coding: utf-8

import sys
reload(sys)
sys.setdefaultencoding(“utf-8”)

from django.shortcuts import render, render_to_response
from polls.models import student
from django.http import HttpResponse
import MySQLdb
import mysite.settings

def index(request):
students = student.objects.all()
name = “”
for stud in students:
name = stud.name
break
return render_to_response(‘index.html’ , {‘students’:students , ‘name’:name})
在settings.py中设置数据库如下:
DATABASES = {
‘default’: {
‘ENGINE’: ‘django.db.backends.mysql’,
#’NAME’: os.path.join(BASE_DIR, ‘test’),#database name
‘NAME’: ‘test’,
‘USER’:’root’,
‘PASSWORD’:’123456′本文来源[email protected]搞@^&代*@码2网,
‘HOST’: ‘localhost’,
‘PORT’: ‘3306’,
}
}
在网页端index.html中编写以下内容

<code> <body>    <p>学生数据如下:</p>    <table border="10">        {% for student in students %}            <tr>                <td>{{student.name}}</td>                <td>{{student.age}}</td>            </tr>        {% endfor %}    </table></code>

我执行了python manage.py makemigrations 和 python manage.py migrate,虽然也出现了与mysql中表student对应的blog_student表,但是blog_student中没有内容,而且网页端没有数据显示。
请教各位朋友们,这是什么原因呢?该如何显示数据啊?
希望朋友们能指点一下,万分感谢。


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:django如何将mysql中表的内容通过models.py在网页端显示
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址