2016-03-31 11 views
1

は私がPOSTクエリデータとAJAXを使用しています。空のQueryDictジャンゴ

しかし、ファイヤーバグは、POST 302action=addまたはaction=removeのパラメータを示します。だから私はなぜ<QueryDict: {}>が空であるのか理解できません。助けてください。

PS。 GETを使うとうまくいきます。

テンプレートshow_event.html

<form id="unfollow" {% if user not in event.users.all %}style="display:none;"{% endif %}> 
    <input type="hidden" value="{{ event.id }}" name="remove"> 
    <button type="submit" class="btn btn-warning btn-block">{% trans "Remove from My events"%}</button> 
</form> 

<form id="follow" {% if user in event.users.all %}style="display:none;"{% endif %}> 
    <input type="hidden" value="{{ event.id }}" name="add"> 
    <button type="submit" class="btn btn-primary btn-block">{% trans "Add to My events"%}</button> 
</form> 

    $(document).on('submit','#unfollow', function(e){ 
     e.preventDefault(); 
     $.ajax({ 
      type:"POST", 
      url:'/event/follow/{{ event.id }}/', 
      data: {'action':'remove'}, 
      success:function(){ 
       $('#unfollow').hide(); 
       $('#follow').show(); 
      } 
     }) 
    }); 

    $(document).on('submit','#follow', function(e){ 
     e.preventDefault(); 
     $.ajax({ 
      type:"POST", 
      url:'/event/follow/{{ event.id }}/', 
      data: {'action':'add'}, 
      success:function(){ 
       $('#follow').hide(); 
       $('#unfollow').show(); 
      } 
     }) 
    }); 

views.py:

def follow (request, event_id): 
    event = get_object_or_404(Event, id=event_id) 
    user = request.user 
    print request.POST 
    if request.method == 'POST': 
     print "post" 
     if request.POST['action'] == 'add': 
      print "add" 
      event.users.add(user) 
      event.save() 
     elif request.POST['action'] == 'remove': 
      print "remove" 
      event.users.remove(user) 
      event.save() 
    return HttpResponse('') 

urls.py:

url(r'^event/follow/(?P<event_id>[0-9]+)/$', 'events.views.follow', name='follow') 
+0

「500」ステータスエラーはありますか?ビューは 'counter_id'をkwargとして受け取り、' event_id'を渡しています。これは同じ見解ですか? – v1k45

+0

@ v1k45申し訳ありませんが私は間違ったビューを貼り付け、今私は私の質問を編集しました。 500エラーがありません – worm2d

答えて

2

EDIT(第二:URLと一致するように、フォームのマークアップを固定):

あなたのマークアップで完全な形を持っているように、実際に、これを行うための簡単な方法があります:

var submitHandler = function(event) { 
    event.preventDefault(); 
    event.stopPropagation(); 

    var $form = $(this); 
    var url = $form.attr("action"); 
    $.post(url, $form.serialize()) 
     .done(function(data) { 
      if (data.following) { 
       $('#follow').hide(); 
       $('#unfollow').show(); 
      } else { 
       $('#follow').show(); 
       $('#unfollow').hide(); 
      } 
     }); 
}; 

$(document).on('submit','#unfollow', submitHandler); 
$(document).on('submit','#follow', submitHandler); 

あなたのマークアップをお読みください:

<form id="unfollow" method="POST" action="{% url 'follow' event_id=event.id %} 
     {% if user not in event.users.all %}style="display:none;"{% endif %}> 
    {% csrf_token %} 
    <input type="hidden" value="remove" name="action"> 
    <button type="submit" class="btn btn-warning btn-block">{% trans "Remove from My events"%}</button> 
</form> 

<form id="follow" method="POST" action="{% url 'follow' event_id=event.id %} 
     {% if user in event.users.all %}style="display:none;"{% endif %}> 
    {% csrf_token %} 
    <input type="hidden" value="add" name="action"> 
    <button type="submit" class="btn btn-primary btn-block">{% trans "Add to My events"%}</button> 
</form> 

あなたのDjangoコード:

@require_http_methods(['POST']) 
def follow (request, event_id): 
    event = get_object_or_404(Event, id=event_id) 
    user = request.user 
    action = request.POST.get('action', None) 
    following = False 
    if action == 'add': 
     event.users.add(user) 
     following = True 
    elif action == 'remove': 
     event.users.remove(user) 
    else: 
     return HttpResponseBadRequest('Unknown action: {}'.format(action)) 
    event.save() 
    return JsonResponse({'following': following}) 

前の返信:

jQueryのバージョンによっては、typeはもう利用できない場合があります。 type: "POST"の代わりにmethod: "POST"をAJAXの設定で使用してみてください。 http://api.jquery.com/jQuery.ajax/

さらに、マークアップをビューとJSで期待するものに合わせるには、method="POST"をフォーム要素に追加します。


サイドノート:(request.POSTがNoneない限り)これは常に動作します

request.POST.get('action', None) 

あなたはこのようQueryDictget()経由の方法にアクセスすることで、より良い非既存のパラメータを処理することができます。パラメータが存在しない場合、デフォルトが返されるか、2番目のパラメータが返されます(この場合はNone)。

request.POST['action'] 

actionが存在しない場合、これはKeyErrorで失敗します。

+0

ありがとうございます。今私はフォームを提出すると(例えばevent_id = 28)、http://127.0.0.1:8000/en/event/follow/28/'の_Unknownアクション:None_テキストが表示されます。そして、querydictは次のようになりました: '' – worm2d

+0

隠された入力フィールドには 'value'と 'name'が混同されていました。私は答えにフォームマークアップのサンプルコードを修正しました。 – Risadinha

+0

素晴らしい!今は動作しますが、提出した後に空白のページが表示されます。空白のページには「:」または「:false」の後に「:」が続きます。あなたの例では、ページの再修正やリダイレクトをせずにフォームを送信する方法は? – worm2d