# Buggy code
def handle(self, *args: Any, **options: str) -> None:
    if settings.STAGING:
        print("This is a Staging server. Suppressing management command.")
        sys.exit(0)

    realm = self.get_realm(options)
    user_emails = options["users"]  # type: ignore  # mypy thinks this is a str, not List[str] #
    activate = options["activate"]
    deactivate = options["deactivate"]

    filter_kwargs = {}  # type: Dict[str, Realm]
    if realm is not None:
        filter_kwargs = dict(realm=realm)

    if activate:
        if not user_emails:
            print("You need to specify at least one user to use the activate option.")
            self.print_help("./manage.py", "soft_deactivate_users")
            sys.exit(1)

        users_to_activate = get_users_from_emails(user_emails, filter_kwargs)
        users_activated = do_soft_activate_users(users_to_activate)
        logger.info("Soft Reactivated %d user(s)" % (len(users_activated)))

    elif deactivate:
        if user_emails:
            users_to_deactivate = get_users_from_emails(user_emails, filter_kwargs)
            print("Soft deactivating forcefully...")
        else:
            if realm is not None:
                filter_kwargs = dict(user_profile__realm=realm)
            users_to_deactivate = get_users_for_soft_deactivation(
                int(options["inactive_for"]), filter_kwargs
            )

        if users_to_deactivate:
            users_deactivated = do_soft_deactivate_users(users_to_deactivate)
            logger.info("Soft Deactivated %d user(s)" % (len(users_deactivated)))
    else:
        self.print_help("./manage.py", "soft_deactivate_users")
        sys.exit(1)


# Traceback (psycopg2.IntegrityError)
Traceback (most recent call last):
File "/home/zulip/deployments/2018-02-28-14-29-15/zulip-py3-venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "./zerver/lib/db.py", line 33, in execute
return wrapper_execute(self, super().execute, query, vars)
File "./zerver/lib/db.py", line 20, in wrapper_execute
return action(sql, params)
psycopg2.IntegrityError: duplicate key value violates unique constraint "zerver_usermessage_user_profile_id_71a38b2c30f35402_uniq"
DETAIL:  Key (user_profile_id, message_id)=(x, y) already exists.


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/zulip/deployments/2018-02-28-14-29-15/zulip-py3-venv/lib/python3.4/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/home/zulip/deployments/2018-02-28-14-29-15/zulip-py3-venv/lib/python3.4/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/zulip/deployments/2018-02-28-14-29-15/zulip-py3-venv/lib/python3.4/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "./zerver/views/home.py", line 84, in home
return home_real(request)
File "./zerver/decorator.py", line 341, in _wrapped_view
return view_func(request, *args, **kwargs)
File "./zerver/decorator.py", line 386, in _wrapped_view_func
return rate_limit()(view_func)(request, *args, **kwargs)
File "./zerver/decorator.py", line 686, in wrapped_func
return func(request, *args, **kwargs)
File "./zerver/views/home.py", line 125, in home_real
narrow=narrow)
File "./zerver/lib/events.py", line 629, in do_events_register
maybe_catch_up_soft_deactivated_user(user_profile)
File "./zerver/lib/soft_deactivation.py", line 191, in maybe_catch_up_soft_deactivated_user
add_missing_messages(user_profile)
File "./zerver/lib/soft_deactivation.py", line 158, in add_missing_messages
UserMessage.objects.bulk_create(user_messages_to_insert)
File "/home/zulip/deployments/2018-02-28-14-29-15/zulip-py3-venv/lib/python3.4/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/zulip/deployments/2018-02-28-14-29-15/zulip-py3-venv/lib/python3.4/site-packages/django/db/models/query.py", line 443, in bulk_create
ids = self._batched_insert(objs_without_pk, fields, batch_size)
File "/home/zulip/deployments/2018-02-28-14-29-15/zulip-py3-venv/lib/python3.4/site-packages/django/db/models/query.py", line 1093, in _batched_insert
inserted_id = self._insert(item, fields=fields, using=self.db, return_id=True)
File "/home/zulip/deployments/2018-02-28-14-29-15/zulip-py3-venv/lib/python3.4/site-packages/django/db/models/query.py", line 1076, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/zulip/deployments/2018-02-28-14-29-15/zulip-py3-venv/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 1107, in execute_sql
cursor.execute(sql, params)
File "/home/zulip/deployments/2018-02-28-14-29-15/zulip-py3-venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/home/zulip/deployments/2018-02-28-14-29-15/zulip-py3-venv/lib/python3.4/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/zulip/deployments/2018-02-28-14-29-15/zulip-py3-venv/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/zulip/deployments/2018-02-28-14-29-15/zulip-py3-venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "./zerver/lib/db.py", line 33, in execute
return wrapper_execute(self, super().execute, query, vars)
File "./zerver/lib/db.py", line 20, in wrapper_execute
return action(sql, params)
django.db.utils.IntegrityError: duplicate key value violates unique constraint "zerver_usermessage_user_profile_id_71a38b2c30f35402_uniq"
DETAIL:  Key (user_profile_id, message_id)=(x, y) already exists.

# Fixed code
def handle(self, *args: Any, **options: str) -> None:
    if settings.STAGING:
        print("This is a Staging server. Suppressing management command.")
        sys.exit(0)

    realm = self.get_realm(options)
    user_emails = options["users"]  # type: ignore  # mypy thinks this is a str, not List[str] #
    activate = options["activate"]
    deactivate = options["deactivate"]

    filter_kwargs = {}  # type: Dict[str, Realm]
    if realm is not None:
        filter_kwargs = dict(realm=realm)

    if activate:
        if not user_emails:
            print("You need to specify at least one user to use the activate option.")
            self.print_help("./manage.py", "soft_deactivate_users")
            sys.exit(1)

        users_to_activate = get_users_from_emails(user_emails, filter_kwargs)
        users_activated = do_soft_activate_users(users_to_activate)
        logger.info("Soft Reactivated %d user(s)" % (len(users_activated)))

    elif deactivate:
        if user_emails:
            users_to_deactivate = get_users_from_emails(user_emails, filter_kwargs)
            print("Soft deactivating forcefully...")
            users_deactivated = do_soft_deactivate_users(users_to_deactivate)
        else:
            users_deactivated = do_auto_soft_deactivate_users(
                int(options["inactive_for"]), realm
            )
        logger.info("Soft Deactivated %d user(s)" % (len(users_deactivated)))

    else:
        self.print_help("./manage.py", "soft_deactivate_users")
        sys.exit(1)