views:

2152

answers:

3

Newbie request that seems difficult to implement. I would like to make an entire inline formset within an admin change form compulsory.. so in my current scenario when I hit save on an Invoice form (in Admin) the inline Order form is blank. I'd like to stop people creating invoices with no orders associated.

Anyone know an easy way to do that?

Normal validation like (required=True) on the model field doesn't appear to work in this instance.

Thanks!!

+15  A: 

The best way to do this is to define a custom formset, with a clean method that validates that at least one invoice order exists.

class InvoiceOrderInlineFormset(forms.models.BaseInlineFormSet):
    def clean(self):
        # get forms that actually have valid data
        count = 0
        for form in self.forms:
            try:
                if form.cleaned_data:
                    count += 1
            except AttributeError:
                # annoyingly, if a subform is invalid Django explicity raises
                # an AttributeError for cleaned_data
                pass
        if count < 1:
            raise forms.ValidationError('You must have at least one order')

class InvoiceOrderInline(admin.StackedInline):
    formset = InvoiceOrderInlineFormset


class InvoiceAdmin(admin.ModelAdmin):
    inlines = [InvoiceOrderInline]
Daniel Roseman
Perfect solution, thanks
I found that if the delete box is checked, it's possible to validate with 0 orders. See my answer for a revised class that solves that problem.
Dan Breen
Thank you so much for this fix (and Dan for the enhancement).As a possible hint to others I've made a 'class MandatoryInlineFormSet(BaseInlineFormSet)' and then derived InvoiceAdminFormSet from that. In my InvoiceAdminFormSet I have a clean() method that does custom validation but first calls back to MandatoryInlineFromSet.clean().
Kurt
+6  A: 

Daniel's answer is excellent and it worked for me on one project, but then I realized due to the way Django forms work, if you are using can_delete and check the delete box while saving, it's possible to validate w/o any orders (in this case).

I spent a while trying to figure out how to prevent that from happening. The first situation was easy - don't include the forms that are going to get deleted in the count. The second situation was trickier...if all the delete boxes are checked, then clean wasn't being called.

The code isn't exactly straightforward, unfortunately. The clean method is called from full_clean which is called when the error property is accessed. This property is not accessed when a subform is being deleted, so full_clean is never called. I'm no Django expert, so this might be a terrible way of doing it, but it seems to work.

Here's the modified class:

class InvoiceOrderInlineFormset(forms.models.BaseInlineFormSet):
    def is_valid(self):
        return super(InvoiceOrderInlineFormset, self).is_valid() and \
                    not any([bool(e) for e in self.errors])

    def clean(self):
        # get forms that actually have valid data
        count = 0
        for form in self.forms:
            try:
                if form.cleaned_data and not form.cleaned_data.get('DELETE', False):
                    count += 1
            except AttributeError:
                # annoyingly, if a subform is invalid Django explicity raises
                # an AttributeError for cleaned_data
                pass
        if count < 1:
            raise forms.ValidationError('You must have at least one order')
Dan Breen
A: 
Kurt