Simple timestamp-based concurrency control in iommi forms

iommi Django

If you have more users accessing your project, you should prevent write-write conflicts.

Imagine two users opening an object edit-form at the same time.

Both users make different changes.

The later one who saves the form wins while the changes of the other user are lost.

python-code

A simple prevention is to add a timestamp (DateTimeField) field to your models

mtime = models.DateTimeField(auto_now=True, verbose_name=_("Last modification"))

then in your iommi.py (which you have, because you followed the docs) you simply add

from django.utils.translation import gettext
from django.core.exceptions import ValidationError

class Form(iommi.Form):

    class Meta:
        @staticmethod
        def post_validation(form, **kwargs):
            # timestamp-based concurrency control
            if "mtime" in form.fields and str(form.fields.mtime.parsed_data) < str(form.fields.mtime.initial):
                raise ValidationError(gettext("Data cannot be saved, because someone else has changed them."))

And that's all. Now the later one cannot overwrite the first one's changes, he just gets ValidationError instead.