[英]Django Select a valid choice.[...] is not one of the available choices. in a dynamically generated form
I am making a quiz application and I want to make a dynamic form to render the questions.我正在制作一个测验应用程序,我想制作一个动态表格来呈现问题。
I use two widgets in my questions ( widgets.RadioSelect
and widgets.CheckboxSelectMultiple
) to render the question's choices.我在我的问题中使用了两个小部件( widgets.RadioSelect
和widgets.CheckboxSelectMultiple
)来呈现问题的选择。 when I submit the form I get the following error:当我提交表单时,出现以下错误:
Select a valid choice.['option1', 'option2'] is not one of the available choices.选择一个有效的选项。['option1', 'option2'] 不是可用选项之一。
rises only from questions with the second widget eg: widgets.CheckboxSelectMultiple
.仅来自第二widgets.CheckboxSelectMultiple
部件的问题,例如: widgets.CheckboxSelectMultiple
。 The RadioSelect submits successfully. RadioSelect 提交成功。
forms.py:表格.py:
class QuestionForm(forms.Form):
def __init__(self, fields, *args, **kwargs):
super(QuestionForm, self).__init__(*args, **kwargs)
# Init form fields
for field in fields:
self.fields[field['name']] = forms.ChoiceField(
label=field['label'],
choices=field['choices'],
widget=getattr(widgets, field['widget']),
required=False
)
views.py:视图.py:
def quiz(request, quiz_id):
quiz = get_object_or_404(QCM, pk=quiz_id)
if request.method == 'POST':
if request.POST['action'] == 'Save':
form = QuestionForm(data=request.POST)
if form.is_valid():
print('form is valid :)')
form.save()
else:
print('form is not valid :(')
else:
form = QuestionForm()
context = {
'form': form,
}
return render(request, 'quiz/quiz.html', context)
quiz.html测验.html
{% extends "quiz/first.html" %}
{% load staticfiles %}
{% block main %}
<form method="POST" class="form-horizontal" id="qcm_form" enctype="multipart/form-data">
<div class="row">
<div class="col-md-12">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label class="field-label" for="id_{{ field.name }}">{{ field.label }}{% if field.field.required %} <span class="text-danger">*</span>{% endif %}</label>
{{ field }}
</div>
{% endfor %}
</div>
</div>
<input type="submit" class="btn btn-primary" name="action" value="Save">
</form>
{% endblock main %}
Any help would be much appreciated.任何帮助将非常感激。
The problem was in the forms.Field
subclass I used ( ChoiceField
) witch accepts only string values not lists.问题出在我使用的forms.Field
子类( ChoiceField
)中,女巫只接受字符串值而不是列表。 And that explains why radio buttons work because they submit a string value and the CheckboxSelectMultiple didn't because it submits a list.这解释了为什么单选按钮会起作用,因为它们提交了一个字符串值,而 CheckboxSelectMultiple 不起作用,因为它提交了一个列表。
I have modified my generated fields list to include the forms.Field
subclass as well.我已经修改了我生成的字段列表以包含forms.Field
子类。
When I have multiple values I use forms.MultipleChoiceField
and if it's just one value I assign forms.ChoiceField
.当我有多个值时,我使用forms.MultipleChoiceField
,如果它只是一个值,我分配forms.ChoiceField
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.