我有一个管理表单,允许最终用户添加测验,测验有答案。编辑测验时,测验答案部分有 4 行用于测验答案。前 3 个编号为 0、1、2,第四个编号为__prefix__
。
例子:
<input name="quizanswer_set-0-text" value="one" class="vTextField" maxlength="255" type="text" id="id_quizanswer_set-0-text" />
<input id="id_quizanswer_set-__prefix__-text" type="text" class="vTextField" name="quizanswer_set-__prefix__-text" maxlength="255" />
处理表单时,它会跳过第四个输入,因为我假设前缀不是它要查找的。
模板代码:
{% for inline_admin_form in inline_admin_formset %}
{{ inline_admin_form.pk_field.field }} {{ inline_admin_form.fk_field.field }}
形式:
class QuizAnswerInlineFormSet(forms.models.BaseInlineFormSet):
def is_valid(self):
# make sure errors are populated
_ = self.errors
return super(QuizAnswerInlineFormSet, self).is_valid()
def clean(self):
super(QuizAnswerInlineFormSet, self).clean()
answer_count = 0
correct_count = 0
for form in self.forms:
if not hasattr(form, 'cleaned_data'):
continue
if not form.cleaned_data:
continue
if not form.is_valid():
continue
if form.cleaned_data[forms.formsets.DELETION_FIELD_NAME]:
continue
answer_count += 1
if form.cleaned_data.get("is_correct", False):
correct_count += 1
if answer_count < 2:
raise ValidationError("Questions must have at least 2 answers")
if correct_count != 1:
raise ValidationError("There must be exactly one correct answer")
有谁知道为什么这是打印__PREFIX__
而不是数字?我需要为此设置什么吗?我最初并没有制作表格,我只是想修复它,我对这种表格并不太熟悉。