大大們好,
於輸入完name, height, weight並按下"提交"後,
在SQLite上仍然看不到data被寫入(DB、Column創建是有成功的),
想請教是在提交按鈕做錯,還是flask的連結邏輯錯誤,或是其他問題?
再麻煩大大們指正了,感謝解惑~
Python code
from datetime import datetime
from flask import flash
from flask import Flask
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# SQLite datebase link
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = r'sqlite:///tmp\test.db'
db = SQLAlchemy(app)
class UserFrame(db.Model):
__tablename__ = "member"
ids = db.Column(db.Integer , primary_key=True)
name = db.Column(db.String(60))
height = db.Column(db.Integer)
weight = db.Column(db.Integer)
update_time = db.Column(db.DateTime , default=datetime.now)
def __init__(self, name, height, weight):
self.name = name
self.height = height
self.weight = weight
@app.route("/", methods=["POST"])
def index():
db.create_all()
return render_template(("index.html"),
index_res =UserFrame.query.order_by(UserFrame.update_time.desc()).all())
@app.route("/add", methods=["POST","GET"])
def add():
if request.method == ["POST"]:
res = UserFrame(request.form["name"],
request.form["height"],
request.form["weight"])
db.session.add(res)
db.session.commit()
return redirect(url_for("index"))
else:
return render_template("add.html")
if __name__ == "__main__":
app.run(debug = True)
HTML
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<h1>Hi</h1>
<form method="POST" action="{{ url_for('add') }}">
<button type="submit"> 進入會員申請頁面 </button>
</form>
</body>
</html>
add.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<h1>Hi</h1>
<form method="POST" action="{{ url_for('index') }}">
<label> 請輸入名稱: </label>
<input type="text"
placeholder="在這邊輸入"
name="name"
value="{{ request.form.name }}">
<label> 請輸入身高: </label>
<input type="text"
placeholder="在這邊輸入"
name="height"
value="{{ request.form.height }}">
<label> 請輸入體重: </label>
<input type="text"
placeholder="在這邊輸入"
name="weight"
value="{{ request.form.weight }}">
<button type="submit" name="submit" value="submit">提交</button>
</form>
</html>
(以上,參考下方連結,我把它改成自己初學能理解的實作方法)
(試過原著的code,在index()加上create_all()就可以跑)
Reference:https://github.com/pallets/flask-sqlalchemy/tree/main/examples