我正在學習使用燒瓶中的數據庫在https://www.tutorialspoint.com/flask/flask_sqlalchemy.htm 和我的問題是,數據不顯示在HTML!
我的代碼:
燒瓶來自sqlite數據庫的sqlalchemy數據未顯示
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:
當我將數據添加到數據庫中,ID,這是我設置爲自動增量顯示,但其餘數據不顯示。
現在,它的工作原理!謝謝。對不起,我是初學者,但你能解釋他們爲什麼應該是相同的嗎? – Sangwon
它就像一個類結構,一旦你指定了一個屬性名稱,就使用相同的名稱來引用該屬性,在你的初始代碼中你沒有在你的模型中指定_num_和_name_字段,而你的stu_num和stu_name字段沒有在__init__函數中設置。 – ebd