StopValidation In route without raiseing wsgi debugger flas

2024-04-23 22:18:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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

 raise StopValidation("image1 jpg only")

它引发了它,它阻止我看到路线。我只想把它显示成字段错误还有其他的错误。你知道吗

 @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')

Tags: testformonlyifonrequesthtml错误
1条回答
网友
1楼 · 发布于 2024-04-23 22:18:12

如果您只想验证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")])

相关问题 更多 >