烧瓶WTF未验证



我为我的Flask网站制作了一个WTForms,但它无法验证。我以前做过其他烧瓶WTForms,它们似乎都能工作,但这个不起作用

forms.py

class UpdateForm(FlaskForm):
picture = FileField('Update Profile Picture', validators=[FileAllowed(['jpeg', 'jpg', 'png'])])
username = StringField("Username", validators=[], render_kw={"placeholder": f"Enter username"})
email = StringField("Email", validators=[Email()], render_kw={"placeholder": "Enter email"})
submit = SubmitField('Update')
def validate_username(self, username):
if username.data is not None:
user = User.query.filter_by(username=username.data).first()
if user:
raise ValidationError('Username is already taken.')
def validate_email(self, email):
if email.data is not None:
emailL = User.query.filter_by(email=email.data).first()
if emailL:
raise ValidationError('Email is already taken.')
else:
raise ValidationError('Enter a valid email.')

我以前做过这些方法,但这个方法真的不起作用,甚至不会给我带来错误。

路线.py

@app.route('/settings/edit-profile', methods=['POST', 'GET'])
def edit_profile():
if not current_user.is_authenticated:
flash('This process requires login.', 'failure')
return redirect(url_for('login'))
else:
form = UpdateForm()
if request.method == "POST" and form.validate_on_submit():
print(form.username.data)
print(form.email.data)
pfp = url_for('static', filename=f'pfplib/{current_user.pfp}')
return render_template("Settings/edit-profile.html", pfp=pfp, form=form)
pfp = url_for('static', filename=f'pfplib/{current_user.pfp}')
return render_template("Settings/edit-profile.html", pfp=pfp, form=form)

html文件

<form method="POST" action="" enctype="multipart/form-data">
{{ form.csrf_token }}
{{ form.hidden_tag() }}
<div class="main-content">
<div class="pfp-change">
<div class="container-pfp">
<img src="{{ pfp }}">
<div class="pick-div">
<input type="file">
<i class="fa fa-camera" style="color: #ffffff"></i>
</div>
</div>
</div>
<div class="edit-profile-form">
<div class="username-column">
{{ form.username.label(class="head-label") }}
{% if form.username.errors %}
{{ form.username(class="string-field") }}
{% print(error) %}
<div class="invalid-feedback">
<span>{{ error }}</span>
</div>
{% else %}
{{ form.username(class="string-field", value=current_user.username) }}
{% endif %}
</div>
<div class="email-column">
{{ form.email.label(class="head-label") }}
{{ form.email(class="string-field", value=current_user.email) }}
</div>
</div>
</div>
<div class="submit-div">
{{ form.submit(class="btn-gradient submit-btn-1") }}
</div>
</form>

希望有人能尽快帮忙非常感谢你,如果你能找到一个修复

我不确定是什么导致了你的问题,但我认为我已经做了一件与你试图完成的事情非常相似的事情,所以我可以与你分享对我有效的东西,希望它也对你有效:

我的表单验证

class EditProfileForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
about_me = TextAreaField('About me', validators=[Length(min=0, max=250)])
website_link = StringField('Link your website', validators=[Optional(), URL(message='This is not a valid link, make sure you enter the entire URL')])
submit = SubmitField('Apply Changes')

def __init__(self, original_username, *args, **kwargs):
super(EditProfileForm, self).__init__(*args, **kwargs)
self.original_username = original_username
def validate_username(self, username):
if username.data != self.original_username:
user = User.query.filter(User.username.ilike(self.username.data)).first()
if user is not None:
raise ValidationError('This username is already taken')
if ' ' in username.data:
raise ValidationError('Your username may not contain spaces.')

注意:我没有电子邮件验证,但它将遵循与我的用户名验证相同的形式。

我的路线.py

@app.route('/edit_profile/', methods=['GET', 'POST'])
@login_required
def edit_profile():
form = EditProfileForm(current_user.username)
if form.validate_on_submit():
current_user.username = form.username.data
current_user.about_me = form.about_me.data
current_user.website = form.website_link.data
db.session.commit()
flash('Your changes have been saved.')
return redirect(url_for('main.user', username = current_user.username))
elif request.method == 'GET':
form.username.data = current_user.username
form.about_me.data = current_user.about_me

我的相关HTML

<form action="" method="post">
{{ form.hidden_tag() }}
<p>
<div id="changePPLink"><a href="{{ url_for('main.pic_upload') }}" >Change your profile picture</a><br></div>
<div id="changePasswordLink"><a href="{{ url_for('auth.change_password') }}">Change your password</a><br></div>
{{ form.username.label }}<br>
{{ form.username(size=32, id="usernameField") }}<br>
{% for error in form.username.errors %}
<span style="color: red;">{{ error }}</span>
{% endfor %}
</p>
<p>
{{ form.about_me.label }}<br>
{{ form.about_me(cols=50, rows=4, id="aboutMeField") }}<br>
{% for error in form.about_me.errors %}
<span style="color: red;">{{ error }}</span>
{% endfor %}
</p>
<p>
{{ form.website_link.label }}<br>
{{ form.website_link(size=32, id="websiteField") }} <br>
{% for error in form.website_link.errors %}
<span style="color: red;">{{ error }}</span>
{% endfor %}
</p>
<p>{{ form.submit() }}</p>
</form>

从这里我看不出代码之间有太多差异,但有一些可能会导致您的问题。1.我的表单中有一个init函数2.我在username_validation中对user的查询使用了ilike,这使得它不区分大小写3.我在用户名字段上做了所需的数据,只需输入用户的当前用户名作为表单的默认值,这意味着我不需要检查字段中是否有数据,我只检查数据是否与当前用户名匹配。4.我们的路线略有不同,我只是寻找form.validate_on_submit((,但我想你正在对所有正在工作的表单使用你的方法,所以这可能不是的问题所在

5.我们显示的错误信息是不同的

所以你可以试着把我用过的一些方法输入到你的案例中,看看这是否有帮助。了解当你试图提交表格时会发生什么也可能很有用,无论字段中有什么,它都会提交吗?还是根本不提交?这可能有助于找到问题所在。

我希望这能有所帮助,哪怕只是一点点,如果没有,对不起!

您可以在html表单中添加novalidate属性。也许浏览器验证正在阻止您自己的验证。

最新更新