几天以来,我对Flask和SQLAlchemy遇到了问题
我正在寻找一个小应用程序,以使躁郁症患者能够追踪自己的情绪并与医生分享结果。
我的问题出现在注册过程中。注册后,用户会出现在“用户”表中,但填写公式后,它们不会出现在“医生”表中。我无法将数据插入Doctor表。我没有出现任何错误。我可以手动操作,但不能通过表单。
问题似乎不在表单或模板级别。我来自我获取视图中user.id的方式...
我的模型:
class User(UserMixin, db.Model) :
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(20), unique = True, nullable = False)
password = db.Column(db.String(60), nullable=False)
def __init__(self, id, name, email, password):
self.email = email
self.password = password
class Doctor(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
firstname = db.Column(db.String(20), nullable = False)
lastname = db.Column(db.String(20), nullable = False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = relationship("User", backref=backref("user", uselist=False))
def __init__(self, id, firstname, lastname, user_id):
self.firstname = firstname
self.lastname = lastname
self.user_id = current_user.id
我的观看次数:
@app.route('/signup', methods=['GET', 'POST'])
def signup():
form = SignupForm()
if form.validate_on_submit():
hashed_password = generate_password_hash(form.password.data, method='sha256')
new_user = User(id, name = form.name.data, email = form.email.data, password = hashed_password)
db.session.add(new_user)
db.session.commit()
return redirect(url_for('login'))
return render_template('signup.html', form=form)
@app.route('/add_doctor', methods=['GET', 'POST'])
@login_required
def add_doctor():
form = DoctorForm()
if form.validate_on_submit():
user_id = current_user.id
new_doctor = Doctor(id, firstname = form.firstname.data, lastname = form.lastname.data, user_id = user_id)
db.session.add(new_doctor)
db.session.commit
return 'NEW DOCTOR HAS BEEN ADDED'
return render_template('doctor.html', form=form)
谢谢!
我已经找到问题了!
db.session.commit
必须是:
db.session.commit()
和:
new_doctor = Doctor(id, firstname = form.firstname.data, lastname = form.lastname.data, user_id = user_id)
必须是:
new_doctor = Doctor(id, firstname = form.firstname.data, lastname = form.lastname.data, user_id = current_user.id)
那是愚蠢的错误!