如何解决在request.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()
?谢谢。
解决方法
表格是免费的。制作更多。
{% 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。