来自sqlite数据库的Flask Sqlalchemy数据未显示

时间:2017-04-24 07:31:03

标签: python sqlite flask sqlalchemy jinja2

我正在https://www.tutorialspoint.com/flask/flask_sqlalchemy.htm学习使用烧瓶中的数据库 我的问题是数据没有出现在html上! 我的代码:

from flask import Flask, redirect, url_for, request, render_template, session, escape, flash
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'

db = SQLAlchemy(app)

class Students(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  stu_num = db.Column('Student Number', db.Integer)
  stu_name = db.Column('Name', db.String(100))

  def __init__(self, number, name):
    self.num = number
    self.name = name

@app.route('/students/')
def show_students():
  return render_template('show_students.html', students=Students.query.all())

@app.route('/addstudents/', methods=['POST', 'GET'])
def add_students():
  if request.method == 'POST':
    if not request.form['stu_num'] or not request.form['stu_name']:
      flash('Please fill in all the fields')
    else:
      student = Students(request.form['stu_num'], request.form['stu_name'])
      db.session.add(student)
      db.session.commit()
      flash('Record added')
      return redirect(url_for('show_students'))
  return render_template('add_students.html')

if __name__ == '__main__':
  db.create_all()
  app.run(debug = True)

show_students.html:

<!doctype>
  <html>
    <body>

      {% for message in get_flashed_messages() %}
        {{ message }}
      {% endfor %}

      <h2><a href="{{ url_for('add_students') }}">Add Students</a></h2>

     <table>
       <tr>
         <th>Id</th>
         <th>Student Number</th>
         <th>Name</th>
       </tr>

         {% for student in students %}
         <tr>
           <td>{{ student.id }}</td>
           <td>{{ student.num }}</td>
           <td>{{ student.name }}</td>
         </tr>
         {% endfor %}
     </table>
   </body>
 </html>

add_students.html:

<!doctype>
  <html>
    <body>

      {% for message in get_flashed_messages() %}
        {{ message }}
      {% endfor %}

      <form action="http://localhost:5000/addstudents/" method="post">
       <p>Student Number: <input type="text" name="stu_num"></p>
       <p>Student Name: <input type="text" name="stu_name"></p>
       <p><input type="submit" value="Submit"></p>
      </form>

   </body>
 </html>

当我向数据库添加数据时,我设置为自动递增的Id显示,但其余数据未显示。

2 个答案:

答案 0 :(得分:1)

SQLAlchemy为您提供__init__函数,负责创建新对象,初始化字段,数据库等。通过编写自己的__init__,您将覆盖SQLAlchemy的 __init __(),并阻止它做它的事情!

所以试着摆脱你的__init__功能吧!

(或者如果你想在__init__中做的事情,那么一定要在做任何你想做的事情之前或之后调用super().__ init__。)

(但首先,试着摆脱它......)

答案 1 :(得分:1)

您在此处使用不一致的变量名称 在 init 功能中,使用

def __init__(self, number, name):
    student.stu_num=number
    student.stu_name=name
show_students.html中的

尝试使用

<td>{{ student.stu_num }}</td>
<td>{{ student.stu_name }} </td>