prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  500 error when rename team slug
  Error raised if same slug already exists
  
  Traceback:
  
  ```
  File "/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/core/handlers/base.py", line 112, in get_response
       response = wrapped_callback(request, *callback_args, **callback_kwargs)
     File "/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/views/generic/base.py", line 69, in view
       return self.dispatch(request, *args, **kwargs)
     File "/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/utils/decorators.py", line 29, in _wrapper
       return bound_func(*args, **kwargs)
     File "/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/utils/decorators.py", line 99, in _wrapped_view
       response = view_func(request, *args, **kwargs)
     File "/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/utils/decorators.py", line 25, in bound_func
       return func(self, *args2, **kwargs2)
     File "/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/sentry/web/frontend/base.py", line 144, in dispatch
       return self.handle(request, *args, **kwargs)
     File "/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/sentry/web/frontend/team_settings.py", line 37, in handle
       team = form.save()
     File "/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/forms/models.py", line 446, in save
       construct=False)
     File "/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/forms/models.py", line 99, in save_instance
       instance.save()
     File "/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/sentry/models/team.py", line 141, in save
       super(Team, self).save(*args, **kwargs)
     File "/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/db/models/base.py", line 545, in save
       force_update=force_update, update_fields=update_fields)
     File "/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/db/models/base.py", line 573, in save_base
       updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
     File "/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/db/models/base.py", line 635, in _save_table
       forced_update)
     File "/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/db/models/base.py", line 679, in _do_update
       return filtered._update(values) > 0
     File "/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/db/models/query.py", line 510, in _update
       return query.get_compiler(self.db).execute_sql(None)
     File "/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 980, in execute_sql
       cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
     File "/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 786, in execute_sql
       cursor.execute(sql, params)
     File "/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/db/backends/util.py", line 53, in execute
       return self.cursor.execute(sql, params)
     File "/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/db/utils.py", line 99, in __exit__
       six.reraise(dj_exc_type, dj_exc_value, traceback)
     File "/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/db/backends/util.py", line 53, in execute
       return self.cursor.execute(sql, params)
   IntegrityError: duplicate key value violates unique constraint "sentry_team_organization_id_1e0ece47434a2ed_uniq"
   DETAIL:  Key (organization_id, slug)=(1, adwile) already exists.
  ```
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `src/sentry/web/frontend/team_settings.py`
  Content:
  ```
  1 from __future__ import absolute_import
  2 
  3 from django import forms
  4 from django.contrib import messages
  5 from django.core.urlresolvers import reverse
  6 from django.http import HttpResponseRedirect
  7 from django.utils.translation import ugettext_lazy as _
  8 
  9 from sentry.models import AuditLogEntry, AuditLogEntryEvent, Team
  10 from sentry.web.frontend.base import TeamView
  11 
  12 
  13 class EditTeamForm(forms.ModelForm):
  14     class Meta:
  15         fields = ('name', 'slug',)
  16         model = Team
  17 
  18 
  19 class TeamSettingsView(TeamView):
  20     required_scope = 'team:write'
  21 
  22     def get_form(self, request, team):
  23         return EditTeamForm(request.POST or None, instance=team)
  24 
  25     def handle(self, request, organization, team):
  26         form = self.get_form(request, team)
  27         if form.is_valid():
  28             team = form.save()
  29 
  30             AuditLogEntry.objects.create(
  31                 organization=organization,
  32                 actor=request.user,
  33                 ip_address=request.META['REMOTE_ADDR'],
  34                 target_object=team.id,
  35                 event=AuditLogEntryEvent.TEAM_EDIT,
  36                 data=team.get_audit_log_data(),
  37             )
  38 
  39             messages.add_message(request, messages.SUCCESS,
  40                 _('Changes to your team were saved.'))
  41 
  42             return HttpResponseRedirect(reverse('sentry-manage-team', args=[organization.slug, team.slug]))
  43 
  44         if request.user.is_active_superuser():
  45             can_remove_team = True
  46         else:
  47             can_remove_team = request.access.has_team_scope(team, 'team:delete')
  48 
  49         context = {
  50             'form': form,
  51             'can_remove_team': can_remove_team,
  52         }
  53 
  54         return self.respond('sentry/teams/manage.html', context)
  55
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/src/sentry/web/frontend/team_settings.py b/src/sentry/web/frontend/team_settings.py
  --- a/src/sentry/web/frontend/team_settings.py
  +++ b/src/sentry/web/frontend/team_settings.py
  @@ -3,6 +3,7 @@
   from django import forms
   from django.contrib import messages
   from django.core.urlresolvers import reverse
  +from django.db import IntegrityError
   from django.http import HttpResponseRedirect
   from django.utils.translation import ugettext_lazy as _
   
  @@ -23,21 +24,27 @@
           return EditTeamForm(request.POST or None, instance=team)
   
       def handle(self, request, organization, team):
  +        old_slug = team.slug
           form = self.get_form(request, team)
           if form.is_valid():
  -            team = form.save()
  -
  -            AuditLogEntry.objects.create(
  -                organization=organization,
  -                actor=request.user,
  -                ip_address=request.META['REMOTE_ADDR'],
  -                target_object=team.id,
  -                event=AuditLogEntryEvent.TEAM_EDIT,
  -                data=team.get_audit_log_data(),
  -            )
  -
  -            messages.add_message(request, messages.SUCCESS,
  -                _('Changes to your team were saved.'))
  +            try:
  +                team = form.save()
  +            except IntegrityError:
  +                team.slug = old_slug
  +                messages.add_message(request, messages.ERROR,
  +                    _('Changes to your team failed. Slug already exists.'))
  +            else:
  +                AuditLogEntry.objects.create(
  +                    organization=organization,
  +                    actor=request.user,
  +                    ip_address=request.META['REMOTE_ADDR'],
  +                    target_object=team.id,
  +                    event=AuditLogEntryEvent.TEAM_EDIT,
  +                    data=team.get_audit_log_data(),
  +                )
  +
  +                messages.add_message(request, messages.SUCCESS,
  +                    _('Changes to your team were saved.'))
   
               return HttpResponseRedirect(reverse('sentry-manage-team', args=[organization.slug, team.slug]))
  
verification_info: {"golden_diff": "diff --git a/src/sentry/web/frontend/team_settings.py b/src/sentry/web/frontend/team_settings.py\n--- a/src/sentry/web/frontend/team_settings.py\n+++ b/src/sentry/web/frontend/team_settings.py\n@@ -3,6 +3,7 @@\n from django import forms\n from django.contrib import messages\n from django.core.urlresolvers import reverse\n+from django.db import IntegrityError\n from django.http import HttpResponseRedirect\n from django.utils.translation import ugettext_lazy as _\n \n@@ -23,21 +24,27 @@\n         return EditTeamForm(request.POST or None, instance=team)\n \n     def handle(self, request, organization, team):\n+        old_slug = team.slug\n         form = self.get_form(request, team)\n         if form.is_valid():\n-            team = form.save()\n-\n-            AuditLogEntry.objects.create(\n-                organization=organization,\n-                actor=request.user,\n-                ip_address=request.META['REMOTE_ADDR'],\n-                target_object=team.id,\n-                event=AuditLogEntryEvent.TEAM_EDIT,\n-                data=team.get_audit_log_data(),\n-            )\n-\n-            messages.add_message(request, messages.SUCCESS,\n-                _('Changes to your team were saved.'))\n+            try:\n+                team = form.save()\n+            except IntegrityError:\n+                team.slug = old_slug\n+                messages.add_message(request, messages.ERROR,\n+                    _('Changes to your team failed. Slug already exists.'))\n+            else:\n+                AuditLogEntry.objects.create(\n+                    organization=organization,\n+                    actor=request.user,\n+                    ip_address=request.META['REMOTE_ADDR'],\n+                    target_object=team.id,\n+                    event=AuditLogEntryEvent.TEAM_EDIT,\n+                    data=team.get_audit_log_data(),\n+                )\n+\n+                messages.add_message(request, messages.SUCCESS,\n+                    _('Changes to your team were saved.'))\n \n             return HttpResponseRedirect(reverse('sentry-manage-team', args=[organization.slug, team.slug]))\n", "issue": "500 error when rename team slug\nError raised if same slug already exists\n\nTraceback:\n\n```\nFile \"/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/core/handlers/base.py\", line 112, in get_response\n     response = wrapped_callback(request, *callback_args, **callback_kwargs)\n   File \"/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/views/generic/base.py\", line 69, in view\n     return self.dispatch(request, *args, **kwargs)\n   File \"/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/utils/decorators.py\", line 29, in _wrapper\n     return bound_func(*args, **kwargs)\n   File \"/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/utils/decorators.py\", line 99, in _wrapped_view\n     response = view_func(request, *args, **kwargs)\n   File \"/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/utils/decorators.py\", line 25, in bound_func\n     return func(self, *args2, **kwargs2)\n   File \"/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/sentry/web/frontend/base.py\", line 144, in dispatch\n     return self.handle(request, *args, **kwargs)\n   File \"/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/sentry/web/frontend/team_settings.py\", line 37, in handle\n     team = form.save()\n   File \"/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/forms/models.py\", line 446, in save\n     construct=False)\n   File \"/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/forms/models.py\", line 99, in save_instance\n     instance.save()\n   File \"/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/sentry/models/team.py\", line 141, in save\n     super(Team, self).save(*args, **kwargs)\n   File \"/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/db/models/base.py\", line 545, in save\n     force_update=force_update, update_fields=update_fields)\n   File \"/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/db/models/base.py\", line 573, in save_base\n     updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)\n   File \"/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/db/models/base.py\", line 635, in _save_table\n     forced_update)\n   File \"/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/db/models/base.py\", line 679, in _do_update\n     return filtered._update(values) > 0\n   File \"/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/db/models/query.py\", line 510, in _update\n     return query.get_compiler(self.db).execute_sql(None)\n   File \"/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/db/models/sql/compiler.py\", line 980, in execute_sql\n     cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)\n   File \"/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/db/models/sql/compiler.py\", line 786, in execute_sql\n     cursor.execute(sql, params)\n   File \"/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/db/backends/util.py\", line 53, in execute\n     return self.cursor.execute(sql, params)\n   File \"/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/db/utils.py\", line 99, in __exit__\n     six.reraise(dj_exc_type, dj_exc_value, traceback)\n   File \"/home/www/pyenv/versions/sentry/lib/python2.7/site-packages/django/db/backends/util.py\", line 53, in execute\n     return self.cursor.execute(sql, params)\n IntegrityError: duplicate key value violates unique constraint \"sentry_team_organization_id_1e0ece47434a2ed_uniq\"\n DETAIL:  Key (organization_id, slug)=(1, adwile) already exists.\n```\n\n", "before_files": [{"content": "from __future__ import absolute_import\n\nfrom django import forms\nfrom django.contrib import messages\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom sentry.models import AuditLogEntry, AuditLogEntryEvent, Team\nfrom sentry.web.frontend.base import TeamView\n\n\nclass EditTeamForm(forms.ModelForm):\n    class Meta:\n        fields = ('name', 'slug',)\n        model = Team\n\n\nclass TeamSettingsView(TeamView):\n    required_scope = 'team:write'\n\n    def get_form(self, request, team):\n        return EditTeamForm(request.POST or None, instance=team)\n\n    def handle(self, request, organization, team):\n        form = self.get_form(request, team)\n        if form.is_valid():\n            team = form.save()\n\n            AuditLogEntry.objects.create(\n                organization=organization,\n                actor=request.user,\n                ip_address=request.META['REMOTE_ADDR'],\n                target_object=team.id,\n                event=AuditLogEntryEvent.TEAM_EDIT,\n                data=team.get_audit_log_data(),\n            )\n\n            messages.add_message(request, messages.SUCCESS,\n                _('Changes to your team were saved.'))\n\n            return HttpResponseRedirect(reverse('sentry-manage-team', args=[organization.slug, team.slug]))\n\n        if request.user.is_active_superuser():\n            can_remove_team = True\n        else:\n            can_remove_team = request.access.has_team_scope(team, 'team:delete')\n\n        context = {\n            'form': form,\n            'can_remove_team': can_remove_team,\n        }\n\n        return self.respond('sentry/teams/manage.html', context)\n", "path": "src/sentry/web/frontend/team_settings.py"}], "after_files": [{"content": "from __future__ import absolute_import\n\nfrom django import forms\nfrom django.contrib import messages\nfrom django.core.urlresolvers import reverse\nfrom django.db import IntegrityError\nfrom django.http import HttpResponseRedirect\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom sentry.models import AuditLogEntry, AuditLogEntryEvent, Team\nfrom sentry.web.frontend.base import TeamView\n\n\nclass EditTeamForm(forms.ModelForm):\n    class Meta:\n        fields = ('name', 'slug',)\n        model = Team\n\n\nclass TeamSettingsView(TeamView):\n    required_scope = 'team:write'\n\n    def get_form(self, request, team):\n        return EditTeamForm(request.POST or None, instance=team)\n\n    def handle(self, request, organization, team):\n        old_slug = team.slug\n        form = self.get_form(request, team)\n        if form.is_valid():\n            try:\n                team = form.save()\n            except IntegrityError:\n                team.slug = old_slug\n                messages.add_message(request, messages.ERROR,\n                    _('Changes to your team failed. Slug already exists.'))\n            else:\n                AuditLogEntry.objects.create(\n                    organization=organization,\n                    actor=request.user,\n                    ip_address=request.META['REMOTE_ADDR'],\n                    target_object=team.id,\n                    event=AuditLogEntryEvent.TEAM_EDIT,\n                    data=team.get_audit_log_data(),\n                )\n\n                messages.add_message(request, messages.SUCCESS,\n                    _('Changes to your team were saved.'))\n\n            return HttpResponseRedirect(reverse('sentry-manage-team', args=[organization.slug, team.slug]))\n\n        if request.user.is_active_superuser():\n            can_remove_team = True\n        else:\n            can_remove_team = request.access.has_team_scope(team, 'team:delete')\n\n        context = {\n            'form': form,\n            'can_remove_team': can_remove_team,\n        }\n\n        return self.respond('sentry/teams/manage.html', context)\n", "path": "src/sentry/web/frontend/team_settings.py"}]}