Now Hiring: Are you a driven and motivated 1st Line IT Support Engineer?

Nov. 29, 2020

Django Simple Captcha Refresh Problem

Although Google recaptcha v3 is very popular these days using Django Simple Captcha module is yet easy to install and use in your projects. The only thing that may turn you into crazy is captcha refresh option of the module. It's not working if you follow the steps in official pages. 

The captcha module includes following view for refresh :

def captcha_refresh(request):
""" Return json with new captcha for ajax refresh request """
if not request.headers.get('X-Requested-With') == 'XMLHttpRequest':
raise Http404

new_key = CaptchaStore.pick()
to_json_response = {
"key": new_key,
"image_url": captcha_image_url(new_key),
"audio_url": captcha_audio_url(new_key) if settings.CAPTCHA_FLITE_PATH else None,
}
return HttpResponse(json.dumps(to_json_response), content_type="application/json")

If the request is not send by ajax than 404 rises every time. And getJSON solution is always end up with 404.

Here is my simple solution to that and it works:

$('.captcha').click(function () {
$.ajax({
type: "POST",
headers:{"X-Requested-With": "XMLHttpRequest"},
url: "/captcha/refresh/",
dataType:"json",
}).done(function (result) {
$('.captcha').attr('src', result['image_url']);
$('#id_captcha_0').val(result['key'])
});
return false;
});

I hope this will shorten the time of anyone looking for the solution.

Stay healthy !



0 Comments
Leave a Comment
captcha