2017-01-04 17 views
0

この問題に関しては無数のSOスレッドを読んでいますが、400(Bad Request)コンソールエラーを出さずにフォームを送信できません。Django Ajaxからの400(Bad Request)POSTリクエスト

私はこの時点ですべてを試しました。リストするオプションが多すぎます。私は誰かが正しい方向に私を指すことができることを願っています。以下は私のコード部分です - 私はすべての関連する部分を含んでいます。ありがとうございました。

ジャンゴ== 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> 

のURL

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, '[email protected]'] 
      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') 

アヤックス

<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

form.errorsはあなたform cannot get values corresponding to fields first_name and last_name from request.POSTことを言います。形式をシリアル化する代わりに、

data = { 
    'first_name': $('#first_name').val(), 
    'last_name': $('#last_name').val() 
} 

を適切なIDに置き換えてみてください。 first_nameとlastnameはrequest.POSTでアクセスできます。引き続き問題が発生する場合は、ipdbを使用して、指定したブレークポイントのシェルにドロップし、request.POSTのポストデータを検査してください。

HTH :)

関連する問題