【问题标题】:StopValidation() In route without raiseing wsgi debugger flask wtfStopValidation() 在路由中没有引发 wsgi 调试器烧瓶 wtf
【发布时间】:2017-04-16 01:47:43
【问题描述】:

我需要覆盖表单中的验证器并将我自己的验证器应用到这个特定的路径。 当上传的图片不是 jpg 时,它不会通过form.validate_on_submit() 检查,模板会在 html 中呈现错误。当我尝试使用时

 raise StopValidation("image1 jpg only")

它会引发调试器并阻止我看到路由。我只是希望它与其他错误一起显示为 field.error。

 @app.route('/test',methods=['GET','POST'])
    def test():
        form.image1.validators=[]
            if request.method == "POST" and  str(request.files['image1'].filename) != "":
                 if request.files['image1'].filename.split('.',1)[1] != "jpg" :
                    raise StopValidation("image1 jpg only")
                    print "image 1 not jpg"


            if form.validate_on_submit():
                # do stuff

        return render_template('test.html')

【问题讨论】:

    标签: python wtforms flask-wtforms


    【解决方案1】:

    如果您只想验证 jpg 文件,请进行自定义验证,而不是使用 StopValidation 并在您的表单中定义。

    def customvalidatorForImage(form, field):
        allowed_file = ['jpg','jpeg','png','gif']  # you can modify your valid file list here
        if form.image.data:
            if form.image.data.split('.',1)[1] not in allowed_file:
                raise ValidationError("Please enter a valid image file")     
    
    
    class MyForm(Form):
        image = FileField("Image" , [customvalidatorForImage, validators.DataRequired("Image is required")])
    

    【讨论】:

    • 如何在路线中做到这一点而不将其添加到类中?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多