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

时间:2013-09-10 10:49:47

标签: python flask wtforms flask-wtforms

我使用wtforms创建了一个注册表单。我在其中使用FormField,以便我不必再次重复表单的某些元素。但是每当我点击Submit按钮时,它总是在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')

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())

HTML表单出现在gist here

仅供参考:我将所有必填字段与所需的实际数据放在一起。当我调用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>}

编辑:

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

2 个答案:

答案 0 :(得分:3)

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

def __init__(self, *args, **kwargs):
    kwargs['csrf_enabled'] = False
    super(ProfileInfoForm, self).__init__(*args, **kwargs)

我在ProfileInfoForm()

中添加了此功能

问题是FormField包含csrf_token字段以及实际表单,即RegistrationForm还包括csrf_token,因此有两个csrf_token需要验证并且只有一个实际上以形式呈现。因此,我在csrf_token中停用了ProfileInfoForm,因此当FormField呈现它时,它有csrf_token = False

RegistrationForm现在仍然启用csrf_token,因此表单仍然是安全的。

我的猜测是,这也需要在FormField中完成。

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

答案 1 :(得分:0)

我遇到了同样的问题,并且能够解决它。

问题与以下事实有关:LoginForm具有带有验证程序的ID和用户名,而html表单不需要信息

            <h1>Login</h1>

            <form action="" method="POST"  name="login">
        {{ login_form.csrf_token }}
        {{ login_form.hidden_tag() }}

        <p>
            {{ login_form.email.label }}<br>
            {{ login_form.email(size=64) }}<br>
            {% for error in login_form.email.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>
            {{ login_form.password.label }}<br>
            {{ login_form.password(size=32) }}<br>
            {% for error in login_form.password.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>{{ login_form.remember_me }} Remember Me</p>
{#            <input type="submit" value="Sign In">#}
        <p>{{ login_form.submit() }}</p>
    </form>



class LoginForm(FlaskForm):
    ***# user_id = StringField('user_id',validators=[DataRequired()])
    # user_name = StringField('user_name',validators=[DataRequired(), Length(min=3, max=20)])***
    email = StringField('Email', validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember_me = BooleanField('remember_me', default=False)
    submit = SubmitField('LogIn')