updating members of modelformset with unique fields

9 views
Skip to first unread message

anentropic

unread,
May 24, 2015, 12:00:05 PM5/24/15
to django...@googlegroups.com
http://stackoverflow.com/questions/30425468/django-updating-members-of-modelformset-with-unique-fields

The situation - I have a model and inline formset like:

class ProductImage(models.Model):
    product = models.ForeignKey('Product')
    display_order = models.PositiveSmallIntegerField(default=0)

    class Meta:
        unique_together = (('product', 'display_order'),)

inlineformset_factory(
    Product, ProductImage, form=ProductImageForm, extra=1)

In the front end I provide a UI to reorder the images for a given product.

The problem:

  • Let's say I already saved two images attached to <Product id=1>.
  • These two images have display_order=0 and display_order=1 respectively.
  • now I upload a third image, give it display_order=0 while renumbering the existing images to display_order=2 and display_order=1 respectively.

At this point I get a validation error for the unique check.

Looking through Django source code we find this in BaseModelFormSet.save:

return self.save_existing_objects(commit) + self.save_new_objects(commit)

...ok that looks all good, it will save (update) the existing objects first. So from the perspective of the db there is no conflict in the unique constraints.

The problem is that saving comes after validation, or course, and at the point of validation the new objects will conflict with existing ones in the db.

It seems like BaseModelFormSet needs some mechanism whereby it could take into account the about-to-be-updated values from its form instances.

Does anyone have a workaround that does not involve pushing the problem onto the user?

Reply all
Reply to author
Forward
0 new messages