我有一个通过 ajax 提交的小型联系表格。我使用django-recaptcha模块添加了一个 recaptcha。
验证表单后,该字段看起来好像captcha
丢失了,因为在 response-html 表单的验证码字段中添加了一条错误消息。如何手动验证验证码字段?还是 JSmessage.html
提交了错误的字段/数据?
表格.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']
视图.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})
消息.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>