python - 我有另一种获取复选框列表的方法

标签 python django

大多数人推荐的方法:

files_form_checked_chkbox = request.POST.getlist("file_of_chkbox")
for every_file in files_form_checked_chkbox:
    #do somethig

这是我找到的B方法:

keys = request.POST.keys()
for key in keys:
    if key != "csrfmiddlewaretoken":
        #do somethig

这是我的模板:

<p>List</p>
<form action="..." method="post">
    {% csrf_token %}
    {% for key in keys %}
    <p>
        <input type="checkbox" name="file_of_chkbox" value="{{key}}">
        <a href="..." >{{key}}</a>
    </p>
    {% endfor %}
    <input type="submit" value="Delete files" />
</form>

两种方法都可以做同样的事情。

我明白了。可以肯定的是,A 比 B 好,而且 A 已经解释过很多次了。 我使用请求

但我想了解为什么 B 不被推荐使用 reson。

最佳答案

B 没有做与 A 相同的事情。

在循环 request.POST.keys() 时,您通过获取甚至不需要的 POST 参数做了很多额外的工作。

第一个选项正是执行您需要执行的操作 - 获取复选框值列表。并且它是可读的。

关于python - 我有另一种获取复选框列表的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27652070/

相关文章:

OS X 10.9 SDK 中缺少 Python.framework。为什么?还有 : Workaround?

python - 更改模型管理表单默认值

python - django datetimefield 时区

python - pandas 中的拆分列和命名

python - 如何在模板内部确定图像是否已上传?

django - 为什么 Django 的 test 命令不能识别某些选项?

python - 将后台任务抓取的图像保存到 ImageField

javascript - Javascript 中 iso 格式的日期时间

Python argparse : Does it have to return a list?

python - 什么是 django.utils.datetime_safe,我应该使用它而不是标准日期时间吗?