【问题标题】:How to define a custom error message for RecaptchaField using Bootstrap/wtf template to display it如何使用 Bootstrap/wtf 模板为 RecaptchaField 定义自定义错误消息以显示它
【发布时间】:2020-10-23 15:08:32
【问题描述】:

我正在使用 bootstrap/wtf.html 模板来显示我的表单。我所有的表单输入字段都有 wtform 验证器,允许我定义自定义错误消息。不幸的是,从 flask_wtf 导入的 RecaptchaField 似乎不支持验证器(不是为了验证它,因为它是自动完成的,而是为了定义自定义错误消息)。用户不应该面对技术信息,而只是一个很好的通用信息。什么是定义我的自定义消息的最简单和最干净的选项,仍然 通过使用 bootstrap/wtf 模板?其他选择是停止使用模板呈现 recaptcha 字段,但如果可能的话,我宁愿不这样做。

谢谢!

【问题讨论】:

    标签: recaptcha wtforms flask-wtforms flask-bootstrap


    【解决方案1】:

    创建字段时传递自定义错误消息。例如:

    from flask_wtf.recaptcha import RecaptchaField, Recaptcha
    
    class SignupForm(Form):
        email = EmailField('Email')
        recaptcha = RecaptchaField(validators=[Recaptcha(message="Your custom message")])
        submit = InlineSubmitField('Join Now')
    

    【讨论】:

      【解决方案2】:
      from flask_wtf.recaptcha.fields import RecaptchaField
      from wtforms import Form, BooleanField, StringField, PasswordField, IntegerField, validators
      from flask import render_template, request, redirect, url_for, jsonify
      
      
      class InquiryForm(Form):
            email = StringField('email', [validators.Email(message=(u'invalid email address'))])
            recaptcha = RecaptchaField()
      
      @app.route('/inquiry', methods=['POST','GET'])
      def inquiry():
      form = InquiryForm(request.form)
      if request.method == 'POST' and form.validate():
         return jsonify({'success' : 'Message sent'})
      else:
          # request.form.get('g-recaptcha-response')
          # google recaptcha v2 validate return
          if request.form.get('g-recaptcha-response') and form.recaptcha.errors:
             form.recaptcha.errors.append("System has detected possible suspicious activity, please refresh this page.")
             form.recaptcha.errors.reverse()
          elif form.recaptcha.errors:
             form.recaptcha.errors.append("Need to validate recaptcha")
             form.recaptcha.errors.reverse()
      
          return jsonify(form.errors)
      

      这是我如何附加自定义recaptcha 错误消息

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多