[セットトップ]django-simple-captcha使用及び動的ajax更新検証追加


django-simple-captchaの使用及び動的ajaxの更新、検証を追加します.
django-simple-captchaはよく使われる検証コードを追加するpackageですが、ajaxの動的なリフレッシュや検証などの問題があります.公式サイトでは詳細な説明はありません.ここで簡単に紹介します.本論文のコードはpython 3.4、django 1.8を使用しています.他のバージョンも参照できます.
django-simple-captcha使用
  • pip install django-simple-captchaをインストールして、pip install Pillow
  • .captchaをsettings.pyのINSTALLED_に加入する.APPS
  • python manager.py migrationsとpython manage.py migrateを実行します.以前のバージョンはpython manage.py syncdb
  • を使用する必要があります.
  • urlルーティングはurls.pyのurlpatterns
  • に加入する.
    urlpatterns = [
        url(r'^captcha/', include('captcha.urls')) #           
        url('^some_view/', finder.views.some_view) # finder   app  ,          import finder.views
    ]
  • forms.pyに
  • を追加します.
    from django import forms
    from captcha.fields import CaptchaField
    
    class CaptchaTestForm(forms.Form):
        title = forms.CharField(max_length=100, label='title')
        price = forms.FloatField(max_value=100, label='price') #           , title price  
        captcha = CaptchaField() #          ,     
    
  • は、view.pyに以下のコード
  • を追加します.
    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
                return HttpResponse(form.cleaned_data) #         ,         
            else:
                return HttpResponse('validate error')
        else:
            form = CaptchaTestForm()
    
        return render_to_response('template.html',locals()) 
    # Python       locals() 。                      ,
  • templates.の内容
  • 
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
    <form action='.' method='POST'>
        {% csrf_token %}
        {{ form }}
    <input type="submit" value='submit' />
    </form>
    </body>
    </html>
    
    これで開けますhttp://localhost:8000/some_view/は検証コードを含むtitle、priceのフォームがあります.
    ここでは、検証コードの生成原理を簡単に説明します.django-simple-captchaはsessionを使って検証コードを保存していません.データベースを使って、まずテーブルcaptchaを生成します.captchastoreには、以下のフィールドが含まれています.
            # challenge = models.CharField(blank=False, max_length=32) #               1+1
            # response = models.CharField(blank=False, max_length=32) #                           2
            # hashkey = models.CharField(blank=False, max_length=40, unique=True) # hash 
            # expiration = models.DateTimeField(blank=False) #     
    開くhttp://localhost:8000/some_view/隠しフィールドがあることが分かります.
    この隠しフィールドはhashkeyの値です.djangoはhashkeyをページに送り、hiddenとして存在します.フォームを提出する時hashkeyは入力した検証コードと一緒にpostをサーバに送ります.この時、サーバーはcaptcha_を検証します.captchastoreテーブルのhashkeyに対応するレスポンスは入力された検証コードと一致しているかどうか、一致すれば正しく、一致しない場合はエラーを返します.
    django-simple-captcha ajaxダイナミック検証
    コード生成の原理を了解しました.ajaxを使って動的検証ができませんでした.
  • コードをviews.py
  • に書き込みます.
    def ajax_val(request):
        if  request.is_ajax():
            cs = CaptchaStore.objects.filter(response=request.GET['response'],
                                         hashkey=request.GET['hashkey'])
            if cs:
                json_data={'status':1}
            else:
                json_data = {'status':0}
            return JsonResponse(json_data)
        else:
            # raise Http404
            json_data = {'status':0}
            return JsonResponse(json_data) #     from django.http import JsonResponse
  • はurls.pyに書き込み、上のviewのためにルーティング
  • を設定する.
    urlpatterns = [
        url(r'^captcha/', include('captcha.urls')) #           
        url('^some_view/', finder.views.some_view), # finder   app  ,          import finder.views
        url('^ajax_val/', finder.views.ajax_val, name='ajax_val'), #    
    ]
  • tempalted.はajax
  • を書き込みます.
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
    <form action='.' method='POST'>
        {% csrf_token %}
        {{ form }}
    <input type="submit" value='submit' />
    </form>
    
    
        <script> $(function(){ $('#id_captcha_1').blur(function(){ // #id_captcha_1     id,               json_data={ 'response':$('#id_captcha_1').val(), //           id_captcha_0    'hashkey':$('#id_captcha_0').val() } $.getJSON('/ajax_val', json_data, function(data){ //ajax   $('#captcha_status').remove() if(data['status']){ //status  1      , status  0      ,               $('#id_captcha_1').after('<span id="captcha_status" style="color:blue">*     </span>') }else{ $('#id_captcha_1').after('<span id="captcha_status" style="color:red">*     </span>') } }); }); }) </script>
        <script src='./jquery.js'></script>     jquery.js
    </body>
    </html>
    これでdjango-simple-captchaのajaxダイナミック検証を完成しました.
    django-simple-captchaa jaxリフレッシュ
    現在の検証コードがよく見えないなら、更新してもいいです.これはajaxでやります.jango-simple-captcha自体はリフレッシュページを提供しています./refshはcaptcha/urls.pyにあります.
    url(r'refresh/米ドル)、views.cpatch fresh、name='captcha-refsh'
    ここは私達自身のurls.pyの中で処理をしないで、直接/captcha/refresh/views.cpatchを使ってもいいです.refreshソース
    #                 
    def captcha_refresh(request):
        """ Return json with new captcha for ajax refresh request """
        if not request.is_ajax(): #    ajax  
            raise Http404
    
        new_key = CaptchaStore.generate_key()
        to_json_response = {
            'key': new_key,
            'image_url': captcha_image_url(new_key),
        }
        return HttpResponse(json.dumps(to_json_response), content_type='application/json')
    ソースコードを読むことによって、私達はviews.cptch a_を発見しました.refreshはajaxのみの提出を受けて、最後にkeyとイメージアップに戻ります.urlのjsonデータ、ここのkeyはhashkeyで、私達がidを書くことを必要とします.captcha_1の隠しフィールド、イメージエリアurlはコード画像の新しいurlを検証するために、ここでajaxに参加して更新して、検証コードのピクチャーをクリックして更新を実現して、最新のtempaltet.コードはそうです.
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
    <form action='.' method='POST'>
        {% csrf_token %}
        {{ form }}
    <input type="submit" value='submit' />
    </form>
    
    
        <script> $(function(){ $('.captcha').css({ 'cursor': 'pointer' }) # ajax    $('.captcha').click(function(){ console.log('click'); $.getJSON("/captcha/refresh/", function(result){ $('.captcha').attr('src', result['image_url']); $('#id_captcha_0').val(result['key']) }); }); # ajax     $('#id_captcha_1').blur(function(){ // #id_captcha_1     id,               json_data={ 'response':$('#id_captcha_1').val(), //           id_captcha_0    'hashkey':$('#id_captcha_0').val() } $.getJSON('/ajax_val', json_data, function(data){ //ajax   $('#captcha_status').remove() if(data['status']){ //status  1      , status  0      ,               $('#id_captcha_1').after('<span id="captcha_status" style="color:blue">*     </span>') }else{ $('#id_captcha_1').after('<span id="captcha_status" style="color:red">*     </span>') } }); }); }) </script>
        <script src='./jquery.js'></script>     jquery.js
    </body>
    </html>
    
    ok、今私達はdjango-simple-captchaの使用を完成しました.自分で勉強した心得はもっと多くの仲間に役立ちたいです.
    彼女に感謝します.彼女はいつもそばにいてくれて、私を支えてくれます.