我已经定义了以下自定义验证器:
class DataRequiredCustom(object):
def __init__(self, login_signup='signup', message='Data should be provided'):
self.login_signup = login_signup
self.message = message
def __call__(self, form, field):
if self.login_signup == 'signup':
return DataRequiredCustom(message=self.message)
data_required_custom = DataRequiredCustom
现在我的表单类:
class LoginRegistrationForm(Form):
email = StringField('Email', validators=[DataRequired(), Length(1, 64), Email()])
displayname = StringField('displayname', validators=[data_required_custom(self.login_signup), Length(1, 64)])
password = PasswordField('Password', validators=[DataRequired()])
password2 = PasswordField('Confirm password', EqualTo('password'), validators=[data_required_custom(self.login_signup)])
submit_register = SubmitField('Register')
submit_login = SubmitField('Log In')
def __init__(self, login_signup='signup'):
super(LoginRegistrationForm, self).__init__()
self.login_signup = login_signup
如果参数displayname
等于password2
,则不得验证字段login_signup
和'signup'
。不幸的是,将参数self.login_signup
传递给自定义验证类data_required_custom
会产生错误:
NameError:未定义名称“self”。
如何将参数传递给验证表单?
更新
我的模板上有两个以下表格:
<div class="simple-register">
<form action="{{ url_for('auth.signup') }}" method="POST"/>
{{ form.email(type="email") }} <br/>
{{ form.displayname(type="text") }} <br/>
{{ form.password(type="password") }} <br/>
{{ form.password2(type="password") }} <br/>
{{ form.submit_register(type="submit", value="SignUp") }}
</form>
</div>
和
<form action="{{ url_for('auth.login') }}" method="POST">
{{ form.email() }} <br/>
{{ form.password() }} <br/>
{{ form.submit_login(type="submit", value="Login"}}
</form>
答案 0 :(得分:0)
您正在类初始化块中传递self,但尚未存在self。尝试将代码移动到init方法。
class LoginRegistrationForm(Form):
def __init__(self, login_signup='signup'):
super(LoginRegistrationForm, self).__init__()
self.login_signup = login_signup
self.email = StringField('Email', validators=[DataRequired(), Length(1, 64), Email()])
self.displayname = StringField('displayname', validators=[data_required_custom(self.login_signup), Length(1, 64)])
self.password = PasswordField('Password', validators=[DataRequired()])
self.password2 = PasswordField('Confirm password', EqualTo('password'), validators=[data_required_custom(self.login_signup)])
self.submit_register = SubmitField('Register')
self.submit_login = SubmitField('Log In')