来自Django Ajax POST请求的400(错误请求)

时间:2017-01-04 20:49:45

标签: jquery ajax django django-forms django-views

我已经阅读了无数关于此问题的SO主题,但我无法在不产生400(错误请求)控制台错误的情况下提交表单。

此时我已经尝试了一切;列出的选项太多了。我希望有人可以指出我正确的方向。以下是我的代码 - 我已经包含了所有相关的部分。谢谢。

的Django == 1.10.3 jQuery的== 2.2.4

tag.py

@register.inclusion_tag('tags/_plaque-order-form.html', takes_context=True)
def plaque_order_form(context):
    title = 'Plaque Order Form'
    form = PlaqueOrderForm()
    context = {
        'form': form,
        'title': title,
    }
    return context

订购单

<form action="{% url 'contribute:plaque_order_form' %}" method="POST" id="plaqueOrderForm">
  {% csrf_token %}
  {% for field in form %}
    {{ field }}
  {% endfor %}
  <button class="btn btn-black no-margin-bottom btn-small" type="submit" id="plaqueOrderFormBTN">Submit</button>
</form>

地址

urlpatterns = [
    url(r'^$', index, name='home'),
    url(r'^plaque_order_form/$', plaque_order_form, name='plaque_order_form')
]

在模板中插入表单作为标记包含

{% plaque_order_form %}

视图

def plaque_order_form(request):
    if request.method == "POST":
        form = PlaqueOrderForm(request.POST)
        if form.is_valid():
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']
            subject = 'New Plaque Order'
            from_email = settings.DEFAULT_FROM_EMAIL
            recipient_list = [from_email, 'chris@somewhere.net']
            ctx = {
                'subject': subject,
                'first_name': first_name,
                'last_name': last_name
            }

            message = get_template('email_forms/plaque_order_form_email.html').render(Context(ctx))
            msg = EmailMessage(subject, message, from_email=from_email, to=recipient_list)
            msg.content_subtype = 'html'
            msg.send()

            messages.success(request, "Thank you for your order; someone will be in touch with you shortly")

        if form.errors:
            json_data = json.dumps(form.errors)
            return HttpResponseBadRequest(json_data, content_type='application/json')
    else:
        raise Http404

    return HttpResponse(plaque_order_form, mimetype='application/json')

AJAX

<script type="text/javascript">
    $(document).ready(function () {
        var csrftoken = $.cookie('csrftoken');

        function csrfSafeMethod(method) {
            // these HTTP methods do not require CSRF protection
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }

        $.ajaxSetup({
            beforeSend: function (xhr, settings) {
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
        });

        $('#plaqueOrderFormBTN').click(function (e) {
            e.preventDefault();
            var mForm = $('plaqueOrderForm').serialize();
            console.log(mForm);
            $.ajax({
                type: 'POST',
                url: '{% url 'contribute:plaque_order_form' %}',
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(mForm),
                success: function (e) {
                    alert(e)
                },
                error: function (e) {
                    console.log(e);
                }
            });
            return false;
        })
    })
</script>

1 个答案:

答案 0 :(得分:0)

form.errors说你的async/await。不要序列化表单,请尝试

form cannot get values corresponding to fields first_name and last_name from request.POST

将#first_name和#last_name替换为适当的ID。然后可以通过request.POST访问first_name和last name。如果仍然遇到问题,请使用ipdb并放入指定断点处的shell,然后检查request.POST中的post数据。

HTH:)