Install django-simple-captcha
via pip: pip install django-simple-captcha
通过 pip 安装 django-simple-captcha: pip Install django-simple-captcha
Add captcha
to the INSTALLED_APPS
in your settings.py
在 settings.py 中添加 captcha 到 INSTALLED apps
Run python manage.py migrate
运行 python manage.py migrate
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
Using a CaptchaField
is quite straight-forward:
使用 CaptchaField 非常简单:
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
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())
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
.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 中,你必须更新图像和隐藏的形式输入
# javascript:
$('.captcha').click(function () {
$.getJSON("/captcha/refresh/", function (result) {
$('.captcha').attr('src', result['image_url']);
$('#id_captcha_0').val(result['key'])
});
});