如何在视图中提交包含数组字段和处理的表单?

时间:2016-12-03 15:22:59

标签: python django

我正在尝试使用数组字段提交表单并在Django视图上处理。另外,我想将提交的表单数据与正确的答案表数据进行比较。

question.html:

<form method="post" class="form-inline">
        {% csrf_token %}

        {% for question in questions %}
            <h3>{{ question.title }}</h3>

            <div class="radio">
                <label class="radio-inline">
                    <input type="radio" name="ans{{ question.id }}" value="{{ question.option.0 }}">
                    {{ question.option.0 }}
                </label>
            </div>

            <div class="radio">
                <label class="radio-inline">
                    <input type="radio" name="ans{{ question.id }}" value="{{ question.option.1 }}">
                    {{ question.option.1 }}
                </label>
            </div>

            <div class="radio">
                <label class="radio-inline">
                    <input type="radio" name="ans{{ question.id }}" value="{{ question.option.2 }}">
                    {{ question.option.2 }}
                </label>
            </div>
        {% endfor %}

        <button type="submit" class="btn btn-success" name="ans_submit">Submit</button>
</form>

view.py:

if request.method == 'POST':
  if(request.POST.get('ans_submit')):
        temp_context["submitted_answers"] = request.POST.get("ans", "") # Receive as an array?

期待获得专家意见。

由于

1 个答案:

答案 0 :(得分:1)

实际上发布给您的是ans0ans1...ansN。 所以你想要做的是这样的事情:

answer_fields = [field for field in request.POST if field.startswith('ans')]
for field in answer_fields:
    # Do something with `field`...
    print(request.GET[field])

此外,您可能希望检查后一部分是否为数字,如下所示:

[field for field in request.POST
 if field.startswith('ans') and field[3:].isnumeric()]