前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用 django-simple-captcha 的方法

使用 django-simple-captcha 的方法

作者头像
小海怪的互联网
发布2019-09-29 16:42:13
1.1K0
发布2019-09-29 16:42:13
举报

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'])
    });

});
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.09.28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Installation
  • Adding to a Form
    • Define the Form
      • Validate the Form
        • Passing arguments to the field
          • Example usage for ajax form
            • Example usage ajax refresh button
            • html:
            • javascript:
              • Example usage ajax refresh
              • javascript:
              相关产品与服务
              验证码
              腾讯云新一代行为验证码(Captcha),基于十道安全栅栏, 为网页、App、小程序开发者打造立体、全面的人机验证。最大程度保护注册登录、活动秒杀、点赞发帖、数据保护等各大场景下业务安全的同时,提供更精细化的用户体验。
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档