You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FLASK应用无法接收HTML表单数据,求解决方案及代码示例

Flask无法接收HTML表单提交数据的解决方法

你的代码存在几个关键问题导致无法接收表单数据,以下是修复方案和完整代码示例:

问题分析

  1. 数据格式不匹配:HTML表单默认以application/x-www-form-urlencoded格式提交数据,但你用了request.get_json()(仅处理JSON格式),自然拿不到数据。
  2. 路由URL不匹配:Flask路由定义的是/students,但表单action写的是/students/(末尾多了斜杠),会导致请求路由不匹配。
  3. 语法错误:创建new_student时缺少闭合的右括号,会导致服务器报错。

修复后的Flask代码

import os.path
from flask import Flask, request, redirect, url_for, render_template
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'students.db')
db = SQLAlchemy(app)

# 类名遵循PEP8规范,首字母大写
class Student(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    FirstName = db.Column(db.String(100), nullable=False)
    SecondName = db.Column(db.String(20), nullable=False)
    Section = db.Column(db.Text, nullable=False)

# 添加GET路由用于渲染表单页面
@app.route('/')
def index():
    return render_template('form.html')  # HTML文件需放在项目根目录的templates文件夹下

@app.route('/students', methods=['POST'])
def create_student():
    # 用request.form获取表单提交的键值对数据
    first_name = request.form.get('FirstName')
    second_name = request.form.get('SecondName')
    section = request.form.get('Section')
    
    # 可选:添加基础数据验证,避免空值存入数据库
    if not first_name or not second_name or not section:
        return "所有字段不能为空", 400
    
    # 修复语法错误,补充闭合括号
    new_student = Student(
        FirstName=first_name,
        SecondName=second_name,
        Section=section
    )
    db.session.add(new_student)
    db.session.commit()
    
    # 提交成功后重定向,避免用户刷新页面重复提交
    return redirect(url_for('index'))

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(host='127.0.0.1', port=8000, debug=True)

修复后的HTML表单代码

<!DOCTYPE html>
<html>
<head>
    <title>Create Student Entry</title>
</head>
<body>
<!-- 使用相对路径匹配路由,避免硬编码URL -->
<form action="/students" method="post">
    <label for="FirstName">FirstName:</label><br>
    <input type="text" id="FirstName" name="FirstName" required><br>
    <label for="SecondName">SecondName:</label><br>
    <input type="text" id="SecondName" name="SecondName" required><br>
    <label for="Section">Section:</label><br>
    <input type="text" id="Section" name="Section" required><br>
    <input type="submit" value="Submit">
</form>
</body>
</html>

额外优化提示

  • 手动创建templates文件夹存放HTML文件,确保Flask能通过render_template正确加载页面,避免直接打开本地HTML文件引发的路径问题。
  • 表单添加required属性实现前端基础验证,减少无效请求。
  • 遵循PEP8命名规范(如类名Student而非student),提升代码可读性。
  • 提交成功后用redirect重定向,防止重复提交数据。

内容的提问来源于stack exchange,提问作者Ashish Bansal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 12:05:43