Django:强制管理员用户在TabularInline中输入至少一个项目

时间:2011-04-13 11:40:45

标签: django admin

在我的对象Chair的管理员中,我有TabularInline个任意数量的Desk个对象。我希望每个Chair始终至少有一个Desk对象与之关联。有没有办法让管理界面强制用户输入至少一个Desk?如果没有输入Desk,则显示错误?

3 个答案:

答案 0 :(得分:16)

使用akaihola的答案,这是一个更完整的例子:

将此添加到您的forms.py:

from django import forms
from django.forms.models import BaseInlineFormSet

class AtLeastOneRequiredInlineFormSet(BaseInlineFormSet):

    def clean(self):
        """Check that at least one service has been entered."""
        super(AtLeastOneRequiredInlineFormSet, self).clean()
        if any(self.errors):
            return
        if not any(cleaned_data and not cleaned_data.get('DELETE', False)
            for cleaned_data in self.cleaned_data):
            raise forms.ValidationError('At least one item required.')

然后,在你的admin.py中:

class DeskInline(admin.TabularInline):
    model = Desk
    formset = AtLeastOneRequiredInlineFormSet

class ChairAdmin(admin.ModelAdmin):
    inlines = [DeskInline,]

admin.site.register(Chair, ChairAdmin)

答案 1 :(得分:9)

要求至少一个项目的通用FormSet clean()方法:

    def clean(self):
        """Check that at least one service has been entered."""
        super(MyFormSet, self).clean()
        if any(self.errors):
            return
        if not any(cleaned_data and not cleaned_data.get('DELETE', False)
                   for cleaned_data in self.cleaned_data):
            raise forms.ValidationError('At least one item required.')

这适用于普通表格集,模型表格集和内联模型表单集。

答案 2 :(得分:0)

Matthew Flanagan有一个很好的例子,说明如何在表单集中要求一个有效的表单:http://code.google.com/p/wadofstuff/wiki/WadOfStuffDjangoFormshttp://wadofstuff.blogspot.com/2009/08/requiring-at-least-one-inline-formset.html 希望能帮到你。