1

全文仅在条件为真时验证管理表单

我正在尝试验证表单是否有答案。为了在管理员中验证表单,您需要创建一个新表单并告诉 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
4

1 回答 1

0

这就是我最终基于Django 管理验证对内联表单所做的事情,该验证依赖于所有表单之间的字段总数

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
于 2013-05-24T18:33:35.470 回答