Flask WTForms 总是在 validate_on_submit() 上给出 false

sra*_*l07 3 python flask wtforms flask-wtforms

我已经使用 wtforms 创建了一个注册表单。我在其中使用 FormField 以便我不必再次重复表单的某些元素。但是每当我点击提交按钮时,它总是在 validate_on_submit 方法调用时给我错误。不明白为什么会这样。

form.py的如下:

class ProfileInfoForm(Form):
    firstname = TextField('firstname', validators=
                          [validators.Required("Please enter First name.")])
    lastname = TextField('lastname', validators=
                         [validators.Required("Please enter Last name.")])
    email = EmailField('email', validators=
                       [validators.Required("Please enter your valid email.")])
    gender = RadioField('gender', validators=
                        [validators.Required("Please select gender")],
                        choices=[('female', 'Female'), ('male', 'Male')])
    dob = TextField('dob', validators=
                    [validators.Required("Please select date of birth.")])
    languages = SelectMultipleField('languages', choices=[('', '')],
                                    validators=
                                    [validators.Required("Please select\
                                                         atleast one \
                                                         language.")])


class RegistrationForm(Form):
    profilefield = FormField(ProfileInfoForm)
    password = PasswordField('password',
                             validators=
                             [validators.Required("Please enter password."),
                              validators.Length(min=8),
                              validators.EqualTo('confirm_password',
                                                 message='Password and confirm\
                                                 password must match')])
    confirm_password = PasswordField('confirm_password',
                                     validators=
                                     [validators.Required("Please enter\
                                                          confirm password.")])
    tnc = BooleanField('tnc', validators=
                       [validators.Required("Please select Terms and \
                                            Conditions")], default=False)

    submit = SubmitField('Create My Account')
Run Code Online (Sandbox Code Playgroud)

Signup 方法如下:

@module.route('/signup', methods=['GET', 'POST'])
  @handle_error
  def signup():
      if hasattr(g, 'user') and g.user:
          # TODO: do some operations if needed else keep it blank
          return redirect(url_for('index'))
      else:
          signup_form = RegistrationForm()
          # Add choices for the user
          signup_form.profilefield.languages.choices = getLanguages()
          if signup_form.validate_on_submit():
              firstname = signup_form.profilefield.firstname.data
              lastname = signup_form.profilefield.lastname.data
              email = signup_form.profilefield.email.data
              password = signup_form.password.data
              #  confirm_password = signup_form.confirm_password.data
              gender = signup_form.profilefield.gender.data
              dob = signup_form.profilefield.dob.data
              languages = signup_form.profilefield.languages.data
              tnc = signup_form.tnc.data

              payload = {'firstname': firstname, 'lastname': lastname,
                         'email': email, 'password': password, 'gender': gender,
                         'dob': dob, 'languages': languages,
                         'tnc': ('1' if tnc else '0')}
              try:
                  buildApiUrl = BuildApiUrl()
                  response = requests.post(buildApiUrl.getUrl("user", "signup"),
                                           data=payload)

                  if response.status_code == requests.codes.ok:
                      data = json.loads(response.text)
                      if 'status' in data and data['status'] != 200:
                          flash(data['message'], category="error")
                      else:
                          flash(data['message'] +
                                ': Your account is created successfully! ' +
                                'Please login to your account!',
                                category="success")
                          return redirect(url_for('index'))
              except requests.exceptions.RequestException:
                  flash('Internal Server side error occured', category="error")
                  return redirect(url_for('server_error', e='500'))

      return render_template('public/index.html',
                             signup_form=signup_form, login_form=LoginForm())
Run Code Online (Sandbox Code Playgroud)

HTML 表单存在于这里的要点上

仅供参考:我将所有必填字段与所需的实际数据一起放入。当我调用 validate_on_submit() 时仍然出错。我的代码有什么问题?

编辑:getLanguages 是一种从数据库中检索语言并放入选择列表的方法。此功能按预期发生,我可以获得语言列表。

编辑 2:在这里实现一件事。这是由于 FormField 而发生的,因为我通过将 ProfileInfoForm() 的所有字段添加到 RegistrationForm() 方法进行了测试,一切正常,我可以注册。所以 FormField 或我使用它的方式存在一些问题,但不确定哪里出了问题。

发现问题不在于 FormField,而在于我的 ProfileInfoForm()。它总是返回 false。还没有理由,但我认为我可能必须为此编写自己的验证。有什么想法吗?

编辑:

在转储时,我得到了以下信息(此处使用了 pprint):

{'SECRET_KEY': '1e4c35233e50840483467e8d6cfe556c',
 '_errors': None,
 '_fields': {'csrf_token': <wtforms.ext.csrf.fields.CSRFTokenField object at 0x2207290>,
             'dob': <wtforms.fields.simple.TextField object at 0x2207650>,
             'email': <flask_wtf.html5.EmailField object at 0x22074d0>,
             'firstname': <wtforms.fields.simple.TextField object at 0x2207350>,
             'gender': <wtforms.fields.core.RadioField object at 0x2207590>,
             'languages': <wtforms.fields.core.SelectMultipleField object at 0x2207710>,
             'lastname': <wtforms.fields.simple.TextField object at 0x2207410>},
 '_prefix': u'profilefield-',
 'csrf_enabled': True,
 'csrf_token': <wtforms.ext.csrf.fields.CSRFTokenField object at 0x2207290>,
 'dob': <wtforms.fields.simple.TextField object at 0x2207650>,
 'email': <flask_wtf.html5.EmailField object at 0x22074d0>,
 'firstname': <wtforms.fields.simple.TextField object at 0x2207350>,
 'gender': <wtforms.fields.core.RadioField object at 0x2207590>,
 'languages': <wtforms.fields.core.SelectMultipleField object at 0x2207710>,
 'lastname': <wtforms.fields.simple.TextField object at 0x2207410>}
Run Code Online (Sandbox Code Playgroud)

编辑:

我稍微挖掘了一下,发现生成错误是由于缺少 csrf 令牌。但是我已经{{ signup_form.hidden_tag() }}在我的表单模板中包含 了 html。我可以在检查元素时看到生成的 html 中的隐藏标记,并且可以看到带有哈希值的 csrf_token 字段。那么这里有什么问题呢?

sra*_*l07 5

我用以下功能解决了我的问题:

def __init__(self, *args, **kwargs):
    kwargs['csrf_enabled'] = False
    super(ProfileInfoForm, self).__init__(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

我添加了这个功能 ProfileInfoForm()

问题是FormField包括csrf_token字段以及实际表单,即RegistrationForm还包括 csrf_token,所以有两个csrf_token需要验证,只有一个在表单中实际呈现。所以,当 FormField 渲染它时,我禁用csrf_tokenProfileInfoForm它,它有csrf_token = False.

而且RegistrationForm确实有csrf_token还是现在这样的形式仍然是安全有效。

我的猜测是这也需要完成FormField

仅供参考:由于我对 FormField 代码的解释,此解决方案可能是错误的。所以如果我在上述解决方案中错了,请纠正我。