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

一时失言乱红尘 2023-06-23 12:52 62阅读 0赞

**使用 django-simple-captcha**

Installation 安装

  1. Install django-simple-captcha via pip: pip 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 中添加一个条目:

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

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:

  1. 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:

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

  1. from django import forms
  2. from captcha.fields import CaptchaField
  3. class CaptchaTestForm(forms.Form):
  4. myfield = AnyOtherField()
  5. captcha = CaptchaField()

…or, as a ModelForm:

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

  1. from django import forms
  2. from captcha.fields import CaptchaField
  3. class CaptchaTestModelForm(forms.ModelForm):
  4. captcha = CaptchaField()
  5. class Meta:
  6. 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:

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

  1. def some_view(request):
  2. if request.POST:
  3. form = CaptchaTestForm(request.POST)
  4. # Validate the form: the captcha field will automatically
  5. # check the input
  6. if form.is_valid():
  7. human = True
  8. else:
  9. form = CaptchaTestForm()
  10. 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 实现的验证码验证示例:

  1. from django.views.generic.edit import CreateView
  2. from captcha.models import CaptchaStore
  3. from captcha.helpers import captcha_image_url
  4. from django.http import HttpResponse
  5. import json
  6. class AjaxExampleForm(CreateView):
  7. template_name = ''
  8. form_class = AjaxForm
  9. def form_invalid(self, form):
  10. if self.request.is_ajax():
  11. to_json_response = dict()
  12. to_json_response['status'] = 0
  13. to_json_response['form_errors'] = form.errors
  14. to_json_response['new_cptch_key'] = CaptchaStore.generate_key()
  15. to_json_response['new_cptch_image'] = captcha_image_url(to_json_response['new_cptch_key'])
  16. return HttpResponse(json.dumps(to_json_response), content_type='application/json')
  17. def form_valid(self, form):
  18. form.save()
  19. if self.request.is_ajax():
  20. to_json_response = dict()
  21. to_json_response['status'] = 1
  22. to_json_response['new_cptch_key'] = CaptchaStore.generate_key()
  23. to_json_response['new_cptch_image'] = captcha_image_url(to_json_response['new_cptch_key'])
  24. 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:

  1. <form action='.' method='POST'>
  2. {
  3. { form }}
  4. <input type="submit" />
  5. <button class='js-captcha-refresh'></button>
  6. </form>

# javascript:

  1. $('.js-captcha-refresh').click(function(){
  2. $form = $(this).parents('form');
  3. $.getJSON($(this).data('url'), {}, function(json) {
  4. // This should update your captcha image src and captcha hidden input
  5. });
  6. return false;
  7. });

Example usage ajax refresh 示例使用 ajax 刷新

# javascript:

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

发表评论

表情:
评论列表 (有 0 条评论,62人围观)

还没有评论,来说两句吧...

相关阅读

    相关 django滑动验证

    一、概述 最近用django写了一个后台系统,使用的是验证码方式。但是开发人员抱怨,输入验证太麻烦,还有可能出错,太影响效率了。 是否可以用滑动验证码,一拖动就可以了!