首页 > 解决方案 > 尽管有 csrf 令牌,但表单未验证

问题描述

我在这里看到了一些类似的问题,但似乎没有一个解决方案在这里适用(问题通常是它缺少 csrf 令牌,这里不是这种情况)。

我有一个包含四个字段的表单 - 3 个带有 SelectField 的下拉列表和一个 StringField - 使用烧瓶 wtforms 构建。我尝试向它添加一个编辑功能,它使用相同的 HTML 模板,但是它没有得到验证(没有进入 form.validate_on_submit 部分)。这是函数的代码:

@app.route('/movements/<int:movement_id>/edit', methods=['GET', 'POST'])   
def edit_movement(movement_id):
    movement = Movement.query.get_or_404(movement_id)
    form = MovementForm()
    if form.validate_on_submit():
        product = Product.query.filter_by(id=form.product.data).first()
        from_location = Location.query.filter_by(id=form.from_location.data).first()
        to_location = Location.query.filter_by(id=form.to_location.data).first()
        if int((Balance.query.filter_by(product = product.name).filter_by(location = from_location.name).first()).balance) < int(form.quantity.data) and from_location.name != "":
           flash("Invalid movement. Quantity of the product is insufficient.")
        else: 
            movement.product_id = product.id
            movement.product = product.name
            movement.from_location_id = from_location.id
            movement.from_location = from_location.name
            movement.to_location_id = to_location.id
            movement.to_location = to_location.name
            movement.quantity = form.quantity.data
            db.session.commit()
            flash('The product movement has been edited!', 'success')
        return redirect(url_for('movements'))
    elif request.method == 'GET':
        form.product.choices = [(product.id,product.name) for product in Product.query.all()]
        form.from_location.choices = [(location.id,location.name) for location in Location.query.all()]
        form.to_location.choices = [(location.id,location.name) for location in Location.query.all()]
        form.quantity.data = movement.quantity
    edit_button = True   
    return render_template('movements.html',form=form, edit_button=edit_button)

这是表单的代码:

class MovementForm(FlaskForm):
    product = SelectField("Product", choices = [])
    from_location = SelectField("From Location", choices = [], coerce=int)
    to_location = SelectField("To Location", choices = [], coerce=int)
    quantity = StringField("Quantity", validators=[DataRequired()])
    add_movement = SubmitField("Add Movement")

这是表格的模型:

class Movement(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    product_id = db.Column(db.Integer, db.ForeignKey('product.id'), nullable=False)
    product = db.Column(db.String(50), nullable=False)
    from_location_id = db.Column(db.Integer, db.ForeignKey('location.id'))
    from_location = db.Column(db.String(50))
    to_location_id = db.Column(db.Integer, db.ForeignKey('location.id'))
    to_location = db.Column(db.String(50))
    quantity = db.Column(db.Integer, nullable=False)
    timestamp = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

表单的 HTML 代码:

<form action="" method="POST">
        {{ form.csrf_token }}
        {{ form.product.label }}
        {{ form.product }}
        {{ form.from_location.label }}
        {{ form.from_location }}
        {{ form.to_location.label }}
        {{ form.to_location }}
        {{ form.quantity.label }}
        {{ form.quantity }}
        {% if edit_button %}
            <input type="submit" value="Edit Movement">
        {% else %}
            {{ form.add_movement }}
        {% endif %}
</form>

标签: pythonhtmlflaskflask-wtforms

解决方案


validate_on_submit是一个方便的函数,它结合了对表单是否已提交的检查(即 POST、PUT、PATCH 或 DELETE)与对form.validate. 如果验证失败,则保存的字典form.errors将填充有用的信息。

调试问题的一个有用步骤是记录(打印)form.errors如果validate_on_submit返回 False 的内容。


推荐阅读