使用 Flask-WTF/WTForms 在 Flask 中添加取消按钮

Add a cancel button in Flask with Flask-WTF/WTForms

我想添加一个返回上一页的取消按钮。 我的代码是: forms.py:

from flask_wtf import Form
from wtforms import StringField, HiddenField, SubmitField
from wtforms.validators import DataRequired, Length, ValidationError


def _required(form, field):
    if not field.raw_data or not field.raw_data[0]:
        raise ValidationError('Field is required')

class OrganisationForm(Form):
    id = HiddenField('id', default="-1")
    name = StringField('name', validators=[DataRequired()])
    manager_name = StringField('manager_name')
    address = StringField('address', validators=[DataRequired()])
    city = StringField('city', validators=[DataRequired()])
    postal_code = StringField('postal_code', validators=[DataRequired(), Length(max=16)])
    province = StringField('province', validators=[Length(max=2, message="Can't exceed 2 characters")])
    country = StringField('country', validators=[DataRequired()])
    submit = SubmitField('Add')
    cancel = SubmitField('Cancel')

和模板页面:

{% block content %}
<div class="content-section">
  {{ utils.flashed_messages() }}
  <div class="center">

      {% if add_orgnisation %}
                <h1>add an organisation</h1>
            {% else %}
                <h1>Edit an organisation</h1>
      {% endif %}
    <br/>
    <br/>
    {{ wtf.quick_form(form,novalidate=True) }}
  </div>
</div>
{% endblock %}

观看次数,py

@orgs.route('/organisations/org_new')
@login_required
def org_new():
    add_orgnisation = True
    form = OrganisationForm()
    return render_template("organisations/organisation_form.html", form=form, title="New Organisation", edit=False, add_orgnisation=add_orgnisation)

单击取消按钮时出现 405 错误:方法不允许。

我的错误在哪里?我应该添加什么才能在单击“取消”时返回上一页?

谢谢

这是我的工作原理。

以我的形式...

btn_cancel = SubmitField(label='Cancel',
                         render_kw={'formnovalidate': True})

在我的 Python 代码中(views.py 在你的情况下)...

if request.method == 'POST':
    if form.btn_cancel.data:
        return redirect(url_for('data'))

最后一分钟编辑:下面 Gray Li 关于允许您的视图函数接受 POST 请求的注释也很重要。请务必检查一下。

I have a 405 error when I click on cancel button: Method not allowed. Where is my mistake?

当您提交表单时,数据将作为 POST 请求发送(因为呈现的表单元素将使用 <form method="post">)。但是,您的视图函数默认只允许 GET 请求,要接受 POST 请求,您必须像这样指定 methods 参数:

@orgs.route('/organisations/org_new', methods=['GET', 'POST'])  # <--
@login_required
def org_new():
   # ...

and what should I add to have a go back previous page when I click on Cancel?

使用 SubmitField 创建的任何字段都将呈现为提交按钮 (<input type="submit">),因此当您单击它时它会提交表单。

点击取消按钮时要回到上一页,一般有两种方法:

1。在视图函数中捕获按钮提交

喜欢中的方法。您可以只捕获提交然后将用户重定向到上一页:

@orgs.route('/organisations/org_new', methods=['GET', 'POST'])
@login_required
def org_new():
    if request.method == 'POST':
        if form.cancel.data:  # if cancel button is clicked, the form.cancel.data will be True
            return redirect(url_for('previous_page_view_name'))
    # ...

P.S。由于您已经在 wtf.quick_form 中设置了 novalidate=True,因此您无需在 class.

cancel 按钮上设置 render_kw={'formnovalidate': True}

2。创建一个 <a> 按钮而不是 cancel 字段

您可以创建一个普通的 <a> 元素作为取消按钮 (class="btn btn-secondary") 并用上一页的 URL 填充 href 参数(然后您不需要需要在表单 class 中添加 cancel 字段)。这样,您就不能使用 wtf.quick_form(),而是需要使用 wtf.form_field():

手动渲染每个字段
<form method="post">
    {{ wtf.form_field(form.id) }}
    {{ wtf.form_field(form.name) }}
    {{ wtf.form_field(form.manager_name) }}
    {{ wtf.form_field(form.address) }}
    ...
    {{ wtf.form_field(form.submit) }}
    <a href="{{ url_for('previous_page_view_name') }}" class="btn btn-secondary">Cancel</a>
</form>

不,我正在使用 TimeField 强制捕获有效时间。我没有尝试将其更改为普通文本字段,因此改为使用上面的取消 link 选项。不过我还是喜欢有一个取消按钮。