【问题标题】:Flask FileAllowed validator not detecting errors - How to write a custom validator?Flask FileAllowed 验证器未检测到错误 - 如何编写自定义验证器?
【发布时间】:2020-11-02 23:57:03
【问题描述】:

我遇到了与here 相同的问题,但列出的解决方案不能解决问题。

我正在使用 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">!!!一切正常,感谢您的点击!

【问题讨论】:

    标签: python flask jinja2 flask-sqlalchemy flask-wtforms


    【解决方案1】:

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

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

    【讨论】:

    • 您好,谢谢您的回复!最终,错误是我的 HTML 中的一个错字。我拼错了 multipart iirc。
    • 图片文件是保存在目录还是数据库中?
    • 我保存在数据库中
    猜你喜欢
    • 1970-01-01
    • 2021-10-13
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    相关资源
    最近更新 更多