2011-04-13 16 views

Respuesta

8

Un genérico método FormSet clean() para requerir al menos un artículo:

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

Esto debería funcionar para formsets llano, formsets modelo y en línea formsets modelo.

15

Usando la respuesta de akaihola, aquí es un ejemplo más completo:

Agregar a su 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.') 

Y luego, en su admin.py:

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

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

admin.site.register(Chair, ChairAdmin) 
Cuestiones relacionadas