Ticket #9493: formset_unique.4.diff

File formset_unique.4.diff, 4.3 KB (added by mrts, 11 years ago)

Minor nitpicking

  • django/forms/models.py

     
    378378            self.save_m2m = save_m2m
    379379        return self.save_existing_objects(commit) + self.save_new_objects(commit)
    380380
     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 = [check for check
     395                in self.forms[0].instance._meta.unique_together
     396                if [True for field in check if field in self.forms[0].fields]]
     397        unique_checks.extend(unique_together)
     398
     399        errors = []
     400        for unique_check in unique_checks:
     401            data = set()
     402            for i in xrange(self._total_form_count):
     403                form = self.forms[i]
     404                if not hasattr(form, 'cleaned_data'):
     405                    continue
     406                if [True for field in unique_check
     407                        if field in form.cleaned_data and form.cleaned_data[field] is not None]:
     408                    instance = tuple([form.cleaned_data[field] for field in unique_check])
     409                    if instance in data:
     410                        if len(unique_check) == 1:
     411                            errors.append(_(u"You have entered duplicate data for %(field)s, all %(field)ss should be unique." % { 'field': force_unicode(field), }))
     412                        else:
     413                            errors.append(_(u"You have entered duplicate data for %(fields)s, %(fields)ss should be unique together." % { 'fields': get_text_list(unique_check, _("and")), }))
     414                        break
     415                    else:
     416                        data.add(instance)
     417
     418        if errors:
     419            raise ValidationError(errors)
     420
    381421    def save_existing_objects(self, commit=True):
    382422        self.changed_objects = []
    383423        self.deleted_objects = []
  • tests/modeltests/model_formsets/models.py

     
    792792>>> formset.get_queryset()
    793793[<Player: Bobby>]
    794794
     795# Prevent duplicates from within the same formset
     796>>> FormSet = modelformset_factory(Product, extra=2)
     797>>> data = {
     798...     'form-TOTAL_FORMS': 2,
     799...     'form-INITIAL_FORMS': 0,
     800...     'form-0-slug': 'red_car',
     801...     'form-1-slug': 'red_car',
     802... }
     803>>> formset = FormSet(data)
     804>>> formset.is_valid()
     805False
     806>>> formset._non_form_errors
     807[u'You have entered duplicate data for slug, all slugs should be unique.']
     808
     809>>> FormSet = modelformset_factory(Price, extra=2)
     810>>> data = {
     811...     'form-TOTAL_FORMS': 2,
     812...     'form-INITIAL_FORMS': 0,
     813...     'form-0-price': '25',
     814...     'form-0-quantity': '7',
     815...     'form-1-price': '25',
     816...     'form-1-quantity': '7',
     817... }
     818>>> formset = FormSet(data)
     819>>> formset.is_valid()
     820False
     821>>> formset._non_form_errors
     822[u'You have entered duplicate data for price and quantity, price and quantitys should be unique together.']
    795823"""}
  • docs/topics/forms/modelforms.txt

     
    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
Back to Top