Ticket #5175: formsets-required_forms-5897.diff

File formsets-required_forms-5897.diff, 2.5 KB (added by Simon Litchfield <simon@…>, 17 years ago)

Adds formset.formset_errors ErrorList if number of required_forms is not met

  • django/newforms/formsets.py

     
    2121    """A collection of instances of the same Form class."""
    2222
    2323    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None):
    24         self.is_bound = data is not None and files is not None
     24        self.is_bound = data is not None or files is not None
    2525        self.prefix = prefix or 'form'
    2626        self.auto_id = auto_id
    2727        self.data = data
     
    6161                    kwargs['files'] = self.files
    6262                add_form = FormClass(**kwargs)
    6363                self.add_fields(add_form, i)
     64                # HACK: Form is empty, lets re-create without data so it doesn't trip validation
     65                if self.data and add_form.is_empty():
     66                    del(kwargs['data'])
     67                    add_form = FormClass(**kwargs)
     68                    self.add_fields(add_form, i)
    6469                add_forms.append(add_form)
    6570            self._add_forms = add_forms
    6671        return self._add_forms
     
    6974    def _get_change_forms(self):
    7075        """Return a list of all the change forms in this ``FormSet``."""
    7176        FormClass = self.form_class
    72         if not hasattr(self, '_add_forms'):
     77        if not hasattr(self, '_change_forms'):
    7378            change_forms = []
    7479            for i in range(0, self.change_form_count):
    7580                kwargs = {'auto_id': self.auto_id, 'prefix': self.add_prefix(i)}
     
    9398    def full_clean(self):
    9499        """Cleans all of self.data and populates self.__errors and self.cleaned_data."""
    95100        is_valid = True
    96         errors = []
     101        errors = ErrorList()
    97102        if not self.is_bound: # Stop further processing.
    98103            self.__errors = errors
    99104            return
     
    134139        if self.orderable:
    135140            cleaned_data.sort(lambda x,y: x[ORDERING_FIELD_NAME] - y[ORDERING_FIELD_NAME])
    136141
     142        if is_valid and self.required_forms > len(cleaned_data):
     143            errors.insert(0, 'asdf')
     144            is_valid = False
     145           
    137146        if is_valid:
    138147            self.cleaned_data = cleaned_data
    139148            self.deleted_data = deleted_data
     
    151160        return '%s-%s' % (self.prefix, index)
    152161
    153162    def is_valid(self):
     163        if not self.is_bound:
     164            return False
    154165        self.full_clean()
    155166        return self._is_valid
    156167
Back to Top