使用自定义验证程序时,烧瓶表单不显示错误

时间:2018-09-06 18:06:09

标签: python html flask flask-wtforms

我正在为Flask表单输入创建自定义验证器,并且作为示例,我在下面定义了一个函数,该函数检查您是否在输入中包含“ s3://”,如果没有,我想要引发错误。

当我对此进行测试并在输入中省略“ s3://”时,不会引发任何错误。我在做什么错了?

表单类:

from flask_wtf import FlaskForm
from wtforms import StringField, TextField, SubmitField, IntegerField, SelectField, validators
from wtforms.validators import ValidationError
import boto3

# CUSTOM VALIDATOR
def is_s3_uri(form, field):
    if "s3://" not in field.data:
        raise ValidationError('Bucket name must contain full path. Missing "s3://".')

class InputForm(FlaskForm):

    input_uri = StringField('INPUT BUCKET', validators=[validators.required(), is_s3_uri])
    output_uri = StringField('OUTPUT BUCKET', validators=[validators.required(), is_s3_uri])

HTML:

<div class="tab">
    <h3>File Locations:</h3>
    <div class="form-group required">
        {{ form.input_uri.label }}: {{ form.input_uri(placeholder="(e.g. s3://pipeline-run/fastqs/)...", oninput=", this.className = ''") }}
    </div>
        {% if form.input_uri.errors %}
            <ul class="errors">{% for error in form.input_uri.errors %}<li>{{ error }}</li>{% endfor %}</ul>
        {% endif %}
    <div class="form-group required">
        {{ form.output_uri.label }}: {{ form.output_uri(placeholder="(e.g. s3://pipeline-run/results/)...", oninput="this.className = ''") }}
    </div>
        {% if form.input_uri.errors %}
            <ul class="errors">{% for error in form.output_uri.errors %}<li>{{ error }}</li>{% endfor %}</ul>
        {% endif %}
</div>

更新

我还尝试添加一个内置的验证器(例如,使用Length(min=6, max=120)),但这也没有强制执行。

stack_name = StringField('STACK NAME', validators=[Length(min=4, max=120), DataRequired()])

更新2

@app.route('/', methods=['GET', 'POST'])
def pipeline():

   INPUT_URI = ''
   OUTPUT_URI = ''

   form = InputForm(request.form)

   if request.method == 'POST':
       if form.validate_on_submit():
           INPUT_URI = request.form['input_uri']
           OUTPUT_URI = request.form['output_uri']

           # process info

       else:
           flash('Invalid params. Please re-try.', 'danger')
           return redirect(request.path)

   return render_template('pipeline-alt.html', 
                        title='Pipeline Input', 
                        form=form)

更新3 : 使用Jquery表单验证插件

HTML:

<div class="form-group required">
    {{ form.input_uri.label }}: {{ form.input_uri(placeholder="(e.g. s3://pipeline-run/fastqs/)...", oninput=", this.className = ''", name="input_uri") }}
</div>

jQuery:

<script>

$(document).ready(function () {

    $('#regForm').validate({ // initialize the plugin
        rules: {
            input_uri: {
                required: true,
                minlength: 4
            }
        },
        submitHandler: function (form) { // for demo
            alert('valid form submitted'); // for demo
            return false; // for demo
        }
    });

});

</script>

结果:TypeError: html_params() got multiple values for keyword argument 'name'

1 个答案:

答案 0 :(得分:0)

您是否正在验证提交的表单?您没有发布足够的代码,但我会尽力提供帮助。

在呈现的视图中,您应该使用form.validate_on_submit()以便表单得到验证。我看不到您发布的HTML中的整个表单代码,如果是这样,则您缺少将表单发送到服务器进行验证的“提交”按钮。

请发布您的视图(呈现表单)代码

您的表单应在下面示例的方法中使用POST。 您处理表单的视图的示例应该与form.validate_on_submit()

相似
from flask import request
@app.route('/form_route', methods=['GET', 'POST'])
def form_route():
    form = YourFormClass()
    if request.method == 'POST':
        if form.validate_on_submit():
        # validation will be triggered from the if statement and if it validates, it will enter this if block
        # perform actions if the form is valid
        else:
        # do somthing if the form is not valid
    return render_template(form=form)