python - 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">!!! 一切正常,感谢您的点击!
解决方案
这是我的代码,它适用于上传用户个人资料图片
@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)
推荐阅读
- excel - 在某些 Excel 版本中无法使用 VBA 更改日期格式
- azure - 在 Azure 应用程序网关后面托管 WCF 服务时如何获取正确的 WSDL URL?
- firebase - 多关系社交网络的 Firestore 数据库结构
- hadoop - 将 HDFS 复制因子降低到 2(或仅 1)对 HBase map/reduce 性能的影响
- css - Tailwind CSS 如何编码像素完美设计
- python - 检查numpy数组的形状
- sql - 更新 sqlserver
- java - 如何在 Spring Boot Thymleaf 模板的内联背景图像 css 标记中添加静态图像?
- asp.net-mvc - 结束响应后重定向到操作不起作用 vb.net mvc 5
- html - 如何将字段集的内容发送到电子邮件地址?