Ticket #9493: formset-unique.3.diff

File formset-unique.3.diff, 4.6 KB (added by Alex Gaynor, 11 years ago)

made it a little more effiecient and add docs

  • django/forms/models.py

    diff --git a/django/forms/models.py b/django/forms/models.py
    index 7f49324..6a9fbf5 100644
    a b class BaseModelFormSet(BaseFormSet): 
    377377                    form.save_m2m()
    378378            self.save_m2m = save_m2m
    379379        return self.save_existing_objects(commit) + self.save_new_objects(commit)
     380   
     381    def clean(self):
     382        self.validate_unique()
     383   
     384    def validate_unique(self):
     385        from django.db.models.fields import FieldDoesNotExist
     386        unique_checks = []
     387        for name, field in self.forms[0].fields.iteritems():
     388            try:
     389                f = self.forms[0].instance._meta.get_field_by_name(name)[0]
     390            except FieldDoesNotExist:
     391                continue
     392            if f.unique:
     393                unique_checks.append((name,))
     394        unique_together = self.forms[0].instance._meta.unique_together[:]
     395        unique_together = [check for check in unique_together if [True for field in check if field in self.forms[0].fields]]
     396        unique_checks.extend(unique_together)
     397       
     398        bad_fields = set()
     399        for unique_check in unique_checks:
     400            data = set()
     401            for i in xrange(self._total_form_count):
     402                form = self.forms[i]
     403                if not hasattr(form, 'cleaned_data'):
     404                    continue
     405                if [True for field in unique_check if field in form.cleaned_data and form.cleaned_data[field] is not None]:
     406                    if tuple([form.cleaned_data[field] for field in unique_check]) in data:
     407                        bad_fields.add(unique_check)
     408                        break
     409                    else:
     410                        data.add(tuple([form.cleaned_data[field] for field in unique_check]))
     411       
     412        if bad_fields:
     413            errors = []
     414            for field in bad_fields:
     415                if len(field) == 1:
     416                    errors.append(_(u"You have entered duplicate data for %(field)s, all %(field)ss should be unique." % {
     417                            'field': get_text_list(field, _("and")),
     418                        }))
     419                else:
     420                    errors.append(_(u"You have entered duplicate data for %(fields)s, %(fields)ss should be unique together." % {
     421                            'fields': get_text_list(field, _("and")),
     422                        }))
     423            raise ValidationError(errors)
    380424
    381425    def save_existing_objects(self, commit=True):
    382426        self.changed_objects = []
  • docs/topics/forms/modelforms.txt

    diff --git a/docs/topics/forms/modelforms.txt b/docs/topics/forms/modelforms.txt
    index ad3fe02..f2875ff 100644
    a b in a view. The only difference is that we call ``formset.save()`` to save the 
    538538data into the database. This is described above in
    539539:ref:`saving-objects-in-the-formset`.
    540540
     541Overiding ``clean()`` on a ``model_formset``
     542--------------------------------------------
     543
     544Just like with ``ModelForms``, by default the ``clean()`` method of a
     545``model_formset`` will validate that none of the items in the formset validate
     546the unique constraints on your model(either unique or unique_together).  If you
     547want to overide the ``clean()`` method on a ``model_formset`` and maintain this
     548validation, you must call the parent classes ``clean`` method.
     549
     550
    541551Using ``inlineformset_factory``
    542552-------------------------------
    543553
  • tests/modeltests/model_formsets/models.py

    diff --git a/tests/modeltests/model_formsets/models.py b/tests/modeltests/model_formsets/models.py
    index 4bf7b40..8c674b5 100644
    a b True 
    777777>>> formset.get_queryset()
    778778[<Player: Bobby>]
    779779
     780# Prevent duplicates from within the same formset
     781>>> FormSet = modelformset_factory(Product, extra=2)
     782>>> data = {
     783...     'form-TOTAL_FORMS': 2,
     784...     'form-INITIAL_FORMS': 0,
     785...     'form-0-slug': 'red_car',
     786...     'form-1-slug': 'red_car',
     787... }
     788>>> formset = FormSet(data)
     789>>> formset.is_valid()
     790False
     791>>> formset._non_form_errors
     792[u'You have entered duplicate data for slug, all slugs should be unique.']
     793
     794>>> FormSet = modelformset_factory(Price, extra=2)
     795>>> data = {
     796...     'form-TOTAL_FORMS': 2,
     797...     'form-INITIAL_FORMS': 0,
     798...     'form-0-price': '25',
     799...     'form-0-quantity': '7',
     800...     'form-1-price': '25',
     801...     'form-1-quantity': '7',
     802... }
     803>>> formset = FormSet(data)
     804>>> formset.is_valid()
     805False
     806>>> formset._non_form_errors
     807[u'You have entered duplicate data for price and quantity, price and quantitys should be unique together.']
    780808"""}
Back to Top