首页  >  文章  >  数据库  >  django如何将mysql中表的内容通过models.py在网页端显示

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

WBOY
WBOY原创
2016-06-06 09:37:411476浏览

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

<code>     <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中没有内容,而且网页端没有数据显示。
请教各位朋友们,这是什么原因呢?该如何显示数据啊?
希望朋友们能指点一下,万分感谢。

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn