【问题标题】:Flask WTForms - Retrieve form data when submitting to a different route, i.e. a different POST route than the GET route which renders the formFlask WTForms - 提交到不同路由时检索表单数据,即与呈现表单的 GET 路由不同的 POST 路由
【发布时间】:2020-09-30 10:13:08
【问题描述】:

我想尽可能根据 REST 设置我的 URL/端点,同时仍然使用 Flask-WTForms。

我希望我的表单在GET /posts/new 呈现,并提交到POST /post

使用 Flask-WTForms,我只能弄清楚如何让它 GET/POST 到同一个 URL。

我当前的代码如下所示:

@post_bp.route('/posts/new', methods=['GET', 'POST'])
def show_post_form():
    create_post_form = CreatePostForm()

    if create_post_form.validate_on_submit():
        return 'success'

    return render_template('create_post_form.html', form=create_post_form)

但是我希望能够使它看起来更像这样,但我似乎无法解决:

@post_bp.route('/posts/new', methods=['GET'])
def show_post_form():
    create_post_form = CreatePostForm()

    return render_template('create_post_form.html', form=create_post_form)
  • 这条路线只显示表单
  • 表单向 /post 提交 POST 请求
<form action="{{url_for('shipment.C_shipment')}}" method="POST" novalidate>
  • POST /post 路由处理提交的表单,如果出现错误,例如,它会重定向回GET /posts/new
@post_bp.route('/post', methods=['POST'])
def create_post():
    create_post_form = CreatePostForm()

    if create_post_form.validate_on_submit():
        return "success!"

    if len(create_post_form.errors) != 0:
        for error in create_shipment_form.errors:
            for msg in create_shipment_form.errors[error]:
                flash(msg)

    return redirect(url_for('shipment.show_create_shipment_form'))

    
  • 我想在这里创建一个新的CreatePostForm() 对象并没有真正起作用..

有什么建议吗?

【问题讨论】:

  • url_for('shipment.C_shipment') - 对吗?

标签: python flask flask-wtforms wtforms


【解决方案1】:

创建一个新的CreatePostForm 是正确的,因为它会为您解析提交的表单数据。这允许您在表单对象上调用validate_on_submit()

我认为您没有为 HTML sn-p 中的表单操作生成正确的 URL。 url_for() 的参数应该是所需的端点(参见 docs),它应该是 &lt;post_bp&gt;.create_post。这将类似于您的电话

return redirect(url_for('shipment.show_create_shipment_form'))

如果这不能解决问题,请提供您在尝试将数据发送到 /post 时收到的前端和后端错误消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 2019-09-10
    • 1970-01-01
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多