python - 如何在 django 应用程序中获取复选框值

标签 python django twitter-bootstrap python-3.x bootstrap-4

我正在尝试在一个简单的 django 中使用复选框控件应用。代码逻辑似乎很好,但我得到一个空的 fruit列表([None, None])。我不知道为什么它不起作用,任何人都可以指出错误。提前致谢

index.html

<div class="form-check">
<input class="form-check-input" type="checkbox" value="Apple" id="apple">
<label class="form-check-label" for="apple">Apple</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="Mango" id="mango">
<label class="form-check-label" for="mango">Mango</label>
</div> 

View .py
if request.method == 'POST':
    fruit = []
    fruit.append(request.POST.get('apple'))
    fruit.append(request.POST.get('mango'))

最佳答案

正如丹尼尔所说,你必须添加一个 name属性到表单元素,所以它们被提交到服务器。

index.html

<form method="post">
  {% csrf_token %}
  <div class="form-check">
    <input class="form-check-input" type="checkbox" value="Apple" id="apple" name="fruits">
    <label class="form-check-label" for="apple">Apple</label>
  </div>
  <div class="form-check">
    <input class="form-check-input" type="checkbox" value="Mango" id="mango" name="fruits">
    <label class="form-check-label" for="mango">Mango</label>
  </div>
  <button type="submit">Submit</button>
</form>

这样,您可以在 View 中获取水果列表:

View .py
if request.method == 'POST':
    fruits = request.POST.getlist('fruits')
fruits变量将是检查输入的列表。例如。:
['Apple', 'Mango']

关于python - 如何在 django 应用程序中获取复选框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48735726/

相关文章:

python - 在模型上的 save() 覆盖期间查询中没有匹配的对象 - 抛出DoesNotExist错误

python - 从 Django 模型类中解耦域类

twitter-bootstrap - 如何在多个属性上搜索对象(knockout.js+ twitter bootstrap typeahead)?

twitter-bootstrap - Bootstrap div 溢出父级

javascript - Bootstrap 切换菜单加载失败

Python,函数式编程,映射到更高层次

python - PEP8 将变量引用@pytest.fixture 标记为 "shadows name from outer scope"

python - Django错误: django. core.exceptions.ImproperlyConfigured:加载MySQLdb模块时出错

python - ElementTree 命名空间字典不适用于 find() 或 findall()

python : imported packages with 'nested' modules