Reputation: 973
I have a small contact form that is submitted via ajax. I added a recaptcha using the django-recaptcha module.
When the form is validated it looks like the captcha
field is missing, because an error message is added to the captcha-field in the response-html form. How can I validate the captcha-field manually? Or is the JS in message.html
submitting the wrong field/data?
forms.py
from django import forms
from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV2Checkbox
from .models import Message
class MessageForm(forms.ModelForm):
"""docstring for MessageForm."""
captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox)
class Meta:
model = Message
fields = ['name', 'from_email', 'message', 'captcha']
views.py
from django.shortcuts import render, redirect
from .forms import MessageForm
def messageView(request):
if request.method == 'POST' and request.is_ajax:
form = MessageForm(request.POST)
if form.is_valid():
message = form.save()
form = MessageForm()
else:
print('form not valid')
return render(request, 'contact/message.html',
{'form': form})
else:
form = MessageForm()
return render(request, 'contact/message.html',
{'form': form})
message.html
{% load crispy_forms_tags %}
<div class="form-container">
<form class="message-form" method="post" action="">
{% csrf_token %}
{{ form|crispy }}
<div class="form-actions">
<button type="submit" name="button" class="btn btn-primary">Send</button>
</div>
</form>
</div>
<script>
$(document).ready(function() {
$('.message-form').on('submit', function(event) {
event.preventDefault();
return create_message();
});
function create_message() {
$.ajax({
url: 'contact/message/',
type: 'POST',
data: {name: $('#id_name').val(),
from_email: $('#id_from_email').val(),
message: $('#id_message').val(),
captcha: $('#g-recaptcha-response').val(),
csrfmiddlewaretoken: '{{csrf_token}}'
},
success: function(json) {
$('.form-container').html(json)
}
})
};
});
</script>
Upvotes: 3
Views: 1028
Reputation: 21
Try change line captcha: $('#g-recaptcha-response').val(),
for g-recaptcha-response: $('#g-recaptcha-response').val(),
Upvotes: 0