我对 Flask 还很陌生,正在努力将数据从表单传输到 SQL 数据库。该表单位于模式内,可以完美运行,并且在提交表单后将重定向回主页。但是,表单中的数据不会传输到我与该项目关联的 SQL 数据库。我确信我错过了一些非常简单的东西,我们将不胜感激!如果需要更多代码屏幕截图,请告诉我。
用于注册模式的 HTML 模板
<div class="modal fade" id="registerModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="registerModalLabel">Register</h4>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<form method="POST" action="" novalidate>
{{ registration_form.hidden_tag() }}
<div class="mb-2">
{{ registration_form.employee_id.label(class="form-label") }}
{{ registration_form.employee_id(class="form-control") }}
{% for error in registration_form.employee_id.errors %}
<span style="color: red;">[{{ error }}]</span>
</div>
<div class="mb-2">
{{ registration_form.email.label(class="form-label") }}
{{ registration_form.email(class="form-control") }}
{% for error in registration_form.email.errors %}
<span style="color: red;">[{{ error }}]</span>
</div>
<div class="mb-2">
{{ registration_form.password.label(class="form-label") }}
{{ registration_form.password(class="form-control") }}
{% for error in registration_form.password.errors %}
<span style="color: red;">[{{ error }}]</span>
</div>
<div class="mb-2">
{{ registration_form.confirm_password.label(class="form-label") }}
{{ registration_form.confirm_password(class="form-control") }}
{% for error in registration_form.confirm_password.errors %}
<span style="color: red;">[{{ error }}]</span>
</div>
<div class="mb-2">
{{ registration_form.submit(class="btn btn-primary") }}
</div>
</form>
</div>
</div>
</div>
</div>
表单数据发送到的索引路由功能
@app.route('/index', methods=['GET', 'POST'])
def index():
if current_user.is_authenticated:
return redirect(url_for('index'))
registration_form = RegistrationForm()
login_form = LoginForm()
if registration_form.validate_on_submit():
employee_id = registration_form.employee_id.data
email = registration_form.email.data
password = registration_form.password.data
# Check if employee ID or email already exists
existing_employee_id = Employee.query.filter_by(employee_id=employee_id).first()
existing_email = Employee.query.filter_by(email=email).first()
if existing_employee_id:
flash('This ID is already in use.', 'danger')
elif existing_email:
flash('This email is already registered.', 'danger')
else:
new_employee = Employee(
employee_id=employee_id,
email=email,
password_hash=generate_password_hash(password, salt_length=32)
)
print(new_employee)
db.session.add(new_employee)
try:
db.session.commit()
flash(f'Registration successful for employee {employee_id}.', 'success')
return redirect(url_for('index'))
except:
db.session.rollback()
flash(f'Failed to register user', 'danger')
return render_template('index.html', registration_form=registration_form, login_form=login_form)
我希望将模态表单中的数据提交到我的 SQL 数据库。表单完成并关闭,但数据尚未传输。
通过执行这些步骤,您应该能够排除故障并修复将表单数据保存到 SQL 数据库的问题。如果您遇到特定错误或需要进一步帮助,请随时询问!