I have the following template:
<script>
$(document).ready(function(){
function captcha() {
$.ajax({
type: "POST",
url: "../captcha",
data:{},
contentType: "application/json",
dataType: "json",
success: function(data) {
alert(data);
},
failure: function(data) {
alert(data);
}
});
}
$(".btn_success").click(captcha);
});
</script>
<form action="./captcha" method="POST">{% csrf_token %}
<div style="color:red">{{ form.non_field_errors }}</div>
{% for field in form.visible_fields %}
{% if
field.name = 'captcha' %}
{{field}}
<input type='submit' id="btn_success" class="btn_success" value = "Invio"/>
{% endif %}
<span>{{ field.errors }}</span>
{% endfor %}
</form>
views.py:
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 forms.py
class MyForm(forms.ModelForm):
sections = forms.ChoiceField(choices=get_sections())
classes = forms.ChoiceField(choices=get_classes())
subclasses = forms.ChoiceField(choices=get_subclasses())
groups = forms.ChoiceField(choices=get_groups())
subgroups = forms.ChoiceField(choices=get_subgroups())
captcha = CaptchaField()
class Meta:
model = MyModel
exclude = []
and ursl.py
url(r'^captcha$', views.CaptchaView.as_view(), name="captcha"),
but the CaptchaView is invoked but not as ajax call. What am i doing wrong??
Thanx in advance
valerio