当前位置:Gxlcms > mysql > django如何将mysql中表的内容通过models.py在网页端显示

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

时间:2021-07-01 10:21:17 帮助过:66人阅读

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)

def __str__(self):    return self.name

并且在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',
'HOST': 'localhost',
'PORT': '3306',
}
}
在网页端index.html中编写以下内容

     

学生数据如下:

{% for student in students %} {% endfor %}
{{student.name}} {{student.age}}

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

人气教程排行