首页 > 解决方案 > 如何从 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 %}

但是,我看到的问题是表单被视为一个。在我发布输入后,两个整数字段返回相同的值..(下面的屏幕截图)

在此处输入图像描述(发帖前) 在此处输入图像描述(发帖后)

任何人都知道我如何从同一个字段中获取两个输入值..?或者是否有办法使用多个字段?非常感谢您!

标签: pythondjangoformsfieldsudoku

解决方案


您可以对表单实例使用“前缀”arg

检查这个答案


推荐阅读