gpt4 book ai didi

python - 如何在 django 中使用 ajax 形式验证 django-recaptcha

转载 作者:行者123 更新时间:2023-12-05 07:26:16 24 4
gpt4 key购买 nike

我有一个通过 ajax 提交的小型联系表单。我使用 django-recaptcha 添加了一个验证码模块。

当表单通过验证时,它看起来像 captcha 字段丢失了,因为错误消息被添加到 response-html 表单中的验证码字段。如何手动验证验证码字段?还是 message.html 中的 JS 提交了错误的字段/数据?

表单.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']

View .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>

最佳答案

尝试更改 captcha: $('#g-recaptcha-response').val(),g-recaptcha-response: $('#g-recaptcha-response ').val(),

关于python - 如何在 django 中使用 ajax 形式验证 django-recaptcha,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54460354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com