开发者

Django: Forcing admin users to enter at least one item in TabularInline

In my admin for an object Chair I have a TabularInline for an arbitrary number of Desk objects. I want every Chair to always have开发者_如何学Go at least one Desk object associated with it. Is there a way to make the admin interface force the user to enter at least one Desk? Like show an error if no Desk is entered?


Using akaihola's answer, here is a more complete example:

Add this to your 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.')

And then, in your admin.py:

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

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

admin.site.register(Chair, ChairAdmin)


A generic FormSet clean() method for requiring at least one item:

    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.')

This should work for plain formsets, model formsets and in-line model formsets.


Matthew Flanagan has a great example of how to require one valid form in a formset: http://code.google.com/p/wadofstuff/wiki/WadOfStuffDjangoForms and http://wadofstuff.blogspot.com/2009/08/requiring-at-least-one-inline-formset.html Hope that helps you out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