2016-03-26 32 views
0
def my_view(request, my_id): 
    myItem = Item.objects.get(pk=item_id) 
    context = {'myitem': my item} 
    #This is where I send a POST request from a button named myButton with a value="OK". 
    if request.method == "POST": 
     if 'OK' in request.POST: 
      return render(request, 'url1', context)`enter code here` 
    else: 
     return render(request, 'url2', context) 

以上是我的代碼。如果我打印request.POST,它實際上在字典中具有值OK。然而,Python不執行if子句。所述request.POST我得到錯誤,我的視圖沒有返回HttpResponse對象。它沒有返回

輸出是:

<QueryDict: {u'submit': [u'OK'], u'csrfmiddlewaretoken': [u'#####']}> 
+0

請顯示request.POST的輸出。 –

回答

1

AFAIK,request.POST具有字典結構;它具有關鍵和價值。假設request.POST{'key': 'OK'},條件語句是合適的,如果

if request.POST['key'] == 'OK': 

或者這將是更好的

if request.POST.get('key') == 'OK': 

因爲request.POST.getNone,如果沒有這樣的關鍵。

+0

嗨Leonard2,request.POST中有一個鍵。事實上,完全相同的場景使用不同的形式和視圖。這只是在這裏工作。 – swdon

+0

可能還有其他問題,但request.POST'中的'OK'將導致'False'。您可以檢查{'key'中的''val''''val'}'是否給出'False'。 – Leonard2

+0

哦,我明白了。感謝您的解決方案,我將以這種方式實施並在其工作時接受答案。在單獨的說明中,我何時可以在request.POST條件中使用if'val'? – swdon

相關問題