使用Ajax在Django中发送表单数据

时间:2018-10-16 09:49:20

标签: javascript jquery ajax django

我在外部js文件中进行了Baz调用,如下所示:

Either

我认为如下:

ajax

在我的html模板中,我的代码如下:

$(document).ready(function () {
    // Contact form
    let contact_button = $("#contact-button");
    contact_button.on('click', function (e) {
        e.preventDefault();
        let contact_name = $("#contact-name");
        let contact_email = $("#contact-email");
        let contact_message = $("#contact-message");

        let csrftoken = getCookie('csrftoken');
        $.ajax({
            type: "POST",
            url: '/main/contact-us/',
            data: {
                email: contact_email.val(),
                name: contact_name.val(),
                message: contact_message.val()
            },
            success: function (result) {
                hideSpinner();
                resetForm();
                contact_form_success()
            },
            beforeSend: function (xhr, settings) {
                showSpinner();
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            },
            error: function (data) {
                hideSpinner();
                let errors = null;
                if (typeof data.responseJSON !== "undefined") {
                    errors = data.responseJSON;
                }
                contact_form_error(errors)
            }
        })
    });

});

主应用中的def contact_us(request): if request.method == 'POST': contact_us_form = ContactUsForm(request.POST) if contact_us_form.is_valid(): name = contact_us_form.cleaned_data['name'] email = contact_us_form.cleaned_data['email'] message = contact_us_form.cleaned_data['message'] try: subject = '[WEB] A customer sent you a message' body = render_to_string('contact_email.html', {'name': name, 'email': email, 'message': message}) from_email = 'web@bemiddelingscenter.com' to_emails = MAIN_MAIL msg = EmailMultiAlternatives(subject, body, from_email, to_emails) msg.content_subtype = "html" # Main content is now text/html msg.mixed_subtype = 'related' msg.send() return HttpResponse(status=200) except: return HttpResponse(status=404) else: data = { "email_error_exists": len(contact_us_form['email'].errors) > 0, "name_error_exists": len(contact_us_form['name'].errors) > 0, "message_error_exists": len(contact_us_form['message'].errors) > 0, } return JsonResponse(data, status=404) 如下:

<form method="post">
    <div class="mb-3">
        <input id="contact-name" class="form-control g-brd-none g-brd-bottom g-brd-white g-brd-primary--focus g-color-white g-bg-transparent g-placeholder-gray-light-v5 rounded-0 g-py-13 g-px-0 mb-2"
               type="text" placeholder="Name">
    </div>

    <div class="mb-3">
        <input id="contact-email" class="form-control g-brd-none g-brd-bottom g-brd-white g-brd-primary--focus g-color-white g-bg-transparent g-placeholder-gray-light-v5 rounded-0 g-py-13 g-px-0 mb-2"
               type="email" placeholder="Email">
    </div>

    <div class="mb-4">
        <textarea id="contact-message"
                class="form-control g-brd-none g-brd-bottom g-brd-white g-brd-primary--focus g-color-white g-bg-transparent g-placeholder-gray-light-v5 g-resize-none rounded-0 g-py-13 g-px-0 mb-5"
                rows="5" placeholder="Message"></textarea>
    </div>

    <button id="contact-button"
            class="btn u-btn-primary g-bg-secondary g-color-primary g-color-white--hover g-bg-primary--hover g-font-weight-600 g-font-size-12 g-rounded-30 g-py-15 g-px-35"
            type="submit"
            role="button"
            title="{% trans "Send message" %}">
        <span id="btn-send-initial">{% trans "Send message" %}</span>
        <span id="btn-spinner-sending" class="hidden">
            {% trans "Sending" %} <img class="sending-spinner" src="/assets/img/loading.gif" style="width: 20px;" alt="{% trans "Loading" %}"
                                       title="{% trans "Loading" %}"/>
        </span>
    </button>



</form>

在主应用程序中,urls.py如下:

urls.py

但是问题是,每当我单击“发送”按钮时,我都会收到成功消息,而电子邮件未发送。

有什么主意吗?

1 个答案:

答案 0 :(得分:0)

urlpatterns = [
   url(r'^$', index, name="index"),
   url(r'^contact-us/$', contact_us, name="contact_us"),
]