在request.POST中获取密钥值的最简单方法

时间:2011-06-11 22:52:28

标签: django django-forms

我有一个用户,他已经在他的userprofile中输入了一系列学校。我想让他能够删除他的任何一个条目。

以下是我目前用于删除数据库条目的方式,具体取决于模板中键的值:

# 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()?谢谢。

3 个答案:

答案 0 :(得分: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方法 - 这些应该永远不会有任何副作用)。

答案 1 :(得分: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))

我想出了另一种使用过滤功能的方法,但它比以上更加简洁,看起来不那么优雅。

答案 2 :(得分:0)

if request.method == 'POST' and 'button_name' in request.POST.keys():
       do_something
elif other button name