如何在Django中使用Ajax表单验证django-recaptcha

时间:2019-01-31 12:13:40

标签: python ajax django django-recaptcha

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

验证表单后,似乎缺少captcha字段,因为错误消息已添加到response-html表单的验证码字段中。如何手动验证验证码字段?还是message.html中的JS提交了错误的字段/数据?

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>

0 个答案:

没有答案