Question

I'm trying to customize the recaptcha inside my form, but I only get a javascript error. Can it be made, or do I have to modify the Flask-WTF code myself?

Was it helpful?

Solution

The example from bbenne10 almost does it except for one little detail: besides putting theme: 'custom' into your config you also must specify the custom_theme_widget: 'recaptcha_widget'. Or whatever will be the id of container where the actual image will be injected and of course the container must be present in your html.

So the final config will look like this:

RECAPTCHA_PUBLIC_KEY = 'key'
RECAPTCHA_PRIVATE_KEY = 'secret'
RECAPTCHA_OPTIONS = dict(
    theme='custom',
    custom_theme_widget='recaptcha_widget'
)

That said there is a hardcoded template that you can override with undocumented RECAPTCHA_TEMPLATE option. Put whatever you like in there and it will be used as base for all themes recaptcha supports.

One more option is to extend from RecaptchaField and make it use your custom RecaptchaWidget this way you can tell it to flask.render_template() with whatever template you like instead of hardcoding html into config.

OTHER TIPS

You can now do this quite easily, actually. First, set (or extend) RECAPTCHA_OPTIONS to a dictionary containing {'theme': 'custom'} (and ensure you're doing app.config.from_object(__name__) or similar), and then ensure that your template contains all of the required DOM elements specified under the Custom Themeing section found here.

Example from a recent site:

# IN YOUR MAIN PYTHON FILE 
RECAPTCHA_OPTIONS = {'theme': 'custom'}
RECAPTCHA_PRIVATE_KEY = 'private_key'
RECAPTCHA_PUBLIC_KEY = 'public_key'
app = Flask(__name__)
app.config.from_object(__name)


# IN THE TEMPLATE (THIS USES TWITTERBOOTSTRAP'S FORM FORMATTING)
<div class='control-group' id='recaptcha_wrapper'>
<label class='control-label'>Enter the words above:</label>
<div class='controls'>
    <input type='text' id='recaptcha_response_field'></input>
    <a id="recaptcha_reload" class="btn" href="javascript:Recaptcha.reload()"><i class="icon-refresh"></i></a>
    <a class="btn recaptcha_only_if_image" href="javascript:Recaptcha.switch_type('audio')">
        <i title="Get an audio CAPTCHA" class="icon-headphones"></i></a>
    <a class="btn recaptcha_only_if_audio" href="javascript:Recaptcha.switch_type('image')">
        <i title="Get an image CAPTCHA" class="icon-picture"></i></a>
    <a class="btn" href="javascript:Recaptcha.showhelp()"><i class="icon-question-sign"></i></a>
    # This causes wtf-forms to drop in the js that populates the above elements
    {{ form.recaptcha() }}
</div>
</div>

After a couple hours trying to get a custom design working I couldn't make it work. Flask-WTF outputs all the html and javascript code for the recaptcha to work. You can't change its behavior without editing the extension code itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top