【发布时间】:2019-01-27 01:55:03
【问题描述】:
我正在尝试在我的 django 应用程序中实施一项调查。目前我通过手动绘制表单结构的 HTML 来实现它,如下所示:
<!-- Question 1-->
<form method="post" action="{% url 'piuserform' %}">
{% csrf_token %}
<div class="mx-auto">
<h3 class="mb-4">At the time of the accident, the injured party was: </h3>
<label class="radcontainer">The driver of an automobile.
<input type="radio" name="question1" value="The driver of an automobile">
<span class="checkmark"></span>
</label>
<label class="radcontainer">The passenger of an automobile.
<input type="radio" name="question1" value="The passenger of an automobile">
<span class="checkmark"></span>
</label>
<label class="radcontainer">A pedestrian.
<input type="radio" name="question1" value="A pedestrian">
<span class="checkmark"></span>
</label>
</div>
<!-- /Question 1 -->
<!-- question 3-->
<div class="mx-auto pt-5">
<h3 class="mb-4">How many vehicles were involved in the accident?</h3>
<label class="radcontainer">One
<input type="radio" name="question3" value="One">
<span class="checkmark"></span>
</label>
<label class="radcontainer">Two
<input type="radio" name="question3" value="Two">
<span class="checkmark"></span>
</label>
<label class="radcontainer">Three
<input type="radio" name="question3" value="Three">
<span class="checkmark"></span>
</label>
<label class="radcontainer">Four or more
<input type="radio" name="question3" value="Four or more">
<span class="checkmark"></span>
</label>
</div>
<!-- /Question 3 -->
现在我尝试使用 Django forms api 来实现这种效果,但它只会呈现最后一个问题。问卷都是单选按钮,答案字段变化很大。有没有办法自动化这个,所以我可以通过 modelForm 或 Formsetfactory 使用 {{form}} 渲染?我查看了许多文档,但没有一个对我的问题真的很清楚,当我尝试像我说的那样实现表单 api 时,它只会呈现一个问题。非常感谢您的帮助
编辑:
当我尝试实现表单 API 时,我使用了这种方法:
forms.py
blah_choices = [("1", "first"), ("2", "second")]
blah_choices2 = [("3", "third"), ("4", "four")]
class testRadioQuestions(forms.Form):
q1 = forms.ChoiceField(label="Blah blah blah form question",
choices=(blah_choices),
widget=forms.RadioSelect()),
q2 = forms.ChoiceField(label="blah blah some more form question",
choices=(blah_choices2),
widget=forms.RadioSelect())
查看
def other_questionnaire(request):
if request.method == "POST":
print(request.body)
return render(request, 'website/otherQuestions.html', {'form': form})
【问题讨论】:
-
您使用的是模型吗?展示您的视图和表单。
-
我尝试使用 forms.Form。我似乎无法通过至少两个单选按钮得到一组一致的问题。