Django Captcha Ajax call not working

179 views
Skip to first unread message

valerio orfano

unread,
Mar 27, 2017, 2:48:17 AM3/27/17
to Django users
I have the following class view taken from documentation:

class CaptchaView(CreateView):
    template_name = "captcha.html"
    form_class = MyForm
   
    def form_invalid(self, form):
        if self.request.is_ajax():
            to_json_response = dict()
            to_json_response['status'] = 0
            to_json_response['form_errors'] = form.errors

            to_json_response['new_cptch_key'] = CaptchaStore.generate_key()
            to_json_response['new_cptch_image'] = captcha_image_url(to_json_response['new_cptch_key'])

            return HttpResponse(json.dumps(to_json_response), content_type='application/json')
        else:
            return HttpResponse("test1", content_type='application/json')

    def form_valid(self, form):
        if self.request.is_ajax():
            to_json_response = dict()
            to_json_response['status'] = 1

            to_json_response['new_cptch_key'] = CaptchaStore.generate_key()
            to_json_response['new_cptch_image'] = captcha_image_url(to_json_response['new_cptch_key'])

            return HttpResponse(json.dumps(to_json_response), content_type='application/json')
        else:
            return HttpResponse("test2", content_type='application/json')


and the following ajax call from template:

    <script type="text/javascript">
        function captcha() {
            $.ajax({
                type: "POST", 
                url: "../captcha",
                contentType: "application/json",
                data: {},
                dataType: "json",
                success: function(data) {
                    alert("success");
                  },
                error: function(data) {
                    alert("not OK");
                  }

                });
        }
    </script>


<input type="button" id="button" onclick="captcha()" value="OK"/>

url(r'^captcha$', views.CaptchaView.as_view(), name="captcha")

Could you please help me to get a proper ajax call? When i click the OK button no success or error message is displayed!!!

Please help me out!!

thanx

valerio


valerio orfano

unread,
Mar 27, 2017, 4:22:55 AM3/27/17
to Django users
Hi, I managed to make an ajax call. But the form is always invalid. IT is like the captcha field passed to the view is always empty.

valerio

Andréas Kühne

unread,
Mar 27, 2017, 5:05:23 AM3/27/17
to django...@googlegroups.com
Hi,

First of all - you are not sending anything to the form. 


            $.ajax({
                type: "POST",  
                url: "../captcha",
                contentType: "application/json",
                data: {},
                dataType: "json",
                success: function(data) {
                    alert("success");
                  },
                error: function(data) {
                    alert("not OK");
                  }

                });

This says that the data sent to the method SHOULD be empty - so the form will always be invalid - there is nothing in it. You probably want to include your form in the data part of the jquery request. Check this for more information: https://api.jquery.com/serialize/.

Secondly - you should also include the CSRF token - otherwise you will get other errors with that eventually - check this for information on how to do that: https://docs.djangoproject.com/en/1.10/ref/csrf/#ajax

Regards,

Andréas

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/32c46521-92be-40be-820a-fb5fe63c4620%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

ludovic coues

unread,
Mar 27, 2017, 5:06:03 AM3/27/17
to django...@googlegroups.com
You Ajax call have a suspicious "data: {}" in the middle of all the arguments.

valerio orfano

unread,
Mar 27, 2017, 7:44:49 AM3/27/17
to Django users
Hi Andreas thak you very much.

I've changed my html with the following:

    <script type="text/javascript">
    $(document).ready(function(){
        $.ajaxSetup({
             beforeSend: function(xhr, settings) {
                 function getCookie(name) {
                     var cookieValue = null;
                     if (document.cookie && document.cookie != '') {
                         var cookies = document.cookie.split(';');
                         for (var i = 0; i < cookies.length; i++) {
                             var cookie = jQuery.trim(cookies[i]);
                             // Does this cookie string begin with the name we want?
                             if (cookie.substring(0, name.length + 1) == (name + '=')) {
                                 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                                 break;
                             }
                         }
                     }
                     return cookieValue;
                 }
                 if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                     // Only send the token to relative URLs i.e. locally.
                     xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
                 }
             }
        });
       
        $(".captcha_form").submit(function(event){
            alert("passa");
            event.preventDefault();
            $.ajax({
                type: "POST", 
                url: "./captcha",
                contentType: "application/json",
                data: $(this).serialize(),

                dataType: "json",
                success: function(data) {
                    alert(data.status);
                  },
                error: function(data) {
                    alert("NOT_OK");
                  }         
                });
        });
    });
    </script>

