首页 > 解决方案 > Flask FileAllowed 验证器未检测到错误 - 如何编写自定义验证器?

问题描述

我遇到了与此处概述的相同的问题,但列出的解决方案并不能解决问题。

我正在使用 Flask 创建一个博客网站,并在用户帐户页面上(路线如下所示)


routes.py 进口

from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed
from wtforms import StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
from pgblog.models import User
from flask_login import current_user

routes.py - 账户路由

@app.route("/account", methods=["GET","POST"])
@login_required
def account():
    form = UpdateAccountForm()
    
    if form.validate_on_submit():
        current_user.username=form.username.data
        current_user.email=form.email.data
        db.session.commit()
        flash("Your Account has been Updated.", "success")
        return redirect(url_for("account"))

    elif request.method == "GET":
        form.username.data = current_user.username
        form.email.data = current_user.email

    image_file = url_for("static", filename="profile_pics/" + current_user.image_file)
    return render_template("account.html", title="Account", image_file=image_file, form=form)


用户可以更改他们的个人资料图像。更新账户信息的表格如下图所示:


forms.py 导入

from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed
from wtforms import StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
from pgblog.models import User
from flask_login import current_user

forms.py - UpdateAccountForm

class UpdateAccountForm(FlaskForm):
    username = StringField("Username", validators=[DataRequired(), Length(min=3,max=20)])
    email = StringField("Email", validators=[DataRequired(), Email()])
    picture = FileField("Update Profile Picture", validators=[FileAllowed(['jpg', 'png'], "wrong format!")])

    submit = SubmitField("Update")

    def validate_picture(self, picture):
        if picture.errors:
            raise ValidationError("Images only!")


    def validate_username(self, username):
        if username.data != current_user.username:
            if User.query.filter_by(username=username.data).first():
                raise ValidationError("That username is taken. Please choose a different one.")
    
    def validate_email(self, email):
        if email.data != current_user.email:
            if User.query.filter_by(email=email.data).first():
                raise ValidationError("That email is taken. Please choose a different one.")

错误应显示在以下 div 中:


account.html - 图片上传div

<div class="form-group">
    {{ form.picture.label(class="form-control-label") }}
    {{ form.picture() }}

    {% if form.picture.errors %}
        <ul class="invalid-feedback">{% for error in form.picture.errors %}<li>{{ error }}</li>{% endfor %}</ul>
    {% endif %}
</div>

form.hidden.tag() 包含在 account.html 以及 form.submit() 中

但是,无论文件类型如何,我都不会出现错误!

难道我做错了什么?或者,有没有办法可以编写自己的验证函数?

编辑:我拼错了 enctype="multipart/form-data">!!! 一切正常,感谢您的点击!

标签: pythonflaskjinja2flask-sqlalchemyflask-wtforms

解决方案


这是我的代码,它适用于上传用户个人资料图片

@app.route("/updateaccount", methods=['GET', 'POST']) 
    @login_required 
    def updateaccount():
        form = UpdateAccountForm() 
        if form.validate_on_submit(): 
            if form.picture.data:
                picture_file = save_picture(form.picture.data)
                current_user.image_file = picture_file
            current_user.username = form.username.data 
            current_user.email = form.email.data 
            db.session.commit() 
            flash('Your account has been updated!', 'success') 
            return redirect(url_for('updateaccount')) 
        elif request.method == 'GET':
            form.username.data = current_user.username 
            form.email.data = current_user.email 
        image_file = url_for('static', filename='profile_pics/' + current_user.image_file)
        return render_template('account.html', title='Account',image_file=image_file, form=form)

推荐阅读