Debian Codegraph @

docs/usage.rst

raw
1 Using django-simple-captcha
2 ===========================
3
4 Installation
5 +++++++++++++
6
7 1. Install ``django-simple-captcha`` via pip_: ``pip install django-simple-captcha``
8 2. Add ``captcha`` to the ``INSTALLED_APPS`` in your ``settings.py``
9 3. Run ``python manage.py migrate``
10 4. Add an entry to your ``urls.py`` (import ``include`` from ``django.urls``)::
11
12 urlpatterns += [
13 path('captcha/', include('captcha.urls')),
14 ]
15
16 .. _pip: http://pypi.python.org/pypi/pip
17
18
19 Note: Pillow requires that image libraries are installed on your system. On e.g. Debian or Ubuntu, you'd need these packages to compile and install Pillow::
20
21 apt-get -y install libz-dev libjpeg-dev libfreetype6-dev python-dev
22
23 Adding to a Form
24 +++++++++++++++++
25
26 Using a ``CaptchaField`` is quite straight-forward:
27
28 Define the Form
29 ----------------
30
31
32 To embed a CAPTCHA in your forms, simply add a ``CaptchaField`` to the form definition::
33
34 from django import forms
35 from captcha.fields import CaptchaField
36
37 class CaptchaTestForm(forms.Form):
38 myfield = AnyOtherField()
39 captcha = CaptchaField()
40
41 …or, in a ``ModelForm``::
42
43
44 from django import forms
45 from captcha.fields import CaptchaField
46
47 class CaptchaTestModelForm(forms.ModelForm):
48 captcha = CaptchaField()
49 class Meta:
50 model = MyModel
51
52 Validate the Form
53 -----------------
54
55 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`` and display an error message to the user::
56
57 def some_view(request):
58 if request.POST:
59 form = CaptchaTestForm(request.POST)
60
61 # Validate the form: the captcha field will automatically
62 # check the input
63 if form.is_valid():
64 human = True
65 else:
66 form = CaptchaTestForm()
67
68 return render(request, 'template.html', {'form': form})
69
70 Passing arguments to the field
71 ------------------------------
72
73 ```` takes a few optional arguments:
74
75 * ``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)
76 * ``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 :ref:`generators_ref`. Defaults to whatever is defined in ``settings.CAPTCHA_CHALLENGE_FUNCT``.
77
78 Example usage for ajax form
79 ---------------------------
80
81 An example CAPTCHA validation in AJAX::
82
83 from django.views.generic.edit import CreateView
84 from captcha.models import CaptchaStore
85 from captcha.helpers import captcha_image_url
86 from django.http import HttpResponse
87 import json
88
89 class AjaxExampleForm(CreateView):
90 template_name = ''
91 form_class = AjaxForm
92
93 def form_invalid(self, form):
94 if self.request.is_ajax():
95 to_json_response = dict()
96 to_json_response['status'] = 0
97 to_json_response['form_errors'] = form.errors
98
99 to_json_response['new_cptch_key'] = CaptchaStore.generate_key()
100 to_json_response['new_cptch_image'] = captcha_image_url(to_json_response['new_cptch_key'])
101
102 return HttpResponse(json.dumps(to_json_response), content_type='application/json')
103
104 def form_valid(self, form):
105 form.save()
106 if self.request.is_ajax():
107 to_json_response = dict()
108 to_json_response['status'] = 1
109
110 to_json_response['new_cptch_key'] = CaptchaStore.generate_key()
111 to_json_response['new_cptch_image'] = captcha_image_url(to_json_response['new_cptch_key'])
112
113 return HttpResponse(json.dumps(to_json_response), content_type='application/json')
114
115
116 And in javascript your must update the image and hidden input in form
117
118
119 Example usage ajax refresh button
120 ---------------------------------
121
122 # html::
123
124 <form action='.' method='POST'>
125 {{ form }}
126 <input type="submit" />
127 <button class='js-captcha-refresh'></button>
128 </form>
129
130 # javascript::
131
132 $('.js-captcha-refresh').click(function(){
133 $form = $(this).parents('form');
134
135 $.getJSON($(this).data('url'), {}, function(json) {
136 // This should update your captcha image src and captcha hidden input
137 });
138
139 return false;
140 });
141
142
143 Example usage ajax refresh
144 ---------------------------------
145
146 # javascript::
147
148 $('.captcha').click(function () {
149 $.getJSON("/captcha/refresh/", function (result) {
150 $('.captcha').attr('src', result['image_url']);
151 $('#id_captcha_0').val(result['key'])
152 });
153 });
154
155 Example usage in Django REST Framework
156 ---------------------------------
157
158 To use CAPTCHA in a serializer, simply have your serializer inherit from ``CaptchaSerializer``::
159
160 from captcha.serializers import CaptchaSerializer
161 from rest_framework import serializers
162
163 class CheckCaptchaSerializer(CaptchaSerializer):
164 email = serializers.EmailField()
165
166 …or use ``CaptchaModelSerializer``::
167
168 from captcha.serializers import CaptchaModelSerializer
169 from rest_framework import serializers
170
171 class CheckCaptchaModelSerializer(CaptchaModelSerializer):
172 sender = serializers.EmailField()
173
174 class Meta:
175 model = User
176 fields = ("captcha_code", "captcha_hashkey", "sender")
177
178 ``CaptchaSerializer`` and ``CaptchaModelSerializer`` implement the ``captcha_code`` and ``captcha_hashkey`` fields.
179 In case of invalid captcha or hash code an exception is raised::
180
181 raise exceptions.ValidationError({"error": gettext_lazy("Invalid CAPTCHA")})