# Buggy code
def send_notifications(notification_list, job_id=None):
    if not isinstance(notification_list, list):
        raise TypeError("notification_list should be of type list")
    if job_id is not None:
        job_actual = UnifiedJob.objects.get(id=job_id)

    notifications = Notification.objects.filter(id__in=notification_list)
    if job_id is not None:
        job_actual.notifications.add(*notifications)

    for notification in notifications:
        update_fields = ["status", "notifications_sent"]
        try:
            sent = notification.notification_template.send(
                notification.subject, notification.body
            )
            notification.status = "successful"
            notification.notifications_sent = sent
        except Exception as e:
            logger.error(six.text_type("Send Notification Failed {}").format(e))
            notification.status = "failed"
            notification.error = smart_str(e)
            update_fields.append("error")
        finally:
            notification.save(update_fields=update_fields)


# Traceback (ValueError)
xxx@dddd-01:~$ docker logs awx_task_1
Using /etc/ansible/ansible.cfg as config file
...
Traceback (most recent call last):
File "/usr/bin/awx-manage", line 9, in <module>
load_entry_point('awx==1.0.6.0', 'console_scripts', 'awx-manage')()
File "/usr/lib/python2.7/site-packages/awx/__init__.py", line 109, in manage
execute_from_command_line(sys.argv)
File "/var/lib/awx/venv/awx/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
Operations to perform:
Apply all migrations: auth, conf, contenttypes, djcelery, main, network_ui, oauth2_provider, sessions, sites, social_django, sso, taggit
utility.execute()
...
ValueError: The field oauth2_provider.AccessToken.application was declared with a lazy reference to 'main.oauth2application', but app 'main' doesn't provide model 'oauth2application'.
The field oauth2_provider.Grant.application was declared with a lazy reference to 'main.oauth2application', but app 'main' doesn't provide model 'oauth2application'.
The field oauth2_provider.RefreshToken.access_token was declared with a lazy reference to 'main.oauth2accesstoken', but app 'main' doesn't provide model 'oauth2accesstoken'.
The field oauth2_provider.RefreshToken.application was declared with a lazy reference to 'main.oauth2application', but app 'main' doesn't provide model 'oauth2application'.

...
django.db.utils.IntegrityError: duplicate key value violates unique constraint "auth_user_username_key"
DETAIL:  Key (username)=(admin) already exists.

Instance already registered awx
Instance Group already registered tower
...
2018-04-27 17:58:18,281 CRIT Supervisor is running as root.  Privileges were not dropped because no user is specified in the config file.  If you intend to run as root, you can set user=root in the config file to avoid this message.
...

# Fixed code
def send_notifications(notification_list, job_id=None):
    if not isinstance(notification_list, list):
        raise TypeError("notification_list should be of type list")
    if job_id is not None:
        job_actual = UnifiedJob.objects.get(id=job_id)

    notifications = Notification.objects.filter(id__in=notification_list)
    if job_id is not None:
        job_actual.notifications.add(*notifications)

    for notification in notifications:
        update_fields = ["status", "notifications_sent"]
        try:
            sent = notification.notification_template.send(
                notification.subject, notification.body
            )
            notification.status = "successful"
            notification.notifications_sent = sent
        except Exception as e:
            logger.error(six.text_type("Send Notification Failed {}").format(e))
            notification.status = "failed"
            notification.error = smart_str(e)
            update_fields.append("error")
        finally:
            try:
                notification.save(update_fields=update_fields)
            except Exception as e:
                logger.exception(
                    six.text_type("Error saving notification {} result.").format(
                        notification.id
                    )
                )