我正在尝试验证表单是否有答案。为了在管理员中验证表单,您需要创建一个新表单并告诉 admin.ModelAdmin 类使用该表单。
它是否正确?
我已经创建了一个表单,但现在我不能使用我的内联表单。如果我将它放在 admin.ModelAdmin 中,它仍然会显示,我仍然可以填写该部分,但它不会出现在 clean_data 表单中,如果它在发布数据中。
如何在 QuestionAdminForm 中使用 ChoiceInline?
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 4
#TODO: move?
class QuestionAdminForm(forms.ModelForm):
choices = ChoiceInline
class Meta:
model = Question
def clean(self):
data = self.cleaned_data
#logger.info(data)
choices = self.cleaned_data['choices']
#logger.info(data)
if not self.choices_set.filter(
choice=choices.strip(), is_correct=True).exists():
raise forms.ValidationError("Wrong choice!")
# Always return the cleaned data, whether you have changed it or
# not.
return data
class QuestionAdmin(admin.ModelAdmin):
readonly_fields = ('average', 'last_updated')
#list_display = ["question", "module", "average", "quiz"]
#can't have below because M2M question-> module
#list_display = ["question", "module", "average"]
list_display = ["question", "average"]
list_display_links = ["question"]
list_filter = ['modules__name']
search_fields = ["question", "modules__name", "quiz__name"]
inlines = [ChoiceInline]
actions = [duplicate_questions]
form = QuestionAdminForm