2011-06-11 63 views
0

我有一個用戶列出了他在用戶配置文件中輸入的學校列表。我想讓他有能力刪除他的任何一個條目。獲取請求中密鑰值的最簡單方法.POST

以下是我目前使用的刪除數據庫錄入的方式,基於一鍵在模板中的值:

# in template 
{% for education in educations %} 
    <p>{{ education.school }} 
    <input type="submit" name="delete_{{education.id}}" value="Delete" /></p> 
{% endfor %} 

# in view 

if 'Delete' in request.POST.values(): 
    for key in request.POST.keys(): 
     if key.startswith('delete'): 
      education_id = key[7:] 
    profile.educations.remove(Education.objects.get(id=education_id)) 

是否有更簡單的方式來獲得一個鍵的值,而不是必須遍歷for key in request.POST.keys()?謝謝。

回答

2

表格是免費的。製作更多。

{% for education in educations %} 
    something something 
    <form action="..." method="POST"> 
     <input type="hidden" name="id" value="{{ education.id }}"> 
     <input type="submit" value="Delete"> 
    </form> 
{% endfor %} 

然後在視圖:

id = request.POST['id'] 
profile.educations.remove(...) 

或將ID的GET參數,而不是隱藏字段(只要確保你不使用GET方法的形式 - 那些永遠不應該有任何副作用)。

0

雖然我也同意,形式是很好的,你也可以簡化您的代碼位:

if 'Delete' in request.POST.values(): 
    for key in request.POST.keys(): 
     if key.startswith('delete'): 
      education_id = key[7:] 
    profile.educations.remove(Education.objects.get(id=education_id)) 

可以簡化爲:

for education_id in [key[7:] for key, value in request.POST.iteritems() if value == 'Delete' and key.startswith('delete')]: 
    profile.educations.remove(Education.objects.get(id=education_id)) 

我使用過濾器想出了另一種方法功能,但它更混亂,看起來不如以上優雅。

0
if request.method == 'POST' and 'button_name' in request.POST.keys(): 
     do_something 
elif other button name 
相關問題