使用 django-simple-captcha搞定Django验证码问题

卜昂熙
2023-12-01

 使用 django-simple-captcha

Installation 安装

  1. Install django-simple-captcha via pippip install  django-simple-captcha

    通过 pip 安装 django-simple-captcha: pip Install django-simple-captcha

  2. Add captcha to the INSTALLED_APPS in your settings.py

    在 settings.py 中添加 captcha 到 INSTALLED apps

  3. Run python manage.py migrate

    运行 python manage.py migrate

  4. Add an entry to your urls.py:

    在你的 urls.py 中添加一个条目:

    urlpatterns += [
        url(r'^captcha/', include('captcha.urls')),
    ]
    

Note: PIL and Pillow require that image libraries are installed on your system. On e.g. Debian or Ubuntu, you’d need these packages to compile and install Pillow:

注意: PIL 和 Pillow 要求在您的系统上安装映像库。 在例如 Debian 或 Ubuntu 上,你需要这些软件包来编译和安装 Pillow:

apt-get -y install libz-dev libjpeg-dev libfreetype6-dev python-dev

Adding to a Form 加入表格

Using a CaptchaField is quite straight-forward:

使用 CaptchaField 非常简单:

Define the Form 定义表格

To embed a CAPTCHA in your forms, simply add a CaptchaField to the form definition:

要在表单中嵌入验证码,只需在表单定义中添加一个验证码:

from django import forms
from captcha.fields import CaptchaField

class CaptchaTestForm(forms.Form):
    myfield = AnyOtherField()
    captcha = CaptchaField()

…or, as a ModelForm:

... 或者,作为一个模式表单:

from django import forms
from captcha.fields import CaptchaField

class CaptchaTestModelForm(forms.ModelForm):
    captcha = CaptchaField()
    class Meta:
        model = MyModel

Validate the Form 验证表单

In your view, validate the form as usual. If the user didn’t provide a valid response to the CAPTCHA challenge, the form will raise a ValidationError:

在您的视图中,像往常一样验证表单。 如果用户没有对验证码质疑提供有效的响应,表单将引发验证错误:

def some_view(request):
    if request.POST:
        form = CaptchaTestForm(request.POST)

        # Validate the form: the captcha field will automatically
        # check the input
        if form.is_valid():
            human = True
    else:
        form = CaptchaTestForm()

    return render_to_response('template.html',locals())

Passing arguments to the field 将参数传递到字段

CaptchaField takes a few optional arguements:

Captchafield 采取了一些可选的论点:

  • output_format will let you format the layout of the rendered field. Defaults to the value defined in : 将允许您设置所呈现字段的布局。默认值定义在:CAPTCHA_OUTPUT_FORMAT 验证码输出格式.
  • id_prefix Optional prefix that will be added to the ID attribute in the generated fields and labels, to be used when e.g. several Captcha fields are being displayed on a same page. (added in version 0.4.4) 可选的前缀,将被添加到生成的字段和标签的 ID 属性中,当几个验证码字段显示在同一页面时使用。 (在0.4.4版本中加入)
  • generator Optional callable or module path to callable that will be used to generate the challenge and the response, e.g. 可选的可调用或可调用模块路径,用于生成挑战和响应,例如generator='path.to.generator_function' or 或generator=lambda: ('LOL', 'LOL'), see also ,请参阅Generators and modifiers 生成器和修改器. Defaults to whatever is defined in . 默认为定义在settings.CAPTCHA_CHALLENGE_FUNCT.

Example usage for ajax form Ajax 表单的示例用法

An example CAPTCHA validation in AJAX:

一个用 AJAX 实现的验证码验证示例:

from django.views.generic.edit import CreateView
from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url
from django.http import HttpResponse
import json

class AjaxExampleForm(CreateView):
    template_name = ''
    form_class = AjaxForm

    def form_invalid(self, form):
        if self.request.is_ajax():
            to_json_response = dict()
            to_json_response['status'] = 0
            to_json_response['form_errors'] = form.errors

            to_json_response['new_cptch_key'] = CaptchaStore.generate_key()
            to_json_response['new_cptch_image'] = captcha_image_url(to_json_response['new_cptch_key'])

            return HttpResponse(json.dumps(to_json_response), content_type='application/json')

    def form_valid(self, form):
        form.save()
        if self.request.is_ajax():
            to_json_response = dict()
            to_json_response['status'] = 1

            to_json_response['new_cptch_key'] = CaptchaStore.generate_key()
            to_json_response['new_cptch_image'] = captcha_image_url(to_json_response['new_cptch_key'])

            return HttpResponse(json.dumps(to_json_response), content_type='application/json')

And in javascript your must update the image and hidden input in form

在 javascript 中,你必须更新图像和隐藏的形式输入

Example usage ajax refresh button 示例使用 ajax 刷新按钮

# html:

<form action='.' method='POST'>
    {{ form }}
    <input type="submit" />
    <button class='js-captcha-refresh'></button>
</form>

# javascript:

$('.js-captcha-refresh').click(function(){
    $form = $(this).parents('form');

    $.getJSON($(this).data('url'), {}, function(json) {
        // This should update your captcha image src and captcha hidden input
    });

    return false;
});

Example usage ajax refresh 示例使用 ajax 刷新

# javascript:

$('.captcha').click(function () {
    $.getJSON("/captcha/refresh/", function (result) {
        $('.captcha').attr('src', result['image_url']);
        $('#id_captcha_0').val(result['key'])
    });


});
 类似资料: