问题描述
||
我有一个用户,他在用户个人资料中输入了学校列表。我想让他能够删除他的任何条目。
以下是根据模板中键的值,当前用于删除数据库条目的方式:
# 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()
?谢谢。
解决方法
表格是免费的。制作更多。
{% 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方法-绝不应该有任何副作用)。
, 尽管我也同意表单很好,但是您也可以稍微简化一下代码:
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))
我想出了另一种使用过滤器功能的方法,但是它比以前的方法更加混乱,看起来也不那么优雅。
, if request.method == \'POST\' and \'button_name\' in request.POST.keys():
do_something
elif other button name