全文Only validate admin form if condition is true
我正在尝试验证表单是否有答案。 为了验证管理员中的表单,您需要创建一个新表单并告诉admin.ModelAdmin类使用该表单。
这是对的吗?
我创建了一个表单,但现在我无法使用我的内联表单。如果我把它放在admin.ModelAdmin中它仍然显示,我仍然可以填写该部分,但它不会出现在cleaning_data形式,如果它在post数据中。
如何在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
答案 0 :(得分:0)
这是我最终根据Django admin validation for inline form which rely on the total of a field between all forms
做的事情class CombinedFormSet(BaseInlineFormSet):
# Validate formset data here
def clean(self):
super(CombinedFormSet, self).clean()
for form in self.forms:
if not hasattr(form, 'cleaned_data'):
continue
data = self.cleaned_data
valid = False
for i in data:
if i != {}:
if i['is_correct']:
valid = True
if not valid:
#TODO: translate admin?
raise forms.ValidationError("A Question must have an answer.")
# Always return the cleaned data, whether you have changed it or
# not.
return data
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 4
formset = CombinedFormSet