Don't crash when adding models with optional m2m fields

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
This commit is contained in:
Magnus Hagander
2017-12-28 16:09:31 +01:00
parent 0b7ef6d457
commit 65d0854f83

View 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,