Don't crash when adding models with optional m2m fields
authorMagnus Hagander <magnus@hagander.net>
Thu, 28 Dec 2017 15:09:31 +0000 (16:09 +0100)
committerMagnus Hagander <magnus@hagander.net>
Thu, 28 Dec 2017 15:09:31 +0000 (16:09 +0100)
If the m2m field is optional, there will be no "pre" data available, not
even an empty one. Don't crash in this case, just assume it's empty
(which it is).

This could happen when adding a new Organisation, which currently is the
only model we have with optional m2m fields

pgweb/util/signals.py

index 1a57822ee4c54292d7a1c068ea7868a403390747..79ce509f2c602e83291b9d607ee5c63116c7b1b0 100644 (file)
@@ -129,8 +129,8 @@ def my_m2m_changed_handler(sender, **kwargs):
                        instance._stored_m2m[f] = set([unicode(t) for t in getattr(instance,f).all()])
                elif kwargs['action'] == 'post_add':
                        newset = set([unicode(t) for t in getattr(instance,f).all()])
-                       added = newset.difference(instance._stored_m2m[f])
-                       removed = instance._stored_m2m[f].difference(newset)
+                       added = newset.difference(instance._stored_m2m.get(f, set()))
+                       removed = instance._stored_m2m.get(f, set()).difference(newset)
                        subj = '{0} id {1} has been modified'.format(instance._meta.verbose_name, instance.id)
                        if added or removed:
                                send_simple_mail(settings.NOTIFICATION_FROM,