2015-12-17 10 views
0

我使用Django 1.8.5具有簡單數學驗證碼圖片頁面。問題是如何通過ajax獲取新的驗證碼。在簡單數學CAPTCHA獲取新的驗證碼的Django無需重新加載

comment_form.html:

<div class="form-group"> 
      {{form.captcha}} 
      <span class="error" id="comment-error-captcha"></span> 
     </div> 

forms.py:

class AddCommentForm(forms.ModelForm): 
    captcha = MathCaptchaField(widget=MathCaptchaWidget(question_tmpl=u'<label for="id_captcha_0">What is the answer %(num1)i %(operator)s %(num2)i? </label>')) 
    class Meta: 
     model = Comment 
     fields = '__all__' 
    def __init__(self, *args, **kwargs): 
     super(AddCommentForm, self).__init__(*args, **kwargs) 
     self.fields['captcha'].widget.attrs['class'] = 'form-control' 

我不知道如何獲得新的驗證碼無需重新加載頁面,請幫幫我。

回答

0

解決方案:

class GetNewCaptcha(View): 

def get(self, request, **kwargs): 
    r = {} 
    form = AddCommentForm() 
    token = self.get_or_create_csrf_token(request) 
    r['token'] = token 
    r['captcha'] = str(form['captcha']) 
    return JsonResponse(r) 
0

顯然,你需要使用AJAX重裝,但簡單數學驗證碼不提供這種解決方案。你可以覆蓋這個模塊並添加一個Ajax刷新或使用另一個。我在我的項目中使用django-simple captcha它與阿賈克斯耳目一新已經自帶。 例如:

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; 
}); 
+0

「簡單數學驗證碼不提供這種解決方案」,是你絕對確定? – vadimka

+0

是的,我查過了源代碼 –

相關問題