But my alert returns always status=0 that means invalid form. Any help ?

Thx a lot
Hi,


Regards,

Andréas

To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.

valerio orfano

unread,
Mar 27, 2017, 7:46:06 AM3/27/17
to Django users
btw this is my html:

<form id ="captcha_form" class="captcha_form" action="" method="post">{%csrf_token%}
    <div style="color:red">{{ form.non_field_errors }}</div>
    {% for field in form.visible_fields %}
        {% if field.name = 'captcha' %}
            {{field}}
        {% endif %}
        <span>{{ field.errors }}</span>
    {% endfor %}
    {% for field in form.hidden_fields %}
        {{ field }}
    {% endfor %}
<input type="submit" id="button" class="button"  onclick="captcha()" value="Invio"/>
</form>

Melvyn Sopacua

unread,
Mar 27, 2017, 8:22:44 AM3/27/17
to django...@googlegroups.com

On Monday 27 March 2017 04:46:06 valerio orfano wrote:

> {% if field.name = 'captcha' %}

 

It may not make a difference if you only have one visible field, but this is not a comparison.

--

Melvyn Sopacua

valerio orfano

unread,
Mar 27, 2017, 8:38:15 AM3/27/17
to Django users
Hi Melvyn thanx for ur reply,

this is my form.

class AjaxForm(forms.ModelForm):
    captcha = CaptchaField()
    class Meta:
        model = ajaxModel
        exclude = []

class ajaxModel(models.Model):
    testfield = models.TextField(null=True, blank=True)

If i don't use a ajaxmodel a get an error, so testfield is just a dummy field, just to avoid error.

valerio

valerio orfano

unread,
Mar 27, 2017, 8:43:53 AM3/27/17
to Django users
testfield is where i type my captcha, sorry

Melvyn Sopacua

unread,
Mar 27, 2017, 9:31:38 AM3/27/17
to django...@googlegroups.com

Hi,

 

{% if field.name = 'captcha' %}

 

assigns 'captcha' to field.name and returns if that succeeded. So it's always true. You probably mean:

{% if field.name == 'captcha' %}

 

From what you describe, testfield shows up and your template code says it shouldn't show up.

 

However, when debugging a problem, always reduce to the simplest case, so try with this template code:

 

<form id ="captcha_form" class="captcha_form" action="" method="post">{%csrf_token%}

{{ form }}

<input type="submit" id="button" class="button" onclick="captcha()" value="Invio"/>

</form>

 

> >> Melvyn Sopacua

 

--

Melvyn Sopacua

valerio orfano

unread,
Mar 27, 2017, 11:44:34 AM3/27/17
to Django users
Hi Melvyn 

thanx a lot . I will try tomorrow early morning and will let u know. Thanx. valerio

valerio orfano

unread,
Mar 28, 2017, 3:20:07 AM3/28/17
to Django users
Hi Melvyin still not working



        $(".captcha_form").submit(function(event){
            event.preventDefault();
            var form = $(this)
            alert (form.serialize())
            $.ajax({
                type: "POST", 
                url: "./captcha",
                contentType: "application/json",
                data: form.serialize(),
                dataType: "json",
                success: function(data) {
                    alert(data.status);
                  },
                error: function(data) {
                    alert("NOT_OK");
                  }         
                });
        });
    });
    </script>

<form id ="captcha_form" class="captcha_form" action="./captcha" method="post">{%csrf_token%}
    {{form.as_p}}
<input type="submit" id="button" class="button" value="Invio"/>
</form>



If i make the call using form post method it validates, if use ajax post method with form.serialize() it not validates? The problem for sure ios with ajax call!

Please help out!

rgds valerio
Reply all
Reply to author
Forward
0 new messages