专栏首页小海怪python学习使用 django-simple-captcha 的方法

使用 django-simple-captcha 的方法

Installation

  1. Install django-simple-captcha via pip: pip install django-simple-captcha
  2. Add captcha to the INSTALLED_APPS in your settings.py
  3. Run python manage.py migrate
  4. Add an entry to your 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:

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

Adding to a Form

Using a CaptchaField is quite straight-forward:

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:

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

An example CAPTCHA validation in 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

Example usage ajax refresh button

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

javascript:

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

});

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Python的高级特征你知多少?

    开篇先说,IEEE Spectrum 于9月6日发布了2019年最受欢迎的编程语言排名,无疑Python蝉联第一,成绩颇为亮眼。从前年开始,Python 就开始...

    CSDN技术头条
  • python测试开发django-62.基于类的视图(APIView和View)

    django中编辑视图views.py有两种方式,一种是基于类的实现,另外一种是函数式的实现方式,两种方法都可以用。 REST框架提供了一个APIView类,它...

    上海-悠悠
  • Python官方最后通牒:Python 2传奇20年将落幕,Python 3接力!

    Python官方非常正式的在官网上发表一封公开信,再次强调Python 2将于2020年元旦停止维护!之后,官方将不会再对任何bug、安全漏洞进行任何更新或者修...

    用户2769421
  • Python写的csv文件,如何让 Excel 双击打开不乱码?

    我们常常需要在 Python 中输出 CSV 文件,但你可能会发现,这些输出的 CSV文件,不能双击使用 Excel 打开,否则中文会变成乱码。例如下面这段代码...

    青南
  • 如何使用 Python批量读取多个文件

    可以看出,它会自动把你输入的内容打印出来,相当于在 whileTrue里面加上了 input。

    青南
  • 如何在 Python 里优雅地读取文件特定行

    如果文件非常大,不能读取到内存中,那么你可能会通过for 循环数行数,数到特定行:

    青南
  • 7 Python 基础: 重点知识点函数的参数难点解答

    定义函数的时候,我们把参数的名字和位置确定下来,函数的接口定义就完成了。对于函数的调用者来说,只需要知道如何传递正确的参数,以及函数将返回什么样的值就够了,函数...

    小Gy
  • PyTorch | 保存和加载模型教程

    原文 | https://pytorch.org/tutorials/beginner/saving_loading_models.html

    材ccc
  • Python写的抢票神器成GitHub热榜第一8400星,竟然还支持候补抢票!

    这很可能是全GitHub最德高望重的购票小助手了,功能一直在更新,且现已支持Python 3.6以上版本。

    用户2769421
  • 8 Python 基础: 面试问你类与实例及其属性还不会吗

    面向对象最重要的概念就是类(Class)和实例(Instance),必须牢记类是抽象的模板,比如Student类,而实例是根据类创建出来的一个个具体的“对象”,...

    小Gy

扫码关注云+社区

领取腾讯云代金券