我正在尝试在一个简单的 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/