flask-wtf在同一个html模板中进行多次验证

时间:2015-12-28 13:49:03

标签: python jinja2 flask-wtforms

我的第一个webapp并尝试使用flask,jinja2,wtforms等。我已经找到了答案,但我很快就会出现。我正在尝试使用两个单独的表单呈现模板,每个表单都有唯一的验证要求。我遇到的问题是,即使我只提交一个表单,另一个表单也会向用户返回验证错误。我希望能够独立使用这两种形式,而在另一种形式上没有验证错误。两种表单目前都有效,但在共享相同模板时却不起作用。

烧瓶中:

# Main Customer Page
@app.route('/customers/', methods=['GET', 'POST'])
@login_required
def customers():
    error = None
    customer_form = AddCustomerForm(request.form)
    address_form = AddAddressForm(request.form)
    if request.method == "POST":
        if customer_form.validate_on_submit():
            add_customer = Customer(
                customer_form.name.data,
                customer_form.email.data,
                customer_form.telephone.data
            )
            db.session.add(add_customer)
            db.session.commit()
            flash('New customer was successfully added')
        if address_form.validate_on_submit():
            add_address = Address(
                address_form.street.data,
                address_form.city.data,
                address_form.state.data,
                address_form.zip.data
            )
            db.session.add(add_address)
            db.session.commit()
            flash('New Address was successfully added')
    return render_template('customers.html', customer_form=customer_form, address_form=address_form, error=error)

模板:

{% extends "_base.html" %}

{% block content %}

<h4>Add New Customer</h4>
<form class="form-signin" role="form" method="post" action="/customers/">
  {{ customer_form.csrf_token }}
  {{ customer_form.name(placeholder="customer name") }}
    <span class="error">
      {% if customer_form.name.errors %}
        {% for error in customer_form.name.errors %}
          {{ error }}
        {% endfor %}
      {% endif %}
    </span>
    {{ customer_form.telephone(placeholder="telephone number") }}
    <span class="error">
      {% if customer_form.telephone.errors %}
        {% for error in customer_form.telephone.errors %}
          {{ error }}
        {% endfor %}
      {% endif %}
    </span>
    {{ customer_form.email(placeholder="email address") }}
    <span class="error">
      {% if customer_form.email.errors %}
        {% for error in customer_form.email.errors %}
          {{ error }}
        {% endfor %}
      {% endif %}
    </span>
    <button class="btn btn-sm btn-success" type="submit">Create</button>
  </form>


<form class="form-signin" role="form" method="post" action="/customers/">
  {{ address_form.csrf_token }}
    <br>
    <h4>Add Address</h4>
    {{ address_form.priority }}
    {{ address_form.street(placeholder="street") }}
    <span class="error">
      {% if address_form.street.errors %}
        {% for error in address_form.street.errors %}
          {{ error }}
        {% endfor %}
      {% endif %}
    </span>
    {{ address_form.city(placeholder="city") }}
    <span class="error">
      {% if address_form.city.errors %}
        {% for error in address_form.city.errors %}
          {{ error }}
        {% endfor %}
      {% endif %}
    </span>
    {{ address_form.state(placeholder="state abbreviation") }}
    <span class="error">
      {% if address_form.state.errors %}
        {% for error in address_form.state.errors %}
          {{ error }}
        {% endfor %}
      {% endif %}
    </span>
    {{ address_form.zip(placeholder="zip") }}
    <span class="error">
      {% if address_form.zip.errors %}
        {% for error in address_form.zip.errors %}
          {{ error }}
        {% endfor %}
      {% endif %}
    </span>
  <button class="btn btn-sm btn-success" type="submit">Add</button>
</form>
<br>
<h2>Search Customers</h2>

{% endblock %}

表单验证:

class AddCustomerForm(Form):
    name = StringField('Username', validators=[DataRequired()])
    email = StringField('Email', validators=[Email()])
    telephone = StringField('Telephone', validators=[DataRequired(), Length(min=10, max=10)])


class AddAddressForm(Form):
    names = [(0, "Select Customer")]
    for k in customer_names():
        names.append((k.id, k.name))

    priority = SelectField(
            'Select Customer',  # this is the name of the field
            validators=[DataRequired()],
            choices=names)

    street = StringField('Street', validators=[DataRequired()])
    city = StringField('City', validators=[DataRequired()])
    state = StringField('State', validators=[DataRequired(), Length(min=2, max=2)])
    zip = StringField('Zip', validators=[DataRequired(), Length(min=5, max=5)])

1 个答案:

答案 0 :(得分:0)

最简单的方法是在提交按钮中添加名称和值,并检查处理程序中的值:

<button ... name="action" value="add-customer">Create</button>

<button ... name="action" value="add-address">Add</button>

在您的处理程序中,只需检查request.form["action"]参数的值:

if request.method == "POST":
    if request.form.get("action") == "add-customer":
        # Add a customer
    elif request.form.get("action") == "add-address":
        # Add an address