gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:34:39 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com