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

标签 python ajax django django-recaptcha

我有一个通过 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/

相关文章:

python - .SetInputConnection() 和 .SetInput() 有什么区别

php - 如何旋转图像和保存图像

django - MEDIA_ROOT 错误 : _getfullpathname: path should be string, 字节或 os.PathLike,不是元组

javascript - jQuery ajax 获取 API 请求附加元素以更正 div

python - 将图像渲染为定义的像素方 block HTML5 Canvas ?

python - 加速python的请求函数

php - 在 JQuery 中传递多个数据

mysql - 如何使用单个 .csv 文件更新数据库(Django)中的多个表?

python - 如何比较Python中两个字符串的差异?

javascript - 获取当前 div 在视口(viewport)中可见