我正在尝试编写一个表单来编写问题并为问题提供选择。选择的单选按钮表示问题的正确选择。布尔字段Choice.is_correct_choice
表示选择是否是问题的正确选择。
在我的模板中,我有以下内容:
{% for form in choice_form %}
<input type="radio" name="selected_choice_number" value="{{ forloop.counter }}"> {{ form.as_p }}
{% endfor %}
choice_form是包含选项的formset。
而且,在views.py中,我有:
form = request.POST
selected_choice_number = int(form['selected_choice_number'])
print(form["selected_choice_number"])
for counter, form in enumerate(choice_form, start=1):
choice = form.save(commit=False)
choice.problem = problem
choice.is_choice_correct = (selected_choice_number == counter)
print(choice.choice_text, choice.is_choice_correct)
choice.save()
choice_form formset是以下形式的formset的实例:
class MCQChoiceForm(forms.ModelForm):
class Meta:
model = Choice
fields = ['choice_text']
labels = {
'choice_text': "",
}
widgets = {
"choice_text": forms.Textarea(),
}
这个工作正常,但它看起来很难看,特别是模板中的代码。如何改进代码,以便用Python(表单/视图)而不是模板编码单选按钮逻辑?