python - 如何从 django 的同一表单字段中获取所有输入?(表单域在 HTML 中循环,因此出现不止一次)
问题描述
我正在尝试从同一表单字段中获取所有输入,该表单字段在 HTML 中显示两次,因为它处于循环中(如本例所示)。有什么办法可以做到吗?以下是代码:
HTML
def home(request):
nums = [[3, "", 2, 7, 5, 6, 1, 4, 9],
[1, 4, 5, 2, 3, 9, 6, 7, 8],
[6, 7, 9, 1, 4, 8, 2, 3, 5],
[2, 1, 3, 4, 6, 5, 8, 9, 7],
[4, 5, 6, 8, 9, 7, 3, 1, 2],
[7, 9, 8, 3, 1, "", 4, 5, 6],
[5, 2, 1, 6, 7, 3, 9, 8, 4],
[8, 3, 7, 9, 2, 4, 5, 6, 1],
[9, 6, 4, 5, 8, 1, 7, 2, 3]]
context = {'nums': nums}
if request.method == "POST":
form = SForm(request.POST)
context['form'] = form
if form.is_valid():
num = form.cleaned_data.get('num')
else:
form = SForm()
context['form'] = form
context['range'] = range(9)
return render(request, 's/home.html', context)
表格.py
class SForm(forms.Form):
num = forms.IntegerField(min_value=0, max_value=9, label=False)
HTML.py
{% block content %}
<form method="POST" name="s_form">
{% csrf_token %}
{% for row in nums %}
<tr>
{% for col in row %}
{% if forloop.counter0|divisibleby:"9" %}
<br>
{% endif %}
{% if col != "" %}
<span id="{{ forloop.parentloop.counter0 }} - {{ forloop.counter0 }}">{{ col }}</span>
{% else %}
<span id="{{ forloop.parentloop.counter0 }} - {{ forloop.counter0 }}">{{ form }}</span>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
<div class="container"><button class="btn btn-dark" type="submit" name="button">Submit</button></div>
</form>
{{ num }}
{% endblock %}
但是,我看到的问题是表单被视为一个。在我发布输入后,两个整数字段返回相同的值..(下面的屏幕截图)
任何人都知道我如何从同一个字段中获取两个输入值..?或者是否有办法使用多个字段?非常感谢您!
解决方案
您可以对表单实例使用“前缀”arg
检查这个答案
推荐阅读
- .net-core - 测试 .NET Core 项目时,TeamCity 不会获取 xUnit 测试的结果
- asp.net-mvc - ASP NET MVC - 403 禁止访问被拒绝
- javascript - 在 AngularJS 中为图标添加切换
- php - 无法从php中的多个输入上传文件
- linux - Linux下如何从特定接口发送UDP数据包?
- javascript - Vue警告:未知的自定义元素:
- 您是否正确注册了组件? - react-native - 传递道具的问题
- vb.net - 如何阻止 ListView 在计时器刷新时闪烁?
- go - 一个完成后如何完成所有的goroutine
- javascript - React Native AsyncStorage 甚至在使用 await 和 async 时也会返回 Promise