1
我有一個管理員表單允許和最終用戶添加測驗,並且測驗有答案。當您編輯測驗時,測驗答案部分有4行測驗答案。前3個編號爲0,1,2,第四個編號爲__prefix__
。Django Inline Admin Formset額外條目有前綴而不是數字
例子:
<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__
,而不是數量的想法?有什麼我需要爲此設置?我本來沒有製作表格,我只是想解決這個問題,而且我不太熟悉這種形式。