如何为django-simple-captcha创建Ajax刷新

时间:2013-09-24 03:30:22

标签: django captcha

我在基于django的网站上使用django-simple-captcha应用程序,我能够将captcha表单字段集成到我的表单中,但问题是,如何创建一个调用Ajax刷新刷新的按钮点击验证码图片?该应用程序的文档不是很清楚,我试图按照文档中给出的示例,但它不起作用。请帮我解决这个问题?

编辑:这是django包的链接: django-simple-captcha

2 个答案:

答案 0 :(得分:17)

这是javascript中的一个有效实现:

$(function() {
    // Add refresh button after field (this can be done in the template as well)
    $('img.captcha').after(
            $('<a href="#void" class="captcha-refresh">Refresh</a>')
            );

    // Click-handler for the refresh-link
    $('.captcha-refresh').click(function(){
        var $form = $(this).parents('form');
        var url = location.protocol + "//" + window.location.hostname + ":"
                  + location.port + "/captcha/refresh/";

        // Make the AJAX-call
        $.getJSON(url, {}, function(json) {
            $form.find('input[name="captcha_0"]').val(json.key);
            $form.find('img.captcha').attr('src', json.image_url);
        });

        return false;
    });
});

然后你只需要为类captcha-refresh添加一些CSS,也许可以在<a>中放置一个图像,你就可以了!

答案 1 :(得分:0)

选择的答案是使用jQuery而不是JavaScript。

如果仅使用JavaScript,则应改为执行此操作。这还将刷新音频,而不仅仅是django-simple-captcha使用的图像。

https://django-simple-captcha.readthedocs.io/en/latest/advanced.html#rendering

FORM_RENDERER ='django.forms.renderers.TemplatesSetting'

custom_field.html:

    ​
{% load i18n %}
{% spaceless %}

  <label class="control-label">{{ label }}</label>
        <img src="{{ image }}" alt="captcha" class="captcha" />
<br/>
<audio id="audio" controls>
  <source id="audioSource" src="{{ audio }}" />
</audio>
      {% include "django/forms/widgets/multiwidget.html" %}
{% endspaceless %}

Forms.py:

    ​
    class CustomCaptchaTextInput(CaptchaTextInput):
        template_name = 'custom_field.html'
    ​
    class Form(forms.Form):
        captcha = CaptchaField(widget=CustomCaptchaTextInput)
    ​
        def __init__(self, *args, **kwargs):
            super(Form, self).__init__(*args, **kwargs)
            self.fields['captcha'].widget.attrs['placeholder'] = 'Solve the captcha'
            self.fields['captcha'].label = "Captcha"

在body标签的末尾添加它:

<script>
const captchas = document.querySelectorAll('img.captcha')

function headers(options) {
  options = options || {}
  options.headers = options.headers || {}
  options.headers['X-Requested-With'] = 'XMLHttpRequest'
  return options
}

for (const captcha of captchas) {
  const anchor = document.createElement('a')
  anchor.href = '#void'
  anchor.classList.add('captcha-refresh')
  anchor.textContent = 'Refresh'
  anchor.addEventListener('click', ({ target }) => {
    const url = `${window.location.origin}/captcha/refresh/`
    let formEl = target.parentElement

    while (formEl && formEl.tagName.toLowerCase() !== 'form') {
      formEl = formEl.parentElement
    }

    fetch(url, headers())
      .then(res => res.json())
      .then(json => {
        formEl.querySelector('input[name="captcha_0"]').value = json.key
        captcha.setAttribute('src', json.image_url)
        document.getElementById('audioSource').setAttribute('src', json.audio_url)
        document.getElementById('audio').load()
      })
      .catch(console.error)

    return false
  })

  captcha.after(anchor)
}
</script>