gpt4 book ai didi

python - Flask 中的表单验证

转载 作者:行者123 更新时间:2023-12-01 18:56:35 26 4
gpt4 key购买 nike

这是我的登录表单的 flask 表单。它不喜欢这种需要大学表单字段和电子邮件表单字段的验证 - 我不断收到的错误是

类型错误:validate_university() 缺少 1 个必需的位置参数:“电子邮件”

class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
password2 = PasswordField(('Repeat Password'), validators=[DataRequired(),EqualTo('password')])
university = SelectField("What University do you go to?",choices=[("soton","University of Southampton"),("solent","Solent
Southampton University")])
email=StringField("What is your university email?",validators=[DataRequired(),Email()])
submitpassword = SubmitField('Submit your password choice')

def validate_username(self, username):
user = User.query.filter_by(username=username.data).first()
if user is not None:
raise ValidationError(('Please use a different username.'))

def validate_university(self,university,email):
uni = University.query.filter_by(code=university.data).first()
if not email.data.endswith(uni.emailend):
raise ValidationError(("Please enter correct university e-mail for the university you attend."))

user = User.query.filter_by(email=email.data).first()
if user is not None:
raise ValidationError(('This e-mail is already in use. Please use a different email address.'))

这是相应的路由python函数:

 @bp.route('/reg1', methods=['GET', 'POST']) 
def reg1():
if current_user.is_authenticated:
return redirect(url_for('main.index'))
form = RegistrationForm()
if form.validate_on_submit():
user = User(email=form.email.data,username=form.username.data)
user.set_password(form.password.data)
db.session.add(user)
db.session.commit()
flash('Congratulations, you are now a registered user!')
return redirect(url_for('auth.reg1'))
return render_template('auth/test.html', title='Register',
form=form,lenform=lenform,postcodes=postcodes)

我该如何修复它?为什么它不允许我为大学验证表提供两个位置参数?谢谢

最佳答案

自定义验证方法必须使用“表单、字段”签名进行定义,这意味着您不能使用带有(self、university、email)参数的验证器。

但是,您可以通过表单参数访问验证器中表单的其他字段:

 def validate_university(form, university):  # <- correct signature
uni = University.query.filter_by(code=university.data).first()
email = form.email # <- access the email field like so
....

关于python - Flask 中的表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58856848/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com