我正在尝试使用wtf验证来检查JSON数据中已经存在的useremail。我做了一个检查用户是否存在的函数,但是我遇到了引发ValidatioError的问题。我想将其与StringField消息一起嵌入,例如,当提交表单而不放入数据时,它会收到类似此字段的错误,当用户输入已经存在的电子邮件时,需要以相同的方式显示该错误消息
flash对我有用,但我想将其嵌入StringFields错误
def check_user(self,email):
"""User name check in data base"""
if email != users:
raise ValidationError('Email already registered.')
可以工作但会使应用程序崩溃
def check_user(self,email):
"""User name check in data base"""
if email != users:
self.email.errors.append("Email already registered")
不显示任何错误或反馈
form.py
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo,ValidationError
import json
from flask import redirect,request, url_for, flash
class RegistrationForm(FlaskForm):
username = StringField('Username',
validators = [
DataRequired(message=('Please enter your name!')),
Length(min=3, max=20)
])
email = StringField('Email',
validators = [
DataRequired(message=('Please enter email address!')),
Email(),
Length(min=6)
])
password = PasswordField('Password',
validators = [
DataRequired(message=('Please enter the password')),
Length(min=6,max=20),
])
submit = SubmitField('Sign Up')
# function which check the user already exist in database
def user_already_exit(self, email):
"""Email validation."""
user = User.query.filter_by(email=email.data).first()
if user is not None:
raise ValidationError('Please use a different email address.')
users = {
"aheer": {
"username": "aheer",
"email": "aheer@gmail.com",
"password": "example",
"bio": "Some guy from the internet"
},
"majid": {
"username": "majid",
"email": "clarissa@icloud.com",
"password": "example",
"bio": "Sweet potato is life"
}
}
class LoginForm(FlaskForm):
def check_user(self,email):
"""User name check in data base"""
if email != users:
raise ValidationError('Email already registered.')
email = StringField('Email',
validators = [
DataRequired(message=('Please enter email address!')),
Email(),
Length(min=6)
])
password = PasswordField('Password',
validators = [
DataRequired(message=('Please enter the password')),
Length(min=6,max=20),
])
remember = BooleanField('Remember Me')
submit = SubmitField('Login')
login.html
{% extends "public/templates/public_template.html" %}
{% import "macros/input_macros.html" as im %}
{% block title %} User Login {% endblock %}
{% block main %}
<div class="container">
<div class="row justify-content-center align-items-center pt-3 pb-3">
<div class="col-4">
<div class="card">
<div class="card-body">
<h4 class="text-center">Welcome Back!</h4>
<hr>
<form action="" method="post" novalidate>
{{ form.hidden_tag() }}
<div class="form-group">
{{ im.input(form.email.label) }}
{% if form.email.errors %}
{{ im.input(form.email,placeholder='aheer@gmail.com',class="form-control is-invalid") }}
{% else %}
{{ im.input(form.email,placeholder='aheer@gmail.com',class="form-control") }}
{% endif %}
</div>
<div class="form-group">
{{ im.input(form.password.label) }}
{% if form.password.errors %}
{{ im.input(form.password,class="form-control is-invalid") }}
{% else %}
{{ im.input(form.password,class="form-control") }}
{% endif %}
</div>
<div class="form-check form-check-inline">
{{ form.remember(class="form-check-input") }}
{{ form.remember.label(class="form-check-label") }}
</div>
<div class="form-group">
<input type="submit" class="btn btn-warning btn-block" name="submit" value="Next">
</div>
<hr>
<p class="text-center">Don't have an account ? <a class="ml-1" href="{{ url_for('register') }}">Sign Up</a></p>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
view.py
@app.route("/login", methods=["GET", "POST"])
def login():
get_user_input = request.form
form = LoginForm(get_user_input)
if request.method == "POST" and form.validate_on_submit():
if form.check_user(form.email.data):
flash(f'Welcome {form.email.data}!', 'success')
return redirect(url_for('index'))
else:
user = users[form.email.data]
# if request.method == "POST":
# get_user_input = request.form
# username = get_user_input.get("name")
# password = get_user_input.get("password")
#
# if not username in users:
# print("Username not found")
# return redirect(request.url)
# else:
# user = users[username]
#
# if not password == user["password"]:
# print("Incorrect password")
# return redirect(request.url)
# else:
# session["USERNAME"] = user["username"]
# print("session username set")
# return redirect(url_for('admin'))
return render_template("public/login.html",form=form)
答案 0 :(得分:1)
你很近。 self.email.errors
是验证错误的元组。因此,您应该这样做:
from wtforms import ValidationError
...
def check_user(self,email):
"""User name check in data base"""
if email != users:
self.email.errors += (ValidationError("Email already registered"),)
它从单个ValidationError创建元组并将其添加到您的错误中。