Ticket #5153: ticket5153.diff

File ticket5153.diff, 2.5 KB (added by Christopher Lenz <cmlenz@…>, 17 years ago)

Patch that adds ensure_valid option

  • django/newforms/models.py

     
    2929            continue
    3030        form.initial[f.name] = f.value_from_object(instance)
    3131
    32 def save_instance(form, instance, fields=None, fail_message='saved', commit=True):
     32def save_instance(form, instance, fields=None, fail_message='saved', commit=True,
     33                  ensure_valid=True):
    3334    """
    3435    Saves bound Form ``form``'s cleaned_data into model instance ``instance``.
    3536
    3637    If commit=True, then the changes to ``instance`` will be saved to the
    37     database. Returns ``instance``.
     38    database. If ensure_valid=False, the changes will be saved even if the form
     39    has validation errors.
     40   
     41    Returns ``instance``.
    3842    """
    3943    from django.db import models
    4044    opts = instance.__class__._meta
    41     if form.errors:
     45    if not ensure_valid:
     46        form.full_clean(ensure_valid=False)
     47    elif form.errors:
    4248        raise ValueError("The %s could not be %s because the data didn't validate." % (opts.object_name, fail_message))
    4349    cleaned_data = form.cleaned_data
    4450    for f in opts.fields:
  • django/newforms/forms.py

     
    170170        """
    171171        return self.errors.get(NON_FIELD_ERRORS, ErrorList())
    172172
    173     def full_clean(self):
     173    def full_clean(self, ensure_valid=True):
    174174        """
    175175        Cleans all of self.data and populates self._errors and
    176176        self.cleaned_data.
     177       
     178        If ensure_valid=True, the self.cleaned_data attribute is not set if
     179        validation errors are encountered.
    177180        """
    178181        self._errors = ErrorDict()
    179182        if not self.is_bound: # Stop further processing.
     
    192195                    self.cleaned_data[name] = value
    193196            except ValidationError, e:
    194197                self._errors[name] = e.messages
    195                 if name in self.cleaned_data:
     198                if ensure_valid and name in self.cleaned_data:
    196199                    del self.cleaned_data[name]
    197200        try:
    198201            self.cleaned_data = self.clean()
    199202        except ValidationError, e:
    200203            self._errors[NON_FIELD_ERRORS] = e.messages
    201         if self._errors:
     204        if ensure_valid and self._errors:
    202205            delattr(self, 'cleaned_data')
    203206
    204207    def clean(self):
Back to Top