diff --git a/django/conf/__init__.py b/django/conf/__init__.py
index a3f7ee0..8439f0f 100644
--- a/django/conf/__init__.py
+++ b/django/conf/__init__.py
@@ -91,7 +91,7 @@ class Settings(BaseSettings):
 
         try:
             mod = importlib.import_module(self.SETTINGS_MODULE)
-        except ImportError, e:
+        except ImportError as e:
             raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
 
         # Settings that should be converted into tuples if they're mistakenly entered
diff --git a/django/contrib/admin/tests.py b/django/contrib/admin/tests.py
index 2491fc6..59fa9ba 100644
--- a/django/contrib/admin/tests.py
+++ b/django/contrib/admin/tests.py
@@ -18,7 +18,7 @@ class AdminSeleniumWebDriverTestCase(LiveServerTestCase):
             mod = import_module(module)
             WebDriver = getattr(mod, attr)
             cls.selenium = WebDriver()
-        except Exception, e:
+        except Exception as e:
             raise SkipTest('Selenium webdriver "%s" not installed or not '
                            'operational: %s' % (cls.webdriver_class, str(e)))
         super(AdminSeleniumWebDriverTestCase, cls).setUpClass()
diff --git a/django/contrib/admin/util.py b/django/contrib/admin/util.py
index 61182a6..b1670cb 100644
--- a/django/contrib/admin/util.py
+++ b/django/contrib/admin/util.py
@@ -153,7 +153,7 @@ class NestedObjects(Collector):
                 self.add_edge(None, obj)
         try:
             return super(NestedObjects, self).collect(objs, source_attr=source_attr, **kwargs)
-        except models.ProtectedError, e:
+        except models.ProtectedError as e:
             self.protected.update(e.protected_objects)
 
     def related_objects(self, related, objs):
diff --git a/django/contrib/admin/views/main.py b/django/contrib/admin/views/main.py
index b11f9d5..a250315 100644
--- a/django/contrib/admin/views/main.py
+++ b/django/contrib/admin/views/main.py
@@ -139,7 +139,7 @@ class ChangeList(object):
                 use_distinct = (use_distinct or
                                 lookup_needs_distinct(self.lookup_opts, key))
             return filter_specs, bool(filter_specs), lookup_params, use_distinct
-        except FieldDoesNotExist, e:
+        except FieldDoesNotExist as e:
             raise IncorrectLookupParameters(e)
 
     def get_query_string(self, new_params=None, remove=None):
@@ -316,7 +316,7 @@ class ChangeList(object):
             # Allow certain types of errors to be re-raised as-is so that the
             # caller can treat them in a special way.
             raise
-        except Exception, e:
+        except Exception as e:
             # Every other error is caught with a naked except, because we don't
             # have any other way of validating lookup parameters. They might be
             # invalid if the keyword arguments are incorrect, or if the values
diff --git a/django/contrib/admindocs/views.py b/django/contrib/admindocs/views.py
index 33d9a7d..c3405a7 100644
--- a/django/contrib/admindocs/views.py
+++ b/django/contrib/admindocs/views.py
@@ -318,7 +318,7 @@ def load_all_installed_template_libraries():
         for library_name in libraries:
             try:
                 lib = template.get_library(library_name)
-            except template.InvalidTemplateLibrary, e:
+            except template.InvalidTemplateLibrary as e:
                 pass
 
 def get_return_data_type(func_name):
diff --git a/django/contrib/auth/__init__.py b/django/contrib/auth/__init__.py
index 3495e16..93fd441 100644
--- a/django/contrib/auth/__init__.py
+++ b/django/contrib/auth/__init__.py
@@ -12,9 +12,9 @@ def load_backend(path):
     module, attr = path[:i], path[i+1:]
     try:
         mod = import_module(module)
-    except ImportError, e:
+    except ImportError as e:
         raise ImproperlyConfigured('Error importing authentication backend %s: "%s"' % (path, e))
-    except ValueError, e:
+    except ValueError as e:
         raise ImproperlyConfigured('Error importing authentication backends. Is AUTHENTICATION_BACKENDS a correctly defined list or tuple?')
     try:
         cls = getattr(mod, attr)
diff --git a/django/contrib/comments/views/comments.py b/django/contrib/comments/views/comments.py
index 5772016..c9a1160 100644
--- a/django/contrib/comments/views/comments.py
+++ b/django/contrib/comments/views/comments.py
@@ -66,7 +66,7 @@ def post_comment(request, next=None, using=None):
         return CommentPostBadRequest(
             "No object matching content-type %r and object PK %r exists." % \
                 (escape(ctype), escape(object_pk)))
-    except (ValueError, ValidationError), e:
+    except (ValueError, ValidationError) as e:
         return CommentPostBadRequest(
             "Attempting go get content-type %r and object PK %r exists raised %s" % \
                 (escape(ctype), escape(object_pk), e.__class__.__name__))
diff --git a/django/contrib/formtools/wizard/storage/__init__.py b/django/contrib/formtools/wizard/storage/__init__.py
index b88ccc7..f2293c9 100644
--- a/django/contrib/formtools/wizard/storage/__init__.py
+++ b/django/contrib/formtools/wizard/storage/__init__.py
@@ -10,7 +10,7 @@ def get_storage(path, *args, **kwargs):
     module, attr = path[:i], path[i+1:]
     try:
         mod = import_module(module)
-    except ImportError, e:
+    except ImportError as e:
         raise MissingStorageModule(
             'Error loading storage %s: "%s"' % (module, e))
     try:
diff --git a/django/contrib/gis/db/backends/base.py b/django/contrib/gis/db/backends/base.py
index c8bb3d2..26e9762 100644
--- a/django/contrib/gis/db/backends/base.py
+++ b/django/contrib/gis/db/backends/base.py
@@ -164,13 +164,13 @@ class SpatialRefSysMixin(object):
                 try:
                     self._srs = gdal.SpatialReference(self.wkt)
                     return self.srs
-                except Exception, msg:
+                except Exception as msg:
                     pass
 
                 try:
                     self._srs = gdal.SpatialReference(self.proj4text)
                     return self.srs
-                except Exception, msg:
+                except Exception as msg:
                     pass
 
                 raise Exception('Could not get OSR SpatialReference from WKT: %s\nError:\n%s' % (self.wkt, msg))
diff --git a/django/contrib/gis/db/backends/oracle/introspection.py b/django/contrib/gis/db/backends/oracle/introspection.py
index 58dd3f3..716f318 100644
--- a/django/contrib/gis/db/backends/oracle/introspection.py
+++ b/django/contrib/gis/db/backends/oracle/introspection.py
@@ -16,7 +16,7 @@ class OracleIntrospection(DatabaseIntrospection):
                 cursor.execute('SELECT "DIMINFO", "SRID" FROM "USER_SDO_GEOM_METADATA" WHERE "TABLE_NAME"=%s AND "COLUMN_NAME"=%s',
                                (table_name.upper(), geo_col.upper()))
                 row = cursor.fetchone()
-            except Exception, msg:
+            except Exception as msg:
                 raise Exception('Could not find entry in USER_SDO_GEOM_METADATA corresponding to "%s"."%s"\n'
                                 'Error message: %s.' % (table_name, geo_col, msg))
 
diff --git a/django/contrib/gis/db/backends/postgis/operations.py b/django/contrib/gis/db/backends/postgis/operations.py
index 3286748..9dcfe4c 100644
--- a/django/contrib/gis/db/backends/postgis/operations.py
+++ b/django/contrib/gis/db/backends/postgis/operations.py
@@ -107,7 +107,7 @@ class PostGISOperations(DatabaseOperations, BaseSpatialOperations):
                                        'Was the database created from a spatial database '
                                        'template?' % self.connection.settings_dict['NAME']
                                        )
-        except Exception, e:
+        except Exception as e:
             # TODO: Raise helpful exceptions as they become known.
             raise
 
diff --git a/django/contrib/gis/db/backends/spatialite/base.py b/django/contrib/gis/db/backends/spatialite/base.py
index aea52f5..b447d1d 100644
--- a/django/contrib/gis/db/backends/spatialite/base.py
+++ b/django/contrib/gis/db/backends/spatialite/base.py
@@ -56,7 +56,7 @@ class DatabaseWrapper(SQLiteDatabaseWrapper):
             cur = self.connection.cursor(factory=SQLiteCursorWrapper)
             try:
                 cur.execute("SELECT load_extension(%s)", (self.spatialite_lib,))
-            except Exception, msg:
+            except Exception as msg:
                 raise ImproperlyConfigured('Unable to load the SpatiaLite library extension '
                                            '"%s" because: %s' % (self.spatialite_lib, msg))
             return cur
diff --git a/django/contrib/gis/db/backends/spatialite/operations.py b/django/contrib/gis/db/backends/spatialite/operations.py
index a0efb99..6adcdc5 100644
--- a/django/contrib/gis/db/backends/spatialite/operations.py
+++ b/django/contrib/gis/db/backends/spatialite/operations.py
@@ -122,7 +122,7 @@ class SpatiaLiteOperations(DatabaseOperations, BaseSpatialOperations):
             self.spatial_version = version
         except ImproperlyConfigured:
             raise
-        except Exception, msg:
+        except Exception as msg:
             raise ImproperlyConfigured('Cannot determine the SpatiaLite version for the "%s" '
                                        'database (error was "%s").  Was the SpatiaLite initialization '
                                        'SQL loaded on this database?' %
diff --git a/django/contrib/gis/geometry/backend/__init__.py b/django/contrib/gis/geometry/backend/__init__.py
index d79a556..2e2495d 100644
--- a/django/contrib/gis/geometry/backend/__init__.py
+++ b/django/contrib/gis/geometry/backend/__init__.py
@@ -6,10 +6,10 @@ geom_backend = getattr(settings, 'GEOMETRY_BACKEND', 'geos')
 
 try:
     module = import_module('.%s' % geom_backend, 'django.contrib.gis.geometry.backend')
-except ImportError, e:
+except ImportError as e:
     try:
         module = import_module(geom_backend)
-    except ImportError, e_user:
+    except ImportError as e_user:
         raise ImproperlyConfigured('Could not import user-defined GEOMETRY_BACKEND '
                                    '"%s".' % geom_backend)
 
diff --git a/django/contrib/gis/management/commands/ogrinspect.py b/django/contrib/gis/management/commands/ogrinspect.py
index fbc6f53..6037cc7 100644
--- a/django/contrib/gis/management/commands/ogrinspect.py
+++ b/django/contrib/gis/management/commands/ogrinspect.py
@@ -87,7 +87,7 @@ class Command(LabelCommand):
         # Getting the OGR DataSource from the string parameter.
         try:
             ds = gdal.DataSource(data_source)
-        except gdal.OGRException, msg:
+        except gdal.OGRException as msg:
             raise CommandError(msg)
 
         # Whether the user wants to generate the LayerMapping dictionary as well.
diff --git a/django/contrib/gis/tests/test_measure.py b/django/contrib/gis/tests/test_measure.py
index 8ca6be1..6792569 100644
--- a/django/contrib/gis/tests/test_measure.py
+++ b/django/contrib/gis/tests/test_measure.py
@@ -64,28 +64,28 @@ class DistanceTest(unittest.TestCase):
 
         try:
             d5 = d1 + 1
-        except TypeError, e:
+        except TypeError as e:
             pass
         else:
             self.fail('Distance + number should raise TypeError')
 
         try:
             d5 = d1 - 1
-        except TypeError, e:
+        except TypeError as e:
             pass
         else:
             self.fail('Distance - number should raise TypeError')
 
         try:
             d1 += 1
-        except TypeError, e:
+        except TypeError as e:
             pass
         else:
             self.fail('Distance += number should raise TypeError')
 
         try:
             d1 -= 1
-        except TypeError, e:
+        except TypeError as e:
             pass
         else:
             self.fail('Distance -= number should raise TypeError')
@@ -112,21 +112,21 @@ class DistanceTest(unittest.TestCase):
 
         try:
             d1 *= D(m=1)
-        except TypeError, e:
+        except TypeError as e:
             pass
         else:
             self.fail('Distance *= Distance should raise TypeError')
 
         try:
             d5 = d1 / D(m=1)
-        except TypeError, e:
+        except TypeError as e:
             pass
         else:
             self.fail('Distance / Distance should raise TypeError')
 
         try:
             d1 /= D(m=1)
-        except TypeError, e:
+        except TypeError as e:
             pass
         else:
             self.fail('Distance /= Distance should raise TypeError')
@@ -219,28 +219,28 @@ class AreaTest(unittest.TestCase):
 
         try:
             a5 = a1 + 1
-        except TypeError, e:
+        except TypeError as e:
             pass
         else:
             self.fail('Area + number should raise TypeError')
 
         try:
             a5 = a1 - 1
-        except TypeError, e:
+        except TypeError as e:
             pass
         else:
             self.fail('Area - number should raise TypeError')
 
         try:
             a1 += 1
-        except TypeError, e:
+        except TypeError as e:
             pass
         else:
             self.fail('Area += number should raise TypeError')
 
         try:
             a1 -= 1
-        except TypeError, e:
+        except TypeError as e:
             pass
         else:
             self.fail('Area -= number should raise TypeError')
@@ -263,28 +263,28 @@ class AreaTest(unittest.TestCase):
 
         try:
             a5 = a1 * A(sq_m=1)
-        except TypeError, e:
+        except TypeError as e:
             pass
         else:
             self.fail('Area * Area should raise TypeError')
 
         try:
             a1 *= A(sq_m=1)
-        except TypeError, e:
+        except TypeError as e:
             pass
         else:
             self.fail('Area *= Area should raise TypeError')
 
         try:
             a5 = a1 / A(sq_m=1)
-        except TypeError, e:
+        except TypeError as e:
             pass
         else:
             self.fail('Area / Area should raise TypeError')
 
         try:
             a1 /= A(sq_m=1)
-        except TypeError, e:
+        except TypeError as e:
             pass
         else:
             self.fail('Area /= Area should raise TypeError')
diff --git a/django/contrib/gis/utils/layermapping.py b/django/contrib/gis/utils/layermapping.py
index 154617f..ea3f3d7 100644
--- a/django/contrib/gis/utils/layermapping.py
+++ b/django/contrib/gis/utils/layermapping.py
@@ -430,7 +430,7 @@ class LayerMapping(object):
 
             # Creating the CoordTransform object
             return CoordTransform(self.source_srs, target_srs)
-        except Exception, msg:
+        except Exception as msg:
             raise LayerMapError('Could not translate between the data source and model geometry: %s' % msg)
 
     def geometry_field(self):
@@ -514,7 +514,7 @@ class LayerMapping(object):
                 # Getting the keyword arguments
                 try:
                     kwargs = self.feature_kwargs(feat)
-                except LayerMapError, msg:
+                except LayerMapError as msg:
                     # Something borked the validation
                     if strict: raise
                     elif not silent:
@@ -553,7 +553,7 @@ class LayerMapping(object):
                         if verbose: stream.write('%s: %s\n' % (is_update and 'Updated' or 'Saved', m))
                     except SystemExit:
                         raise
-                    except Exception, msg:
+                    except Exception as msg:
                         if self.transaction_mode == 'autocommit':
                             # Rolling back the transaction so that other model saves
                             # will work.
diff --git a/django/contrib/markup/tests.py b/django/contrib/markup/tests.py
index cccb5c8..05df318 100644
--- a/django/contrib/markup/tests.py
+++ b/django/contrib/markup/tests.py
@@ -87,7 +87,7 @@ Paragraph 2 with a link_
             # Docutils v0.4 and earlier
             self.assertEqual(rendered, """<p>Paragraph 1</p>
 <p>Paragraph 2 with a <a class="reference" href="http://www.example.com/">link</a></p>""")
-        except AssertionError, e:
+        except AssertionError as e:
             # Docutils from SVN (which will become 0.5)
             self.assertEqual(rendered, """<p>Paragraph 1</p>
 <p>Paragraph 2 with a <a class="reference external" href="http://www.example.com/">link</a></p>""")
diff --git a/django/contrib/messages/storage/__init__.py b/django/contrib/messages/storage/__init__.py
index ce3971b..a584acc 100644
--- a/django/contrib/messages/storage/__init__.py
+++ b/django/contrib/messages/storage/__init__.py
@@ -15,7 +15,7 @@ def get_storage(import_path):
     module, classname = import_path[:dot], import_path[dot + 1:]
     try:
         mod = import_module(module)
-    except ImportError, e:
+    except ImportError as e:
         raise ImproperlyConfigured('Error importing module %s: "%s"' %
                                    (module, e))
     try:
diff --git a/django/contrib/sessions/backends/file.py b/django/contrib/sessions/backends/file.py
index 8ffddc4..cb81534 100644
--- a/django/contrib/sessions/backends/file.py
+++ b/django/contrib/sessions/backends/file.py
@@ -90,7 +90,7 @@ class SessionStore(SessionBase):
             fd = os.open(session_file_name, flags)
             os.close(fd)
 
-        except OSError, e:
+        except OSError as e:
             if must_create and e.errno == errno.EEXIST:
                 raise CreateError
             raise
diff --git a/django/contrib/staticfiles/finders.py b/django/contrib/staticfiles/finders.py
index 7b4c7c8..766687c 100644
--- a/django/contrib/staticfiles/finders.py
+++ b/django/contrib/staticfiles/finders.py
@@ -260,7 +260,7 @@ def _get_finder(import_path):
     module, attr = import_path.rsplit('.', 1)
     try:
         mod = import_module(module)
-    except ImportError, e:
+    except ImportError as e:
         raise ImproperlyConfigured('Error importing module %s: "%s"' %
                                    (module, e))
     try:
diff --git a/django/contrib/staticfiles/handlers.py b/django/contrib/staticfiles/handlers.py
index 962b835..f475b22 100644
--- a/django/contrib/staticfiles/handlers.py
+++ b/django/contrib/staticfiles/handlers.py
@@ -56,7 +56,7 @@ class StaticFilesHandler(WSGIHandler):
         if self._should_handle(request.path):
             try:
                 return self.serve(request)
-            except Http404, e:
+            except Http404 as e:
                 if settings.DEBUG:
                     from django.views import debug
                     return debug.technical_404_response(request, e)
diff --git a/django/core/cache/__init__.py b/django/core/cache/__init__.py
index 346deae..3b40555 100644
--- a/django/core/cache/__init__.py
+++ b/django/core/cache/__init__.py
@@ -173,7 +173,7 @@ def get_cache(backend, **kwargs):
             mod_path, cls_name = backend.rsplit('.', 1)
             mod = importlib.import_module(mod_path)
             backend_cls = getattr(mod, cls_name)
-    except (AttributeError, ImportError), e:
+    except (AttributeError, ImportError) as e:
         raise InvalidCacheBackendError(
             "Could not find backend '%s': %s" % (backend, e))
     cache = backend_cls(location, params)
diff --git a/django/core/files/move.py b/django/core/files/move.py
index 3349fc2..4778228 100644
--- a/django/core/files/move.py
+++ b/django/core/files/move.py
@@ -79,7 +79,7 @@ def file_move_safe(old_file_name, new_file_name, chunk_size = 1024*64, allow_ove
 
     try:
         os.remove(old_file_name)
-    except OSError, e:
+    except OSError as e:
         # Certain operating systems (Cygwin and Windows) 
         # fail when deleting opened files, ignore it.  (For the 
         # systems where this happens, temporary files will be auto-deleted
diff --git a/django/core/files/storage.py b/django/core/files/storage.py
index aa62175..6b724b4 100644
--- a/django/core/files/storage.py
+++ b/django/core/files/storage.py
@@ -166,7 +166,7 @@ class FileSystemStorage(Storage):
         if not os.path.exists(directory):
             try:
                 os.makedirs(directory)
-            except OSError, e:
+            except OSError as e:
                 if e.errno != errno.EEXIST:
                     raise
         if not os.path.isdir(directory):
@@ -197,7 +197,7 @@ class FileSystemStorage(Storage):
                     finally:
                         locks.unlock(fd)
                         os.close(fd)
-            except OSError, e:
+            except OSError as e:
                 if e.errno == errno.EEXIST:
                     # Ooops, the file exists. We need a new file name.
                     name = self.get_available_name(name)
@@ -222,7 +222,7 @@ class FileSystemStorage(Storage):
         if os.path.exists(name):
             try:
                 os.remove(name)
-            except OSError, e:
+            except OSError as e:
                 if e.errno != errno.ENOENT:
                     raise
 
@@ -273,7 +273,7 @@ def get_storage_class(import_path=None):
     module, classname = import_path[:dot], import_path[dot+1:]
     try:
         mod = import_module(module)
-    except ImportError, e:
+    except ImportError as e:
         raise ImproperlyConfigured('Error importing storage module %s: "%s"' % (module, e))
     try:
         return getattr(mod, classname)
diff --git a/django/core/files/uploadedfile.py b/django/core/files/uploadedfile.py
index 5178f0b..1dcd9ae 100644
--- a/django/core/files/uploadedfile.py
+++ b/django/core/files/uploadedfile.py
@@ -75,7 +75,7 @@ class TemporaryUploadedFile(UploadedFile):
     def close(self):
         try:
             return self.file.close()
-        except OSError, e:
+        except OSError as e:
             if e.errno != 2:
                 # Means the file was moved or deleted before the tempfile
                 # could unlink it.  Still sets self.file.close_called and
diff --git a/django/core/files/uploadhandler.py b/django/core/files/uploadhandler.py
index 2afb79e..b806098 100644
--- a/django/core/files/uploadhandler.py
+++ b/django/core/files/uploadhandler.py
@@ -204,9 +204,9 @@ def load_handler(path, *args, **kwargs):
     module, attr = path[:i], path[i+1:]
     try:
         mod = importlib.import_module(module)
-    except ImportError, e:
+    except ImportError as e:
         raise ImproperlyConfigured('Error importing upload handler module %s: "%s"' % (module, e))
-    except ValueError, e:
+    except ValueError as e:
         raise ImproperlyConfigured('Error importing upload handler module. Is FILE_UPLOAD_HANDLERS a correctly defined list or tuple?')
     try:
         cls = getattr(mod, attr)
diff --git a/django/core/handlers/base.py b/django/core/handlers/base.py
index a0918bf..4c9dfc0 100644
--- a/django/core/handlers/base.py
+++ b/django/core/handlers/base.py
@@ -43,7 +43,7 @@ class BaseHandler(object):
                 raise exceptions.ImproperlyConfigured('%s isn\'t a middleware module' % middleware_path)
             try:
                 mod = import_module(mw_module)
-            except ImportError, e:
+            except ImportError as e:
                 raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e))
             try:
                 mw_class = getattr(mod, mw_classname)
@@ -109,7 +109,7 @@ class BaseHandler(object):
                 if response is None:
                     try:
                         response = callback(request, *callback_args, **callback_kwargs)
-                    except Exception, e:
+                    except Exception as e:
                         # If the view raised an exception, run it through exception
                         # middleware, and if the exception middleware returns a
                         # response, use that. Otherwise, reraise the exception.
@@ -135,7 +135,7 @@ class BaseHandler(object):
                         response = middleware_method(request, response)
                     response = response.render()
 
-            except http.Http404, e:
+            except http.Http404 as e:
                 logger.warning('Not Found: %s', request.path,
                             extra={
                                 'status_code': 404,
diff --git a/django/core/mail/__init__.py b/django/core/mail/__init__.py
index 7ab02c3..3e3ef0d 100644
--- a/django/core/mail/__init__.py
+++ b/django/core/mail/__init__.py
@@ -30,7 +30,7 @@ def get_connection(backend=None, fail_silently=False, **kwds):
     try:
         mod_name, klass_name = path.rsplit('.', 1)
         mod = import_module(mod_name)
-    except ImportError, e:
+    except ImportError as e:
         raise ImproperlyConfigured(('Error importing email backend module %s: "%s"'
                                     % (mod_name, e)))
     try:
diff --git a/django/core/mail/backends/filebased.py b/django/core/mail/backends/filebased.py
index 3f6b99b..674ca32 100644
--- a/django/core/mail/backends/filebased.py
+++ b/django/core/mail/backends/filebased.py
@@ -25,7 +25,7 @@ class EmailBackend(ConsoleEmailBackend):
         elif not os.path.exists(self.file_path):
             try:
                 os.makedirs(self.file_path)
-            except OSError, err:
+            except OSError as err:
                 raise ImproperlyConfigured('Could not create directory for saving email messages: %s (%s)' % (self.file_path, err))
         # Make sure that self.file_path is writable.
         if not os.access(self.file_path, os.W_OK):
diff --git a/django/core/management/base.py b/django/core/management/base.py
index db855e1..42c9ccd 100644
--- a/django/core/management/base.py
+++ b/django/core/management/base.py
@@ -215,7 +215,7 @@ class BaseCommand(object):
                 from django.utils import translation
                 saved_lang = translation.get_language()
                 translation.activate('en-us')
-            except ImportError, e:
+            except ImportError as e:
                 # If settings should be available, but aren't,
                 # raise the error and quit.
                 if show_traceback:
@@ -241,7 +241,7 @@ class BaseCommand(object):
                 self.stdout.write(output)
                 if self.output_transaction:
                     self.stdout.write('\n' + self.style.SQL_KEYWORD("COMMIT;") + '\n')
-        except CommandError, e:
+        except CommandError as e:
             if show_traceback:
                 traceback.print_exc()
             else:
@@ -297,7 +297,7 @@ class AppCommand(BaseCommand):
             raise CommandError('Enter at least one appname.')
         try:
             app_list = [models.get_app(app_label) for app_label in app_labels]
-        except (ImproperlyConfigured, ImportError), e:
+        except (ImproperlyConfigured, ImportError) as e:
             raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e)
         output = []
         for app in app_list:
diff --git a/django/core/management/commands/createcachetable.py b/django/core/management/commands/createcachetable.py
index 7164d1a..82a126b 100644
--- a/django/core/management/commands/createcachetable.py
+++ b/django/core/management/commands/createcachetable.py
@@ -54,7 +54,7 @@ class Command(LabelCommand):
         curs = connection.cursor()
         try:
             curs.execute("\n".join(full_statement))
-        except DatabaseError, e:
+        except DatabaseError as e:
             self.stderr.write(
                 self.style.ERROR("Cache table '%s' could not be created.\nThe error was: %s.\n" %
                     (tablename, e)))
diff --git a/django/core/management/commands/dumpdata.py b/django/core/management/commands/dumpdata.py
index 1622929..71d6fa7 100644
--- a/django/core/management/commands/dumpdata.py
+++ b/django/core/management/commands/dumpdata.py
@@ -111,7 +111,7 @@ class Command(BaseCommand):
         try:
             return serializers.serialize(format, objects, indent=indent,
                         use_natural_keys=use_natural_keys)
-        except Exception, e:
+        except Exception as e:
             if show_traceback:
                 raise
             raise CommandError("Unable to serialize database: %s" % e)
diff --git a/django/core/management/commands/flush.py b/django/core/management/commands/flush.py
index 6d0f14e..12a276e 100644
--- a/django/core/management/commands/flush.py
+++ b/django/core/management/commands/flush.py
@@ -55,7 +55,7 @@ Are you sure you want to do this?
                 cursor = connection.cursor()
                 for sql in sql_list:
                     cursor.execute(sql)
-            except Exception, e:
+            except Exception as e:
                 transaction.rollback_unless_managed(using=db)
                 raise CommandError("""Database %s couldn't be flushed. Possible reasons:
   * The database isn't running or isn't configured correctly.
diff --git a/django/core/management/commands/loaddata.py b/django/core/management/commands/loaddata.py
index 0c234fb..d066343 100644
--- a/django/core/management/commands/loaddata.py
+++ b/django/core/management/commands/loaddata.py
@@ -194,7 +194,7 @@ class Command(BaseCommand):
                                             models.add(obj.object.__class__)
                                             try:
                                                 obj.save(using=using)
-                                            except (DatabaseError, IntegrityError), e:
+                                            except (DatabaseError, IntegrityError) as e:
                                                 msg = "Could not load %(app_label)s.%(object_name)s(pk=%(pk)s): %(error_msg)s" % {
                                                         'app_label': obj.object._meta.app_label,
                                                         'object_name': obj.object._meta.object_name,
diff --git a/django/core/management/commands/reset.py b/django/core/management/commands/reset.py
index e45edb7..4ac1a03 100644
--- a/django/core/management/commands/reset.py
+++ b/django/core/management/commands/reset.py
@@ -49,7 +49,7 @@ Type 'yes' to continue, or 'no' to cancel: """ % (app_name, connection.settings_
                 cursor = connection.cursor()
                 for sql in sql_list:
                     cursor.execute(sql)
-            except Exception, e:
+            except Exception as e:
                 transaction.rollback_unless_managed()
                 raise CommandError("""Error: %s couldn't be reset. Possible reasons:
   * The database isn't running or isn't configured correctly.
diff --git a/django/core/management/commands/runserver.py b/django/core/management/commands/runserver.py
index e93af96..3ec4ea8 100644
--- a/django/core/management/commands/runserver.py
+++ b/django/core/management/commands/runserver.py
@@ -109,7 +109,7 @@ class BaseRunserverCommand(BaseCommand):
             handler = self.get_handler(*args, **options)
             run(self.addr, int(self.port), handler,
                 ipv6=self.use_ipv6, threading=threading)
-        except WSGIServerException, e:
+        except WSGIServerException as e:
             # Use helpful error messages instead of ugly tracebacks.
             ERRORS = {
                 13: "You don't have permission to access that port.",
diff --git a/django/core/management/commands/syncdb.py b/django/core/management/commands/syncdb.py
index 852fa15..1f5d2ed 100644
--- a/django/core/management/commands/syncdb.py
+++ b/django/core/management/commands/syncdb.py
@@ -38,7 +38,7 @@ class Command(NoArgsCommand):
         for app_name in settings.INSTALLED_APPS:
             try:
                 import_module('.management', app_name)
-            except ImportError, exc:
+            except ImportError as exc:
                 # This is slightly hackish. We want to ignore ImportErrors
                 # if the "management" module itself is missing -- but we don't
                 # want to ignore the exception if the management module exists
@@ -126,7 +126,7 @@ class Command(NoArgsCommand):
                         try:
                             for sql in custom_sql:
                                 cursor.execute(sql)
-                        except Exception, e:
+                        except Exception as e:
                             sys.stderr.write("Failed to install custom SQL for %s.%s model: %s\n" % \
                                                 (app_name, model._meta.object_name, e))
                             if show_traceback:
@@ -151,7 +151,7 @@ class Command(NoArgsCommand):
                         try:
                             for sql in index_sql:
                                 cursor.execute(sql)
-                        except Exception, e:
+                        except Exception as e:
                             sys.stderr.write("Failed to install index for %s.%s model: %s\n" % \
                                                 (app_name, model._meta.object_name, e))
                             transaction.rollback_unless_managed(using=db)
diff --git a/django/core/management/templates.py b/django/core/management/templates.py
index 9a4b2c1..6bf1888 100644
--- a/django/core/management/templates.py
+++ b/django/core/management/templates.py
@@ -82,7 +82,7 @@ class TemplateCommand(BaseCommand):
             top_dir = path.join(os.getcwd(), name)
             try:
                 os.makedirs(top_dir)
-            except OSError, e:
+            except OSError as e:
                 if e.errno == errno.EEXIST:
                     message = "'%s' already exists" % top_dir
                 else:
@@ -232,7 +232,7 @@ class TemplateCommand(BaseCommand):
         try:
             the_path, info = urllib.urlretrieve(url,
                                                 path.join(tempdir, filename))
-        except IOError, e:
+        except IOError as e:
             raise CommandError("couldn't download URL %s to %s: %s" %
                                (url, filename, e))
 
@@ -287,7 +287,7 @@ class TemplateCommand(BaseCommand):
         try:
             archive.extract(filename, tempdir)
             return tempdir
-        except (archive.ArchiveException, IOError), e:
+        except (archive.ArchiveException, IOError) as e:
             raise CommandError("couldn't extract file %s to %s: %s" %
                                (filename, tempdir, e))
 
diff --git a/django/core/serializers/json.py b/django/core/serializers/json.py
index 91af84e..e9570b8 100644
--- a/django/core/serializers/json.py
+++ b/django/core/serializers/json.py
@@ -42,7 +42,7 @@ def Deserializer(stream_or_string, **options):
             yield obj
     except GeneratorExit:
         raise
-    except Exception, e:
+    except Exception as e:
         # Map to deserializer error
         raise DeserializationError(e)
 
diff --git a/django/core/serializers/pyyaml.py b/django/core/serializers/pyyaml.py
index 7a508da..dc884a6 100644
--- a/django/core/serializers/pyyaml.py
+++ b/django/core/serializers/pyyaml.py
@@ -57,6 +57,6 @@ def Deserializer(stream_or_string, **options):
             yield obj
     except GeneratorExit:
         raise
-    except Exception, e:
+    except Exception as e:
         # Map to deserializer error
         raise DeserializationError(e)
diff --git a/django/core/servers/basehttp.py b/django/core/servers/basehttp.py
index 8d4ceab..f728ea1 100644
--- a/django/core/servers/basehttp.py
+++ b/django/core/servers/basehttp.py
@@ -52,13 +52,13 @@ def get_internal_wsgi_application():
     module_name, attr = app_path.rsplit('.', 1)
     try:
         mod = import_module(module_name)
-    except ImportError, e:
+    except ImportError as e:
         raise ImproperlyConfigured(
             "WSGI application '%s' could not be loaded; "
             "could not import module '%s': %s" % (app_path, module_name, e))
     try:
         app = getattr(mod, attr)
-    except AttributeError, e:
+    except AttributeError as e:
         raise ImproperlyConfigured(
             "WSGI application '%s' could not be loaded; "
             "can't find '%s' in module '%s': %s"
@@ -122,7 +122,7 @@ class WSGIServer(simple_server.WSGIServer, object):
         """Override server_bind to store the server name."""
         try:
             super(WSGIServer, self).server_bind()
-        except Exception, e:
+        except Exception as e:
             raise WSGIServerException(e)
         self.setup_environ()
 
diff --git a/django/core/servers/fastcgi.py b/django/core/servers/fastcgi.py
index 17fd609..9c652a7 100644
--- a/django/core/servers/fastcgi.py
+++ b/django/core/servers/fastcgi.py
@@ -102,7 +102,7 @@ def runfastcgi(argset=[], **kwargs):
 
     try:
         import flup
-    except ImportError, e:
+    except ImportError as e:
         print >> sys.stderr, "ERROR: %s" % e
         print >> sys.stderr, "  Unable to load the flup package.  In order to run django"
         print >> sys.stderr, "  as a FastCGI application, you will need to get flup from"
diff --git a/django/core/signing.py b/django/core/signing.py
index 7f92d61..78a8659 100644
--- a/django/core/signing.py
+++ b/django/core/signing.py
@@ -76,12 +76,12 @@ def get_cookie_signer(salt='django.core.signing.get_cookie_signer'):
     module, attr = modpath.rsplit('.', 1)
     try:
         mod = import_module(module)
-    except ImportError, e:
+    except ImportError as e:
         raise ImproperlyConfigured(
             'Error importing cookie signer %s: "%s"' % (modpath, e))
     try:
         Signer = getattr(mod, attr)
-    except AttributeError, e:
+    except AttributeError as e:
         raise ImproperlyConfigured(
             'Error importing cookie signer %s: "%s"' % (modpath, e))
     return Signer('django.http.cookies' + settings.SECRET_KEY, salt=salt)
diff --git a/django/core/urlresolvers.py b/django/core/urlresolvers.py
index 1497d43..aadd290 100644
--- a/django/core/urlresolvers.py
+++ b/django/core/urlresolvers.py
@@ -298,7 +298,7 @@ class RegexURLResolver(LocaleRegexProvider):
             for pattern in self.url_patterns:
                 try:
                     sub_match = pattern.resolve(new_path)
-                except Resolver404, e:
+                except Resolver404 as e:
                     sub_tried = e.args[0].get('tried')
                     if sub_tried is not None:
                         tried.extend([[pattern] + t for t in sub_tried])
@@ -358,7 +358,7 @@ class RegexURLResolver(LocaleRegexProvider):
             raise ValueError("Don't mix *args and **kwargs in call to reverse()!")
         try:
             lookup_view = get_callable(lookup_view, True)
-        except (ImportError, AttributeError), e:
+        except (ImportError, AttributeError) as e:
             raise NoReverseMatch("Error importing '%s': %s." % (lookup_view, e))
         possibilities = self.reverse_dict.getlist(lookup_view)
         prefix_norm, prefix_args = normalize(_prefix)[0]
@@ -462,7 +462,7 @@ def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current
                 extra, resolver = resolver.namespace_dict[ns]
                 resolved_path.append(ns)
                 ns_pattern = ns_pattern + extra
-            except KeyError, key:
+            except KeyError as key:
                 if resolved_path:
                     raise NoReverseMatch(
                         "%s is not a registered namespace inside '%s'" %
diff --git a/django/core/validators.py b/django/core/validators.py
index 95224e9..52971e2 100644
--- a/django/core/validators.py
+++ b/django/core/validators.py
@@ -61,7 +61,7 @@ class URLValidator(RegexValidator):
     def __call__(self, value):
         try:
             super(URLValidator, self).__call__(value)
-        except ValidationError, e:
+        except ValidationError as e:
             # Trivial case failed. Try for possible IDN domain
             if value:
                 value = smart_unicode(value)
@@ -144,7 +144,7 @@ class EmailValidator(RegexValidator):
     def __call__(self, value):
         try:
             super(EmailValidator, self).__call__(value)
-        except ValidationError, e:
+        except ValidationError as e:
             # Trivial case failed. Try for possible IDN domain-part
             if value and u'@' in value:
                 parts = value.split(u'@')
diff --git a/django/db/backends/creation.py b/django/db/backends/creation.py
index 0cd0558..2e3b7e5 100644
--- a/django/db/backends/creation.py
+++ b/django/db/backends/creation.py
@@ -323,7 +323,7 @@ class BaseDatabaseCreation(object):
         try:
             cursor.execute(
                 "CREATE DATABASE %s %s" % (qn(test_database_name), suffix))
-        except Exception, e:
+        except Exception as e:
             sys.stderr.write(
                 "Got an error creating the test database: %s\n" % e)
             if not autoclobber:
@@ -340,7 +340,7 @@ class BaseDatabaseCreation(object):
                     cursor.execute(
                         "CREATE DATABASE %s %s" % (qn(test_database_name),
                                                    suffix))
-                except Exception, e:
+                except Exception as e:
                     sys.stderr.write(
                         "Got an error recreating the test database: %s\n" % e)
                     sys.exit(2)
diff --git a/django/db/backends/mysql/base.py b/django/db/backends/mysql/base.py
index faaefca..c272f9f 100644
--- a/django/db/backends/mysql/base.py
+++ b/django/db/backends/mysql/base.py
@@ -11,7 +11,7 @@ import warnings
 
 try:
     import MySQLdb as Database
-except ImportError, e:
+except ImportError as e:
     from django.core.exceptions import ImproperlyConfigured
     raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
 
@@ -112,29 +112,29 @@ class CursorWrapper(object):
     def execute(self, query, args=None):
         try:
             return self.cursor.execute(query, args)
-        except Database.IntegrityError, e:
+        except Database.IntegrityError as e:
             raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
-        except Database.OperationalError, e:
+        except Database.OperationalError as e:
             # Map some error codes to IntegrityError, since they seem to be
             # misclassified and Django would prefer the more logical place.
             if e[0] in self.codes_for_integrityerror:
                 raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
             raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
-        except Database.DatabaseError, e:
+        except Database.DatabaseError as e:
             raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
 
     def executemany(self, query, args):
         try:
             return self.cursor.executemany(query, args)
-        except Database.IntegrityError, e:
+        except Database.IntegrityError as e:
             raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
-        except Database.OperationalError, e:
+        except Database.OperationalError as e:
             # Map some error codes to IntegrityError, since they seem to be
             # misclassified and Django would prefer the more logical place.
             if e[0] in self.codes_for_integrityerror:
                 raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
             raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
-        except Database.DatabaseError, e:
+        except Database.DatabaseError as e:
             raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
 
     def __getattr__(self, attr):
diff --git a/django/db/backends/oracle/base.py b/django/db/backends/oracle/base.py
index fc02ac4..9c91baa 100644
--- a/django/db/backends/oracle/base.py
+++ b/django/db/backends/oracle/base.py
@@ -18,7 +18,7 @@ def _setup_environment(environ):
     if platform.system().upper().startswith('CYGWIN'):
         try:
             import ctypes
-        except ImportError, e:
+        except ImportError as e:
             from django.core.exceptions import ImproperlyConfigured
             raise ImproperlyConfigured("Error loading ctypes: %s; "
                                        "the Oracle backend requires ctypes to "
@@ -41,7 +41,7 @@ _setup_environment([
 
 try:
     import cx_Oracle as Database
-except ImportError, e:
+except ImportError as e:
     from django.core.exceptions import ImproperlyConfigured
     raise ImproperlyConfigured("Error loading cx_Oracle module: %s" % e)
 
@@ -532,11 +532,11 @@ class DatabaseWrapper(BaseDatabaseWrapper):
         if self.connection is not None:
             try:
                 return self.connection.commit()
-            except Database.IntegrityError, e:
+            except Database.IntegrityError as e:
                 # In case cx_Oracle implements (now or in a future version)
                 # raising this specific exception
                 raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
-            except Database.DatabaseError, e:
+            except Database.DatabaseError as e:
                 # cx_Oracle 5.0.4 raises a cx_Oracle.DatabaseError exception
                 # with the following attributes and values:
                 #  code = 2091
@@ -673,9 +673,9 @@ class FormatStylePlaceholderCursor(object):
         self._guess_input_sizes([params])
         try:
             return self.cursor.execute(query, self._param_generator(params))
-        except Database.IntegrityError, e:
+        except Database.IntegrityError as e:
             raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
-        except Database.DatabaseError, e:
+        except Database.DatabaseError as e:
             # cx_Oracle <= 4.4.0 wrongly raises a DatabaseError for ORA-01400.
             if hasattr(e.args[0], 'code') and e.args[0].code == 1400 and not isinstance(e, IntegrityError):
                 raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
@@ -702,9 +702,9 @@ class FormatStylePlaceholderCursor(object):
         try:
             return self.cursor.executemany(query,
                                 [self._param_generator(p) for p in formatted])
-        except Database.IntegrityError, e:
+        except Database.IntegrityError as e:
             raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
-        except Database.DatabaseError, e:
+        except Database.DatabaseError as e:
             # cx_Oracle <= 4.4.0 wrongly raises a DatabaseError for ORA-01400.
             if hasattr(e.args[0], 'code') and e.args[0].code == 1400 and not isinstance(e, IntegrityError):
                 raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
diff --git a/django/db/backends/oracle/creation.py b/django/db/backends/oracle/creation.py
index 9e6133f..758c9ec 100644
--- a/django/db/backends/oracle/creation.py
+++ b/django/db/backends/oracle/creation.py
@@ -62,7 +62,7 @@ class DatabaseCreation(BaseDatabaseCreation):
         if self._test_database_create():
             try:
                 self._execute_test_db_creation(cursor, parameters, verbosity)
-            except Exception, e:
+            except Exception as e:
                 sys.stderr.write("Got an error creating the test database: %s\n" % e)
                 if not autoclobber:
                     confirm = raw_input("It appears the test database, %s, already exists. Type 'yes' to delete it, or 'no' to cancel: " % TEST_NAME)
@@ -72,7 +72,7 @@ class DatabaseCreation(BaseDatabaseCreation):
                             print "Destroying old test database '%s'..." % self.connection.alias
                         self._execute_test_db_destruction(cursor, parameters, verbosity)
                         self._execute_test_db_creation(cursor, parameters, verbosity)
-                    except Exception, e:
+                    except Exception as e:
                         sys.stderr.write("Got an error recreating the test database: %s\n" % e)
                         sys.exit(2)
                 else:
@@ -84,7 +84,7 @@ class DatabaseCreation(BaseDatabaseCreation):
                 print "Creating test user..."
             try:
                 self._create_test_user(cursor, parameters, verbosity)
-            except Exception, e:
+            except Exception as e:
                 sys.stderr.write("Got an error creating the test user: %s\n" % e)
                 if not autoclobber:
                     confirm = raw_input("It appears the test user, %s, already exists. Type 'yes' to delete it, or 'no' to cancel: " % TEST_USER)
@@ -96,7 +96,7 @@ class DatabaseCreation(BaseDatabaseCreation):
                         if verbosity >= 1:
                             print "Creating test user..."
                         self._create_test_user(cursor, parameters, verbosity)
-                    except Exception, e:
+                    except Exception as e:
                         sys.stderr.write("Got an error recreating the test user: %s\n" % e)
                         sys.exit(2)
                 else:
@@ -197,7 +197,7 @@ class DatabaseCreation(BaseDatabaseCreation):
                 print stmt
             try:
                 cursor.execute(stmt)
-            except Exception, err:
+            except Exception as err:
                 sys.stderr.write("Failed (%s)\n" % (err))
                 raise
 
diff --git a/django/db/backends/postgresql_psycopg2/base.py b/django/db/backends/postgresql_psycopg2/base.py
index 0d25129..61be680 100644
--- a/django/db/backends/postgresql_psycopg2/base.py
+++ b/django/db/backends/postgresql_psycopg2/base.py
@@ -20,7 +20,7 @@ from django.utils.timezone import utc
 try:
     import psycopg2 as Database
     import psycopg2.extensions
-except ImportError, e:
+except ImportError as e:
     from django.core.exceptions import ImproperlyConfigured
     raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
 
@@ -50,17 +50,17 @@ class CursorWrapper(object):
     def execute(self, query, args=None):
         try:
             return self.cursor.execute(query, args)
-        except Database.IntegrityError, e:
+        except Database.IntegrityError as e:
             raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
-        except Database.DatabaseError, e:
+        except Database.DatabaseError as e:
             raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
 
     def executemany(self, query, args):
         try:
             return self.cursor.executemany(query, args)
-        except Database.IntegrityError, e:
+        except Database.IntegrityError as e:
             raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
-        except Database.DatabaseError, e:
+        except Database.DatabaseError as e:
             raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
 
     def __getattr__(self, attr):
@@ -233,5 +233,5 @@ class DatabaseWrapper(BaseDatabaseWrapper):
         if self.connection is not None:
             try:
                 return self.connection.commit()
-            except Database.IntegrityError, e:
+            except Database.IntegrityError as e:
                 raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
diff --git a/django/db/backends/sqlite3/base.py b/django/db/backends/sqlite3/base.py
index 0b19442..3d389ed 100644
--- a/django/db/backends/sqlite3/base.py
+++ b/django/db/backends/sqlite3/base.py
@@ -24,9 +24,9 @@ from django.utils import timezone
 try:
     try:
         from pysqlite2 import dbapi2 as Database
-    except ImportError, e1:
+    except ImportError as e1:
         from sqlite3 import dbapi2 as Database
-except ImportError, exc:
+except ImportError as exc:
     from django.core.exceptions import ImproperlyConfigured
     raise ImproperlyConfigured("Error loading either pysqlite2 or sqlite3 modules (tried in that order): %s" % exc)
 
@@ -335,18 +335,18 @@ class SQLiteCursorWrapper(Database.Cursor):
         query = self.convert_query(query)
         try:
             return Database.Cursor.execute(self, query, params)
-        except Database.IntegrityError, e:
+        except Database.IntegrityError as e:
             raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
-        except Database.DatabaseError, e:
+        except Database.DatabaseError as e:
             raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
 
     def executemany(self, query, param_list):
         query = self.convert_query(query)
         try:
             return Database.Cursor.executemany(self, query, param_list)
-        except Database.IntegrityError, e:
+        except Database.IntegrityError as e:
             raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
-        except Database.DatabaseError, e:
+        except Database.DatabaseError as e:
             raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
 
     def convert_query(self, query):
diff --git a/django/db/backends/sqlite3/creation.py b/django/db/backends/sqlite3/creation.py
index 5f55e39..9e660fa 100644
--- a/django/db/backends/sqlite3/creation.py
+++ b/django/db/backends/sqlite3/creation.py
@@ -57,7 +57,7 @@ class DatabaseCreation(BaseDatabaseCreation):
                 if autoclobber or confirm == 'yes':
                   try:
                       os.remove(test_database_name)
-                  except Exception, e:
+                  except Exception as e:
                       sys.stderr.write("Got an error deleting the old test database: %s\n" % e)
                       sys.exit(2)
                 else:
diff --git a/django/db/models/base.py b/django/db/models/base.py
index fc38224..b92058c 100644
--- a/django/db/models/base.py
+++ b/django/db/models/base.py
@@ -801,14 +801,14 @@ class Model(object):
 
         try:
             self.clean_fields(exclude=exclude)
-        except ValidationError, e:
+        except ValidationError as e:
             errors = e.update_error_dict(errors)
 
         # Form.clean() is run even if other validation fails, so do the
         # same with Model.clean() for consistency.
         try:
             self.clean()
-        except ValidationError, e:
+        except ValidationError as e:
             errors = e.update_error_dict(errors)
 
         # Run unique checks, but only for fields that passed validation.
@@ -817,7 +817,7 @@ class Model(object):
                 exclude.append(name)
         try:
             self.validate_unique(exclude=exclude)
-        except ValidationError, e:
+        except ValidationError as e:
             errors = e.update_error_dict(errors)
 
         if errors:
@@ -842,7 +842,7 @@ class Model(object):
                 continue
             try:
                 setattr(self, f.attname, f.clean(raw_value, self))
-            except ValidationError, e:
+            except ValidationError as e:
                 errors[f.name] = e.messages
 
         if errors:
diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py
index 22546c2..67a4381 100644
--- a/django/db/models/fields/__init__.py
+++ b/django/db/models/fields/__init__.py
@@ -152,7 +152,7 @@ class Field(object):
         for v in self.validators:
             try:
                 v(value)
-            except exceptions.ValidationError, e:
+            except exceptions.ValidationError as e:
                 if hasattr(e, 'code') and e.code in self.error_messages:
                     message = self.error_messages[e.code]
                     if e.params:
diff --git a/django/db/models/query.py b/django/db/models/query.py
index 44acadf..5c68237 100644
--- a/django/db/models/query.py
+++ b/django/db/models/query.py
@@ -205,7 +205,7 @@ class QuerySet(object):
             qs = self._clone()
             qs.query.set_limits(k, k + 1)
             return list(qs)[0]
-        except self.model.DoesNotExist, e:
+        except self.model.DoesNotExist as e:
             raise IndexError(e.args)
 
     def __and__(self, other):
@@ -449,7 +449,7 @@ class QuerySet(object):
                 obj.save(force_insert=True, using=self.db)
                 transaction.savepoint_commit(sid, using=self.db)
                 return obj, True
-            except IntegrityError, e:
+            except IntegrityError as e:
                 transaction.savepoint_rollback(sid, using=self.db)
                 exc_info = sys.exc_info()
                 try:
diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py
index 693dde3..bc7512f 100644
--- a/django/db/models/sql/query.py
+++ b/django/db/models/sql/query.py
@@ -1120,7 +1120,7 @@ class Query(object):
                     parts, opts, alias, True, allow_many, allow_explicit_fk=True,
                     can_reuse=can_reuse, negate=negate,
                     process_extras=process_extras)
-        except MultiJoin, e:
+        except MultiJoin as e:
             self.split_exclude(filter_expr, LOOKUP_SEP.join(parts[:e.level]),
                     can_reuse)
             return
diff --git a/django/db/utils.py b/django/db/utils.py
index 3f5b86e..2b6ae2c 100644
--- a/django/db/utils.py
+++ b/django/db/utils.py
@@ -22,7 +22,7 @@ def load_backend(backend_name):
     # Look for a fully qualified database backend name
     try:
         return import_module('.base', backend_name)
-    except ImportError, e_user:
+    except ImportError as e_user:
         # The database backend wasn't found. Display a helpful error message
         # listing all possible (built-in) database backends.
         backend_dir = os.path.join(os.path.dirname(__file__), 'backends')
@@ -112,7 +112,7 @@ class ConnectionRouter(object):
                 try:
                     module_name, klass_name = r.rsplit('.', 1)
                     module = import_module(module_name)
-                except ImportError, e:
+                except ImportError as e:
                     raise ImproperlyConfigured('Error importing database router %s: "%s"' % (klass_name, e))
                 try:
                     router_class = getattr(module, klass_name)
diff --git a/django/dispatch/dispatcher.py b/django/dispatch/dispatcher.py
index ed9da57..0903c3a 100644
--- a/django/dispatch/dispatcher.py
+++ b/django/dispatch/dispatcher.py
@@ -205,7 +205,7 @@ class Signal(object):
         for receiver in self._live_receivers(_make_id(sender)):
             try:
                 response = receiver(signal=self, sender=sender, **named)
-            except Exception, err:
+            except Exception as err:
                 responses.append((receiver, err))
             else:
                 responses.append((receiver, response))
diff --git a/django/dispatch/saferef.py b/django/dispatch/saferef.py
index 1c7d164..364c13e 100644
--- a/django/dispatch/saferef.py
+++ b/django/dispatch/saferef.py
@@ -119,10 +119,10 @@ class BoundMethodWeakref(object):
                 try:
                     if callable( function ):
                         function( self )
-                except Exception, e:
+                except Exception as e:
                     try:
                         traceback.print_exc()
-                    except AttributeError, err:
+                    except AttributeError as err:
                         print '''Exception during saferef %s cleanup function %s: %s'''%(
                             self, function, e
                         )
diff --git a/django/forms/fields.py b/django/forms/fields.py
index 96ecabf..5d9d581 100644
--- a/django/forms/fields.py
+++ b/django/forms/fields.py
@@ -132,7 +132,7 @@ class Field(object):
         for v in self.validators:
             try:
                 v(value)
-            except ValidationError, e:
+            except ValidationError as e:
                 if hasattr(e, 'code') and e.code in self.error_messages:
                     message = self.error_messages[e.code]
                     if e.params:
@@ -898,7 +898,7 @@ class MultiValueField(Field):
                 raise ValidationError(self.error_messages['required'])
             try:
                 clean_data.append(field.clean(field_value))
-            except ValidationError, e:
+            except ValidationError as e:
                 # Collect all validation errors in a single list, which we'll
                 # raise at the end of clean(), rather than raising a single
                 # exception for the first error we encounter.
diff --git a/django/forms/forms.py b/django/forms/forms.py
index 94eb22d..09663d1 100644
--- a/django/forms/forms.py
+++ b/django/forms/forms.py
@@ -289,7 +289,7 @@ class BaseForm(StrAndUnicode):
                 if hasattr(self, 'clean_%s' % name):
                     value = getattr(self, 'clean_%s' % name)()
                     self.cleaned_data[name] = value
-            except ValidationError, e:
+            except ValidationError as e:
                 self._errors[name] = self.error_class(e.messages)
                 if name in self.cleaned_data:
                     del self.cleaned_data[name]
@@ -297,7 +297,7 @@ class BaseForm(StrAndUnicode):
     def _clean_form(self):
         try:
             self.cleaned_data = self.clean()
-        except ValidationError, e:
+        except ValidationError as e:
             self._errors[NON_FIELD_ERRORS] = self.error_class(e.messages)
 
     def _post_clean(self):
diff --git a/django/forms/formsets.py b/django/forms/formsets.py
index dcd2f01..739a9d4 100644
--- a/django/forms/formsets.py
+++ b/django/forms/formsets.py
@@ -291,7 +291,7 @@ class BaseFormSet(StrAndUnicode):
         # Give self.clean() a chance to do cross-form validation.
         try:
             self.clean()
-        except ValidationError, e:
+        except ValidationError as e:
             self._non_form_errors = self.error_class(e.messages)
 
     def clean(self):
diff --git a/django/forms/models.py b/django/forms/models.py
index cd8f027..ea80f8d 100644
--- a/django/forms/models.py
+++ b/django/forms/models.py
@@ -324,13 +324,13 @@ class BaseModelForm(BaseForm):
         # Clean the model instance's fields.
         try:
             self.instance.clean_fields(exclude=exclude)
-        except ValidationError, e:
+        except ValidationError as e:
             self._update_errors(e.message_dict)
 
         # Call the model instance's clean method.
         try:
             self.instance.clean()
-        except ValidationError, e:
+        except ValidationError as e:
             self._update_errors({NON_FIELD_ERRORS: e.messages})
 
         # Validate uniqueness if needed.
@@ -345,7 +345,7 @@ class BaseModelForm(BaseForm):
         exclude = self._get_validation_exclusions()
         try:
             self.instance.validate_unique(exclude=exclude)
-        except ValidationError, e:
+        except ValidationError as e:
             self._update_errors(e.message_dict)
 
     def save(self, commit=True):
diff --git a/django/forms/util.py b/django/forms/util.py
index 886f08e..1f3e290 100644
--- a/django/forms/util.py
+++ b/django/forms/util.py
@@ -66,7 +66,7 @@ def from_current_timezone(value):
         current_timezone = timezone.get_current_timezone()
         try:
             return timezone.make_aware(value, current_timezone)
-        except Exception, e:
+        except Exception as e:
             raise ValidationError(_('%(datetime)s couldn\'t be interpreted '
                                     'in time zone %(current_timezone)s; it '
                                     'may be ambiguous or it may not exist.')
diff --git a/django/http/__init__.py b/django/http/__init__.py
index 94478ae..1e371bd 100644
--- a/django/http/__init__.py
+++ b/django/http/__init__.py
@@ -326,7 +326,7 @@ class HttpRequest(object):
                 raise Exception("You cannot access body after reading from request's data stream")
             try:
                 self._body = self.read()
-            except IOError, e:
+            except IOError as e:
                 raise UnreadablePostError, e, sys.exc_traceback
             self._stream = StringIO(self._body)
         return self._body
@@ -592,7 +592,7 @@ class HttpResponse(object):
             if isinstance(value, unicode):
                 try:
                     value = value.encode('us-ascii')
-                except UnicodeError, e:
+                except UnicodeError as e:
                     e.reason += ', HTTP response headers must be in US-ASCII format'
                     raise
             else:
diff --git a/django/http/multipartparser.py b/django/http/multipartparser.py
index 477a08c..180ec34 100644
--- a/django/http/multipartparser.py
+++ b/django/http/multipartparser.py
@@ -196,7 +196,7 @@ class MultiPartParser(object):
                                 # We only special-case base64 transfer encoding
                                 try:
                                     chunk = str(chunk).decode('base64')
-                                except Exception, e:
+                                except Exception as e:
                                     # Since this is only a chunk, any error is an unfixable error.
                                     raise MultiPartParserError("Could not decode base64 data: %r" % e)
 
@@ -209,7 +209,7 @@ class MultiPartParser(object):
                                     # If the chunk received by the handler is None, then don't continue.
                                     break
 
-                    except SkipFile, e:
+                    except SkipFile as e:
                         # Just use up the rest of this file...
                         exhaust(field_stream)
                     else:
@@ -218,7 +218,7 @@ class MultiPartParser(object):
                 else:
                     # If this is neither a FIELD or a FILE, just exhaust the stream.
                     exhaust(stream)
-        except StopUpload, e:
+        except StopUpload as e:
             if not e.connection_reset:
                 exhaust(self._input_data)
         else:
diff --git a/django/template/base.py b/django/template/base.py
index e2fc66b..f08313c 100644
--- a/django/template/base.py
+++ b/django/template/base.py
@@ -265,7 +265,7 @@ class Parser(object):
                     self.invalid_block_tag(token, command, parse_until)
                 try:
                     compiled_result = compile_func(self, token)
-                except TemplateSyntaxError, e:
+                except TemplateSyntaxError as e:
                     if not self.compile_function_error(token, e):
                         raise
                 self.extend_nodelist(nodelist, compiled_result, token)
@@ -774,7 +774,7 @@ class Variable(object):
                             # GOTCHA: This will also catch any TypeError
                             # raised in the function itself.
                             current = settings.TEMPLATE_STRING_IF_INVALID  # invalid method call
-        except Exception, e:
+        except Exception as e:
             if getattr(e, 'silent_variable_failure', False):
                 current = settings.TEMPLATE_STRING_IF_INVALID
             else:
@@ -1237,7 +1237,7 @@ def import_library(taglib_module):
     """
     try:
         mod = import_module(taglib_module)
-    except ImportError, e:
+    except ImportError as e:
         # If the ImportError is because the taglib submodule does not exist,
         # that's not an error that should be raised. If the submodule exists
         # and raised an ImportError on the attempt to load it, that we want
diff --git a/django/template/context.py b/django/template/context.py
index bbd38ad..db24551 100644
--- a/django/template/context.py
+++ b/django/template/context.py
@@ -147,7 +147,7 @@ def get_standard_processors():
             module, attr = path[:i], path[i+1:]
             try:
                 mod = import_module(module)
-            except ImportError, e:
+            except ImportError as e:
                 raise ImproperlyConfigured('Error importing request processor module %s: "%s"' % (module, e))
             try:
                 func = getattr(mod, attr)
diff --git a/django/template/debug.py b/django/template/debug.py
index 74aa82b..e8fd0b0 100644
--- a/django/template/debug.py
+++ b/django/template/debug.py
@@ -72,7 +72,7 @@ class DebugNodeList(NodeList):
     def render_node(self, node, context):
         try:
             return node.render(context)
-        except Exception, e:
+        except Exception as e:
             if not hasattr(e, 'django_template_source'):
                 e.django_template_source = node.source
             raise
@@ -87,7 +87,7 @@ class DebugVariableNode(VariableNode):
             output = force_unicode(output)
         except UnicodeDecodeError:
             return ''
-        except Exception, e:
+        except Exception as e:
             if not hasattr(e, 'django_template_source'):
                 e.django_template_source = self.source
             raise
diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py
index f93e799..ea7d5e4 100644
--- a/django/template/defaultfilters.py
+++ b/django/template/defaultfilters.py
@@ -892,5 +892,5 @@ def pprint(value):
     """A wrapper around pprint.pprint -- for debugging, really."""
     try:
         return pformat(value)
-    except Exception, e:
+    except Exception as e:
         return u"Error in formatting: %s" % force_unicode(e, errors="replace")
diff --git a/django/template/defaulttags.py b/django/template/defaulttags.py
index 954c5d6..00cf08c 100644
--- a/django/template/defaulttags.py
+++ b/django/template/defaulttags.py
@@ -183,7 +183,7 @@ class ForNode(Node):
                 for node in self.nodelist_loop:
                     try:
                         nodelist.append(node.render(context))
-                    except Exception, e:
+                    except Exception as e:
                         if not hasattr(e, 'django_template_source'):
                             e.django_template_source = node.source
                         raise
@@ -340,7 +340,7 @@ class SsiNode(Node):
             try:
                 t = Template(output, name=filepath)
                 return t.render(context)
-            except TemplateSyntaxError, e:
+            except TemplateSyntaxError as e:
                 if settings.DEBUG:
                     return "[Included template had syntax error: %s]" % e
                 else:
@@ -409,7 +409,7 @@ class URLNode(Node):
         url = ''
         try:
             url = reverse(view_name, args=args, kwargs=kwargs, current_app=context.current_app)
-        except NoReverseMatch, e:
+        except NoReverseMatch as e:
             if settings.SETTINGS_MODULE:
                 project_name = settings.SETTINGS_MODULE.split('.')[0]
                 try:
@@ -1015,7 +1015,7 @@ def load(parser, token):
         try:
             taglib = bits[-1]
             lib = get_library(taglib)
-        except InvalidTemplateLibrary, e:
+        except InvalidTemplateLibrary as e:
             raise TemplateSyntaxError("'%s' is not a valid tag library: %s" %
                                       (taglib, e))
         else:
@@ -1038,7 +1038,7 @@ def load(parser, token):
             try:
                 lib = get_library(taglib)
                 parser.add_library(lib)
-            except InvalidTemplateLibrary, e:
+            except InvalidTemplateLibrary as e:
                 raise TemplateSyntaxError("'%s' is not a valid tag library: %s" %
                                           (taglib, e))
     return LoadNode()
diff --git a/django/template/loader.py b/django/template/loader.py
index 4185017..b6d62cc 100644
--- a/django/template/loader.py
+++ b/django/template/loader.py
@@ -93,11 +93,11 @@ def find_template_loader(loader):
         module, attr = loader.rsplit('.', 1)
         try:
             mod = import_module(module)
-        except ImportError, e:
+        except ImportError as e:
             raise ImproperlyConfigured('Error importing template source loader %s: "%s"' % (loader, e))
         try:
             TemplateLoader = getattr(mod, attr)
-        except AttributeError, e:
+        except AttributeError as e:
             raise ImproperlyConfigured('Error importing template source loader %s: "%s"' % (loader, e))
 
         if hasattr(TemplateLoader, 'load_template_source'):
@@ -185,7 +185,7 @@ def select_template(template_name_list):
     for template_name in template_name_list:
         try:
             return get_template(template_name)
-        except TemplateDoesNotExist, e:
+        except TemplateDoesNotExist as e:
             if e.args[0] not in not_found:
                 not_found.append(e.args[0])
             continue
diff --git a/django/template/loaders/app_directories.py b/django/template/loaders/app_directories.py
index b0560b4..1ddb18e 100644
--- a/django/template/loaders/app_directories.py
+++ b/django/template/loaders/app_directories.py
@@ -19,7 +19,7 @@ app_template_dirs = []
 for app in settings.INSTALLED_APPS:
     try:
         mod = import_module(app)
-    except ImportError, e:
+    except ImportError as e:
         raise ImproperlyConfigured('ImportError %s: %s' % (app, e.args[0]))
     template_dir = os.path.join(os.path.dirname(mod.__file__), 'templates')
     if os.path.isdir(template_dir):
diff --git a/django/test/_doctest.py b/django/test/_doctest.py
index fe9b2f1..af2f409 100644
--- a/django/test/_doctest.py
+++ b/django/test/_doctest.py
@@ -1626,7 +1626,7 @@ class DebugRunner(DocTestRunner):
          ...                                    {}, 'foo', 'foo.py', 0)
          >>> try:
          ...     runner.run(test)
-         ... except UnexpectedException, failure:
+         ... except UnexpectedException as failure:
          ...     pass
 
          >>> failure.test is test
@@ -1654,7 +1654,7 @@ class DebugRunner(DocTestRunner):
 
          >>> try:
          ...    runner.run(test)
-         ... except DocTestFailure, failure:
+         ... except DocTestFailure as failure:
          ...    pass
 
        DocTestFailure objects provide access to the test:
@@ -2164,7 +2164,7 @@ class DocTestCase(unittest.TestCase):
              >>> case = DocTestCase(test)
              >>> try:
              ...     case.debug()
-             ... except UnexpectedException, failure:
+             ... except UnexpectedException as failure:
              ...     pass
 
            The UnexpectedException contains the test, the example, and
@@ -2193,7 +2193,7 @@ class DocTestCase(unittest.TestCase):
 
              >>> try:
              ...    case.debug()
-             ... except DocTestFailure, failure:
+             ... except DocTestFailure as failure:
              ...    pass
 
            DocTestFailure objects provide access to the test:
diff --git a/django/test/client.py b/django/test/client.py
index 6f3b73d..69f72fd 100644
--- a/django/test/client.py
+++ b/django/test/client.py
@@ -379,7 +379,7 @@ class Client(RequestFactory):
 
             try:
                 response = self.handler(environ)
-            except TemplateDoesNotExist, e:
+            except TemplateDoesNotExist as e:
                 # If the view raises an exception, Django will attempt to show
                 # the 500.html template. If that template is not available,
                 # we should ignore the error in favor of re-raising the
diff --git a/django/test/testcases.py b/django/test/testcases.py
index b5e1dc0..7885225 100644
--- a/django/test/testcases.py
+++ b/django/test/testcases.py
@@ -85,7 +85,7 @@ def restore_transaction_methods():
 def assert_and_parse_html(self, html, user_msg, msg):
     try:
         dom = parse_html(html)
-    except HTMLParseError, e:
+    except HTMLParseError as e:
         standardMsg = u'%s\n%s' % (msg, e.msg)
         self.fail(self._formatMessage(user_msg, standardMsg))
     return dom
@@ -1036,7 +1036,7 @@ class LiveServerThread(threading.Thread):
                 try:
                     self.httpd = StoppableWSGIServer(
                         (self.host, port), QuietWSGIRequestHandler)
-                except WSGIServerException, e:
+                except WSGIServerException as e:
                     if sys.version_info < (2, 6):
                         error_code = e.args[0].args[0]
                     else:
@@ -1059,7 +1059,7 @@ class LiveServerThread(threading.Thread):
             self.httpd.set_app(handler)
             self.is_ready.set()
             self.httpd.serve_forever()
-        except Exception, e:
+        except Exception as e:
             self.error = e
             self.is_ready.set()
 
diff --git a/django/utils/daemonize.py b/django/utils/daemonize.py
index 68e5392..a9d5128 100644
--- a/django/utils/daemonize.py
+++ b/django/utils/daemonize.py
@@ -9,7 +9,7 @@ if os.name == 'posix':
         try:
             if os.fork() > 0:
                 sys.exit(0)     # kill off parent
-        except OSError, e:
+        except OSError as e:
             sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror))
             sys.exit(1)
         os.setsid()
@@ -20,7 +20,7 @@ if os.name == 'posix':
         try:
             if os.fork() > 0:
                 os._exit(0)
-        except OSError, e:
+        except OSError as e:
             sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror))
             os._exit(1)
 
diff --git a/django/utils/decorators.py b/django/utils/decorators.py
index 22f33a7..e653a73 100644
--- a/django/utils/decorators.py
+++ b/django/utils/decorators.py
@@ -89,7 +89,7 @@ def make_middleware_decorator(middleware_class):
                         return result
                 try:
                     response = view_func(request, *args, **kwargs)
-                except Exception, e:
+                except Exception as e:
                     if hasattr(middleware, 'process_exception'):
                         result = middleware.process_exception(request, e)
                         if result is not None:
diff --git a/django/utils/dictconfig.py b/django/utils/dictconfig.py
index 42fbd93..ae797af 100644
--- a/django/utils/dictconfig.py
+++ b/django/utils/dictconfig.py
@@ -297,21 +297,21 @@ class DictConfigurator(BaseConfigurator):
                                 level = handler_config.get('level', None)
                                 if level:
                                     handler.setLevel(_checkLevel(level))
-                            except StandardError, e:
+                            except StandardError as e:
                                 raise ValueError('Unable to configure handler '
                                                  '%r: %s' % (name, e))
                 loggers = config.get('loggers', EMPTY_DICT)
                 for name in loggers:
                     try:
                         self.configure_logger(name, loggers[name], True)
-                    except StandardError, e:
+                    except StandardError as e:
                         raise ValueError('Unable to configure logger '
                                          '%r: %s' % (name, e))
                 root = config.get('root', None)
                 if root:
                     try:
                         self.configure_root(root, True)
-                    except StandardError, e:
+                    except StandardError as e:
                         raise ValueError('Unable to configure root '
                                          'logger: %s' % e)
             else:
@@ -326,7 +326,7 @@ class DictConfigurator(BaseConfigurator):
                     try:
                         formatters[name] = self.configure_formatter(
                                                             formatters[name])
-                    except StandardError, e:
+                    except StandardError as e:
                         raise ValueError('Unable to configure '
                                          'formatter %r: %s' % (name, e))
                 # Next, do filters - they don't refer to anything else, either
@@ -334,7 +334,7 @@ class DictConfigurator(BaseConfigurator):
                 for name in filters:
                     try:
                         filters[name] = self.configure_filter(filters[name])
-                    except StandardError, e:
+                    except StandardError as e:
                         raise ValueError('Unable to configure '
                                          'filter %r: %s' % (name, e))
 
@@ -347,7 +347,7 @@ class DictConfigurator(BaseConfigurator):
                         handler = self.configure_handler(handlers[name])
                         handler.name = name
                         handlers[name] = handler
-                    except StandardError, e:
+                    except StandardError as e:
                         raise ValueError('Unable to configure handler '
                                          '%r: %s' % (name, e))
                 # Next, do loggers - they refer to handlers and filters
@@ -386,7 +386,7 @@ class DictConfigurator(BaseConfigurator):
                         existing.remove(name)
                     try:
                         self.configure_logger(name, loggers[name])
-                    except StandardError, e:
+                    except StandardError as e:
                         raise ValueError('Unable to configure logger '
                                          '%r: %s' % (name, e))
 
@@ -409,7 +409,7 @@ class DictConfigurator(BaseConfigurator):
                 if root:
                     try:
                         self.configure_root(root)
-                    except StandardError, e:
+                    except StandardError as e:
                         raise ValueError('Unable to configure root '
                                          'logger: %s' % e)
         finally:
@@ -421,7 +421,7 @@ class DictConfigurator(BaseConfigurator):
             factory = config['()'] # for use in exception handler
             try:
                 result = self.configure_custom(config)
-            except TypeError, te:
+            except TypeError as te:
                 if "'format'" not in str(te):
                     raise
                 #Name of parameter changed from fmt to format.
@@ -451,7 +451,7 @@ class DictConfigurator(BaseConfigurator):
         for f in filters:
             try:
                 filterer.addFilter(self.config['filters'][f])
-            except StandardError, e:
+            except StandardError as e:
                 raise ValueError('Unable to add filter %r: %s' % (f, e))
 
     def configure_handler(self, config):
@@ -460,7 +460,7 @@ class DictConfigurator(BaseConfigurator):
         if formatter:
             try:
                 formatter = self.config['formatters'][formatter]
-            except StandardError, e:
+            except StandardError as e:
                 raise ValueError('Unable to set formatter '
                                  '%r: %s' % (formatter, e))
         level = config.pop('level', None)
@@ -477,7 +477,7 @@ class DictConfigurator(BaseConfigurator):
                 'target' in config:
                 try:
                     config['target'] = self.config['handlers'][config['target']]
-                except StandardError, e:
+                except StandardError as e:
                     raise ValueError('Unable to set target handler '
                                      '%r: %s' % (config['target'], e))
             elif issubclass(klass, logging.handlers.SMTPHandler) and\
@@ -490,7 +490,7 @@ class DictConfigurator(BaseConfigurator):
         kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
         try:
             result = factory(**kwargs)
-        except TypeError, te:
+        except TypeError as te:
             if "'stream'" not in str(te):
                 raise
             #The argument name changed from strm to stream
@@ -512,7 +512,7 @@ class DictConfigurator(BaseConfigurator):
         for h in handlers:
             try:
                 logger.addHandler(self.config['handlers'][h])
-            except StandardError, e:
+            except StandardError as e:
                 raise ValueError('Unable to add handler %r: %s' % (h, e))
 
     def common_logger_config(self, logger, config, incremental=False):
diff --git a/django/utils/encoding.py b/django/utils/encoding.py
index 36e0da2..d9b5944 100644
--- a/django/utils/encoding.py
+++ b/django/utils/encoding.py
@@ -88,7 +88,7 @@ def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'):
             # errors), so that if s is a SafeString, it ends up being a
             # SafeUnicode at the end.
             s = s.decode(encoding, errors)
-    except UnicodeDecodeError, e:
+    except UnicodeDecodeError as e:
         if not isinstance(s, Exception):
             raise DjangoUnicodeDecodeError(s, *e.args)
         else:
diff --git a/django/views/debug.py b/django/views/debug.py
index b549959..14a151f 100644
--- a/django/views/debug.py
+++ b/django/views/debug.py
@@ -77,7 +77,7 @@ def get_exception_reporter_filter(request):
         modname, classname = modpath.rsplit('.', 1)
         try:
             mod = import_module(modname)
-        except ImportError, e:
+        except ImportError as e:
             raise ImproperlyConfigured(
             'Error importing default exception reporter filter %s: "%s"' % (modpath, e))
         try:
diff --git a/extras/csrf_migration_helper.py b/extras/csrf_migration_helper.py
index 94b5a20..0e13163 100755
--- a/extras/csrf_migration_helper.py
+++ b/extras/csrf_migration_helper.py
@@ -173,7 +173,7 @@ class Template(object):
             fd = open(self.absolute_filename)
             try:
                 content = fd.read().decode(TEMPLATE_ENCODING)
-            except UnicodeDecodeError, e:
+            except UnicodeDecodeError as e:
                 message = '%s in %s' % (
                     e[4], self.absolute_filename.encode('UTF-8', 'ignore'))
                 raise UnicodeDecodeError(*(e.args[:4] + (message,)))
diff --git a/tests/modeltests/basic/tests.py b/tests/modeltests/basic/tests.py
index f9141dc..42192e0 100644
--- a/tests/modeltests/basic/tests.py
+++ b/tests/modeltests/basic/tests.py
@@ -374,9 +374,9 @@ class ModelTest(TestCase):
         try:
             Article.objects.all()[0:1] & Article.objects.all()[4:5]
             self.fail('Should raise an AssertionError')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertEqual(str(e), "Cannot combine queries once a slice has been taken.")
-        except Exception, e:
+        except Exception as e:
             self.fail('Should raise an AssertionError, not %s' % e)
 
         # Negative slices are not supported, due to database constraints.
@@ -384,15 +384,15 @@ class ModelTest(TestCase):
         try:
             Article.objects.all()[-1]
             self.fail('Should raise an AssertionError')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertEqual(str(e), "Negative indexing is not supported.")
-        except Exception, e:
+        except Exception as e:
             self.fail('Should raise an AssertionError, not %s' % e)
 
         error = None
         try:
             Article.objects.all()[0:-5]
-        except Exception, e:
+        except Exception as e:
             error = e
         self.assertTrue(isinstance(error, AssertionError))
         self.assertEqual(str(error), "Negative indexing is not supported.")
diff --git a/tests/modeltests/get_or_create/tests.py b/tests/modeltests/get_or_create/tests.py
index f98f0e6..1e300fb 100644
--- a/tests/modeltests/get_or_create/tests.py
+++ b/tests/modeltests/get_or_create/tests.py
@@ -60,7 +60,7 @@ class GetOrCreateTests(TestCase):
         # the actual traceback. Refs #16340.
         try:
             ManualPrimaryKeyTest.objects.get_or_create(id=1, data="Different")
-        except IntegrityError, e:
+        except IntegrityError as e:
             formatted_traceback = traceback.format_exc()
             self.assertIn('obj.save', formatted_traceback)
 
diff --git a/tests/modeltests/invalid_models/tests.py b/tests/modeltests/invalid_models/tests.py
index dac562c..a1084c6 100644
--- a/tests/modeltests/invalid_models/tests.py
+++ b/tests/modeltests/invalid_models/tests.py
@@ -35,7 +35,7 @@ class InvalidModelTestCase(unittest.TestCase):
 
         try:
             module = load_app("modeltests.invalid_models.invalid_models")
-        except Exception, e:
+        except Exception as e:
             self.fail('Unable to load invalid model module')
 
         count = get_validation_errors(self.stdout, module)
diff --git a/tests/modeltests/lookup/tests.py b/tests/modeltests/lookup/tests.py
index 3571e21..ccd7863 100644
--- a/tests/modeltests/lookup/tests.py
+++ b/tests/modeltests/lookup/tests.py
@@ -468,13 +468,13 @@ class LookupTests(TestCase):
         try:
             Article.objects.filter(pub_date_year='2005').count()
             self.fail('FieldError not raised')
-        except FieldError, ex:
+        except FieldError as ex:
             self.assertEqual(str(ex), "Cannot resolve keyword 'pub_date_year' "
                              "into field. Choices are: author, headline, id, pub_date, tag")
         try:
             Article.objects.filter(headline__starts='Article')
             self.fail('FieldError not raised')
-        except FieldError, ex:
+        except FieldError as ex:
             self.assertEqual(str(ex), "Join on field 'headline' not permitted. "
                              "Did you misspell 'starts' for the lookup type?")
 
diff --git a/tests/modeltests/select_for_update/tests.py b/tests/modeltests/select_for_update/tests.py
index 65bc13a..dba7889 100644
--- a/tests/modeltests/select_for_update/tests.py
+++ b/tests/modeltests/select_for_update/tests.py
@@ -169,9 +169,9 @@ class SelectForUpdateTests(TransactionTestCase):
             people[0].name = 'Fred'
             people[0].save()
             transaction.commit()
-        except DatabaseError, e:
+        except DatabaseError as e:
             status.append(e)
-        except Exception, e:
+        except Exception as e:
             raise
         finally:
             # This method is run in a separate thread. It uses its own
@@ -246,7 +246,7 @@ class SelectForUpdateTests(TransactionTestCase):
                         )
                     )
                 )
-            except DatabaseError, e:
+            except DatabaseError as e:
                 status.append(e)
             finally:
                 # This method is run in a separate thread. It uses its own
diff --git a/tests/modeltests/validation/models.py b/tests/modeltests/validation/models.py
index 8010701..7791a09 100644
--- a/tests/modeltests/validation/models.py
+++ b/tests/modeltests/validation/models.py
@@ -100,6 +100,6 @@ try:
     class MultipleAutoFields(models.Model):
         auto1 = models.AutoField(primary_key=True)
         auto2 = models.AutoField(primary_key=True)
-except AssertionError, assertion_error:
+except AssertionError as assertion_error:
     pass # Fail silently
 assert str(assertion_error) == u"A model can't have more than one AutoField."
\ No newline at end of file
diff --git a/tests/modeltests/validation/test_error_messages.py b/tests/modeltests/validation/test_error_messages.py
index 4a2ad1f..04ad7aa 100644
--- a/tests/modeltests/validation/test_error_messages.py
+++ b/tests/modeltests/validation/test_error_messages.py
@@ -10,13 +10,13 @@ class ValidationMessagesTest(TestCase):
         self.assertRaises(ValidationError, f.clean, 'foo', None)
         try:
             f.clean('foo', None)
-        except ValidationError, e:
+        except ValidationError as e:
             self.assertEqual(e.messages, [u"'foo' value must be an integer."])
         # primary_key must be True. Refs #12467.
         self.assertRaises(AssertionError, models.AutoField, 'primary_key', False)
         try:
             models.AutoField(primary_key=False)
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertEqual(str(e), "AutoFields must have primary_key=True.")
 
     def test_integer_field_raises_error_message(self):
@@ -24,7 +24,7 @@ class ValidationMessagesTest(TestCase):
         self.assertRaises(ValidationError, f.clean, 'foo', None)
         try:
             f.clean('foo', None)
-        except ValidationError, e:
+        except ValidationError as e:
             self.assertEqual(e.messages, [u"'foo' value must be an integer."])
 
     def test_boolean_field_raises_error_message(self):
@@ -32,7 +32,7 @@ class ValidationMessagesTest(TestCase):
         self.assertRaises(ValidationError, f.clean, 'foo', None)
         try:
             f.clean('foo', None)
-        except ValidationError, e:
+        except ValidationError as e:
             self.assertEqual(e.messages,
                         [u"'foo' value must be either True or False."])
 
@@ -41,7 +41,7 @@ class ValidationMessagesTest(TestCase):
         self.assertRaises(ValidationError, f.clean, 'foo', None)
         try:
             f.clean('foo', None)
-        except ValidationError, e:
+        except ValidationError as e:
             self.assertEqual(e.messages, [u"'foo' value must be a float."])
 
     def test_decimal_field_raises_error_message(self):
@@ -49,7 +49,7 @@ class ValidationMessagesTest(TestCase):
         self.assertRaises(ValidationError, f.clean, 'foo', None)
         try:
             f.clean('foo', None)
-        except ValidationError, e:
+        except ValidationError as e:
             self.assertEqual(e.messages,
                         [u"'foo' value must be a decimal number."])
 
@@ -58,7 +58,7 @@ class ValidationMessagesTest(TestCase):
         self.assertRaises(ValidationError, f.clean, 'foo', None)
         try:
             f.clean('foo', None)
-        except ValidationError, e:
+        except ValidationError as e:
             self.assertEqual(e.messages,
                         [u"'foo' value must be either None, True or False."])
 
@@ -67,7 +67,7 @@ class ValidationMessagesTest(TestCase):
         self.assertRaises(ValidationError, f.clean, 'foo', None)
         try:
             f.clean('foo', None)
-        except ValidationError, e:
+        except ValidationError as e:
             self.assertEqual(e.messages, [
                 u"'foo' value has an invalid date format. "
                 u"It must be in YYYY-MM-DD format."])
@@ -75,7 +75,7 @@ class ValidationMessagesTest(TestCase):
         self.assertRaises(ValidationError, f.clean, 'aaaa-10-10', None)
         try:
             f.clean('aaaa-10-10', None)
-        except ValidationError, e:
+        except ValidationError as e:
             self.assertEqual(e.messages, [
                 u"'aaaa-10-10' value has an invalid date format. "
                 u"It must be in YYYY-MM-DD format."])
@@ -83,7 +83,7 @@ class ValidationMessagesTest(TestCase):
         self.assertRaises(ValidationError, f.clean, '2011-13-10', None)
         try:
             f.clean('2011-13-10', None)
-        except ValidationError, e:
+        except ValidationError as e:
             self.assertEqual(e.messages, [
                 u"'2011-13-10' value has the correct format (YYYY-MM-DD) "
                 u"but it is an invalid date."])
@@ -91,7 +91,7 @@ class ValidationMessagesTest(TestCase):
         self.assertRaises(ValidationError, f.clean, '2011-10-32', None)
         try:
             f.clean('2011-10-32', None)
-        except ValidationError, e:
+        except ValidationError as e:
             self.assertEqual(e.messages, [
                 u"'2011-10-32' value has the correct format (YYYY-MM-DD) "
                 u"but it is an invalid date."])
@@ -102,7 +102,7 @@ class ValidationMessagesTest(TestCase):
         self.assertRaises(ValidationError, f.clean, 'foo', None)
         try:
             f.clean('foo', None)
-        except ValidationError, e:
+        except ValidationError as e:
             self.assertEqual(e.messages, [
                 u"'foo' value has an invalid format. It must be "
                 u"in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."])
@@ -111,7 +111,7 @@ class ValidationMessagesTest(TestCase):
         self.assertRaises(ValidationError, f.clean, '2011-10-32', None)
         try:
             f.clean('2011-10-32', None)
-        except ValidationError, e:
+        except ValidationError as e:
             self.assertEqual(e.messages, [
                 u"'2011-10-32' value has the correct format "
                 u"(YYYY-MM-DD) but it is an invalid date."])
@@ -120,7 +120,7 @@ class ValidationMessagesTest(TestCase):
         self.assertRaises(ValidationError, f.clean, '2011-10-32 10:10', None)
         try:
             f.clean('2011-10-32 10:10', None)
-        except ValidationError, e:
+        except ValidationError as e:
             self.assertEqual(e.messages, [
                 u"'2011-10-32 10:10' value has the correct format "
                 u"(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) "
@@ -132,7 +132,7 @@ class ValidationMessagesTest(TestCase):
         self.assertRaises(ValidationError, f.clean, 'foo', None)
         try:
             f.clean('foo', None)
-        except ValidationError, e:
+        except ValidationError as e:
             self.assertEqual(e.messages, [
                 u"'foo' value has an invalid format. It must be in "
                 u"HH:MM[:ss[.uuuuuu]] format."])
@@ -140,7 +140,7 @@ class ValidationMessagesTest(TestCase):
         self.assertRaises(ValidationError, f.clean, '25:50', None)
         try:
             f.clean('25:50', None)
-        except ValidationError, e:
+        except ValidationError as e:
             self.assertEqual(e.messages, [
                 u"'25:50' value has the correct format "
                 u"(HH:MM[:ss[.uuuuuu]]) but it is an invalid time."])
diff --git a/tests/modeltests/validation/test_unique.py b/tests/modeltests/validation/test_unique.py
index 3ae981d..e31698d 100644
--- a/tests/modeltests/validation/test_unique.py
+++ b/tests/modeltests/validation/test_unique.py
@@ -115,19 +115,19 @@ class PerformUniqueChecksTest(TestCase):
         p = FlexibleDatePost(title="Django 1.0 is released")
         try:
             p.full_clean()
-        except ValidationError, e:
+        except ValidationError as e:
             self.fail("unique_for_date checks shouldn't trigger when the associated DateField is None.")
 
         p = FlexibleDatePost(slug="Django 1.0")
         try:
             p.full_clean()
-        except ValidationError, e:
+        except ValidationError as e:
             self.fail("unique_for_year checks shouldn't trigger when the associated DateField is None.")
 
         p = FlexibleDatePost(subtitle="Finally")
         try:
             p.full_clean()
-        except ValidationError, e:
+        except ValidationError as e:
             self.fail("unique_for_month checks shouldn't trigger when the associated DateField is None.")
 
     def test_unique_errors(self):
diff --git a/tests/regressiontests/app_loading/tests.py b/tests/regressiontests/app_loading/tests.py
index 5173338..0e66a5a 100644
--- a/tests/regressiontests/app_loading/tests.py
+++ b/tests/regressiontests/app_loading/tests.py
@@ -61,7 +61,7 @@ class EggLoadingTest(TestCase):
         self.assertRaises(ImportError, load_app, 'broken_app')
         try:
             load_app('broken_app')
-        except ImportError, e:
+        except ImportError as e:
             # Make sure the message is indicating the actual
             # problem in the broken app.
             self.assertTrue("modelz" in e.args[0])
diff --git a/tests/regressiontests/backends/tests.py b/tests/regressiontests/backends/tests.py
index cfb662e..e2e712a 100644
--- a/tests/regressiontests/backends/tests.py
+++ b/tests/regressiontests/backends/tests.py
@@ -544,7 +544,7 @@ class ThreadTests(TestCase):
                 connections['default'] = main_thread_connection
                 try:
                     models.Person.objects.get(first_name="John", last_name="Doe")
-                except DatabaseError, e:
+                except DatabaseError as e:
                     exceptions.append(e)
             t = threading.Thread(target=runner, args=[connections['default']])
             t.start()
@@ -582,7 +582,7 @@ class ThreadTests(TestCase):
             def runner2(other_thread_connection):
                 try:
                     other_thread_connection.close()
-                except DatabaseError, e:
+                except DatabaseError as e:
                     exceptions.add(e)
             t2 = threading.Thread(target=runner2, args=[connections['default']])
             t2.start()
@@ -599,7 +599,7 @@ class ThreadTests(TestCase):
             def runner2(other_thread_connection):
                 try:
                     other_thread_connection.close()
-                except DatabaseError, e:
+                except DatabaseError as e:
                     exceptions.add(e)
             # Enable thread sharing
             connections['default'].allow_thread_sharing = True
diff --git a/tests/regressiontests/file_uploads/tests.py b/tests/regressiontests/file_uploads/tests.py
index ffa2017..4e5020d 100644
--- a/tests/regressiontests/file_uploads/tests.py
+++ b/tests/regressiontests/file_uploads/tests.py
@@ -303,7 +303,7 @@ class FileUploadTests(TestCase):
         # it raises when there is an attempt to read more than the available bytes:
         try:
             client.FakePayload('a').read(2)
-        except Exception, reference_error:
+        except Exception as reference_error:
             pass
 
         # install the custom handler that tries to access request.POST
@@ -311,12 +311,12 @@ class FileUploadTests(TestCase):
 
         try:
             response = self.client.post('/file_uploads/upload_errors/', post_data)
-        except reference_error.__class__, err:
+        except reference_error.__class__ as err:
             self.failIf(
                 str(err) == str(reference_error),
                 "Caught a repeated exception that'll cause an infinite loop in file uploads."
             )
-        except Exception, err:
+        except Exception as err:
             # CustomUploadError is the error that should have been raised
             self.assertEqual(err.__class__, uploadhandler.CustomUploadError)
 
@@ -373,9 +373,9 @@ class DirectoryCreationTests(unittest.TestCase):
         os.chmod(temp_storage.location, 0500)
         try:
             self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', 'x'))
-        except OSError, err:
+        except OSError as err:
             self.assertEqual(err.errno, errno.EACCES)
-        except Exception, err:
+        except Exception as err:
             self.fail("OSError [Errno %s] not raised." % errno.EACCES)
 
     def test_not_a_directory(self):
@@ -385,7 +385,7 @@ class DirectoryCreationTests(unittest.TestCase):
         fd.close()
         try:
             self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', 'x'))
-        except IOError, err:
+        except IOError as err:
             # The test needs to be done on a specific string as IOError
             # is raised even without the patch (just not early enough)
             self.assertEqual(err.args[0],
diff --git a/tests/regressiontests/forms/tests/error_messages.py b/tests/regressiontests/forms/tests/error_messages.py
index b7b4e98..9e1a6c9 100644
--- a/tests/regressiontests/forms/tests/error_messages.py
+++ b/tests/regressiontests/forms/tests/error_messages.py
@@ -15,7 +15,7 @@ class AssertFormErrorsMixin(object):
         try:
             the_callable(*args, **kwargs)
             self.fail("Testing the 'clean' method on %s failed to raise a ValidationError.")
-        except ValidationError, e:
+        except ValidationError as e:
             self.assertEqual(e.messages, expected)
 
 class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin):
diff --git a/tests/regressiontests/forms/tests/fields.py b/tests/regressiontests/forms/tests/fields.py
index 03e0ff6..138d3af 100644
--- a/tests/regressiontests/forms/tests/fields.py
+++ b/tests/regressiontests/forms/tests/fields.py
@@ -660,12 +660,12 @@ class FieldsTests(SimpleTestCase):
         self.assertRaises(ValidationError, f.clean, 'http://qa-dev.w3.org/link-testsuite/http.php?code=405') # Method not allowed
         try:
             f.clean('http://www.broken.djangoproject.com') # bad domain
-        except ValidationError, e:
+        except ValidationError as e:
             self.assertEqual("[u'This URL appears to be a broken link.']", str(e))
         self.assertRaises(ValidationError, f.clean, 'http://qa-dev.w3.org/link-testsuite/http.php?code=400') # good domain, bad page
         try:
             f.clean('http://google.com/we-love-microsoft.html') # good domain, bad page
-        except ValidationError, e:
+        except ValidationError as e:
             self.assertEqual("[u'This URL appears to be a broken link.']", str(e))
 
     @verify_exists_urls(('http://www.google.com/',))
@@ -719,7 +719,7 @@ class FieldsTests(SimpleTestCase):
         # Valid but non-existent IDN
         try:
             f.clean(u'http://broken.עברית.idn.icann.org/')
-        except ValidationError, e:
+        except ValidationError as e:
             self.assertEqual("[u'This URL appears to be a broken link.']", str(e))
 
     @verify_exists_urls((u'http://xn--hxargifdar.idn.icann.org/%CE%91%CF%81%CF%87%CE%B9%CE%BA%CE%AE_%CF%83%CE%B5%CE%BB%CE%AF%CE%B4%CE%B1',))
diff --git a/tests/regressiontests/forms/tests/validators.py b/tests/regressiontests/forms/tests/validators.py
index cadf660..a4cb324 100644
--- a/tests/regressiontests/forms/tests/validators.py
+++ b/tests/regressiontests/forms/tests/validators.py
@@ -12,5 +12,5 @@ class TestFieldWithValidators(TestCase):
         self.assertRaises(ValidationError, field.clean, 'not int nor mail')
         try:
             field.clean('not int nor mail')
-        except ValidationError, e:
+        except ValidationError as e:
             self.assertEqual(2, len(e.messages))
diff --git a/tests/regressiontests/middleware/tests.py b/tests/regressiontests/middleware/tests.py
index 6a1896a..5e48f8d 100644
--- a/tests/regressiontests/middleware/tests.py
+++ b/tests/regressiontests/middleware/tests.py
@@ -88,7 +88,7 @@ class CommonMiddlewareTest(TestCase):
             request)
         try:
             CommonMiddleware().process_request(request)
-        except RuntimeError, e:
+        except RuntimeError as e:
             self.assertTrue('end in a slash' in str(e))
         settings.DEBUG = False
 
@@ -202,7 +202,7 @@ class CommonMiddlewareTest(TestCase):
           request)
       try:
           CommonMiddleware().process_request(request)
-      except RuntimeError, e:
+      except RuntimeError as e:
           self.assertTrue('end in a slash' in str(e))
       settings.DEBUG = False
 
diff --git a/tests/regressiontests/middleware_exceptions/tests.py b/tests/regressiontests/middleware_exceptions/tests.py
index ac5f09a..d1acbfd 100644
--- a/tests/regressiontests/middleware_exceptions/tests.py
+++ b/tests/regressiontests/middleware_exceptions/tests.py
@@ -118,13 +118,13 @@ class BaseMiddlewareExceptionTest(TestCase):
     def assert_exceptions_handled(self, url, errors, extra_error=None):
         try:
             response = self.client.get(url)
-        except TestException, e:
+        except TestException as e:
             # Test client intentionally re-raises any exceptions being raised
             # during request handling. Hence actual testing that exception was
             # properly handled is done by relying on got_request_exception
             # signal being sent.
             pass
-        except Exception, e:
+        except Exception as e:
             if type(extra_error) != type(e):
                 self.fail("Unexpected exception: %s" % e)
         self.assertEqual(len(self.exceptions), len(errors))
diff --git a/tests/regressiontests/model_fields/tests.py b/tests/regressiontests/model_fields/tests.py
index 8fe67fb..ea1e1c7 100644
--- a/tests/regressiontests/model_fields/tests.py
+++ b/tests/regressiontests/model_fields/tests.py
@@ -44,7 +44,7 @@ class BasicFieldTests(test.TestCase):
         nullboolean = NullBooleanModel(nbfield=None)
         try:
             nullboolean.full_clean()
-        except ValidationError, e:
+        except ValidationError as e:
             self.fail("NullBooleanField failed validation with value of None: %s" % e.messages)
 
     def test_field_repr(self):
diff --git a/tests/regressiontests/model_forms_regress/tests.py b/tests/regressiontests/model_forms_regress/tests.py
index caf24d3..09da973 100644
--- a/tests/regressiontests/model_forms_regress/tests.py
+++ b/tests/regressiontests/model_forms_regress/tests.py
@@ -333,7 +333,7 @@ class InvalidFieldAndFactory(TestCase):
                 class Meta:
                     model = Person
                     fields = ('name', 'no-field')
-        except FieldError, e:
+        except FieldError as e:
             # Make sure the exception contains some reference to the
             # field responsible for the problem.
             self.assertTrue('no-field' in e.args[0])
diff --git a/tests/regressiontests/servers/tests.py b/tests/regressiontests/servers/tests.py
index d237c83..ac92bec 100644
--- a/tests/regressiontests/servers/tests.py
+++ b/tests/regressiontests/servers/tests.py
@@ -164,7 +164,7 @@ class LiveServerViews(LiveServerBase):
         """
         try:
             self.urlopen('/')
-        except urllib2.HTTPError, err:
+        except urllib2.HTTPError as err:
             self.assertEquals(err.code, 404, 'Expected 404 response')
         else:
             self.fail('Expected 404 response')
diff --git a/tests/regressiontests/settings_tests/tests.py b/tests/regressiontests/settings_tests/tests.py
index a2e6c49..4b0ede3 100644
--- a/tests/regressiontests/settings_tests/tests.py
+++ b/tests/regressiontests/settings_tests/tests.py
@@ -65,7 +65,7 @@ class ClassDecoratedTestCase(ClassDecoratedTestCaseSuper):
         """
         try:
             super(ClassDecoratedTestCase, self).test_max_recursion_error()
-        except RuntimeError, e:
+        except RuntimeError as e:
             self.fail()
 
 ClassDecoratedTestCase = override_settings(TEST='override')(ClassDecoratedTestCase)
diff --git a/tests/regressiontests/templates/tests.py b/tests/regressiontests/templates/tests.py
index f74aa75..24dccd6 100644
--- a/tests/regressiontests/templates/tests.py
+++ b/tests/regressiontests/templates/tests.py
@@ -42,7 +42,7 @@ from .response import (TemplateResponseTest, BaseTemplateResponseTest,
 
 try:
     from .loaders import RenderToStringTest, EggLoaderTest
-except ImportError, e:
+except ImportError as e:
     if "pkg_resources" in e.message:
         pass # If setuptools isn't installed, that's fine. Just move on.
     else:
@@ -280,7 +280,7 @@ class Templates(unittest.TestCase):
             try:
                 tmpl = loader.select_template([load_name])
                 r = tmpl.render(template.Context({}))
-            except template.TemplateDoesNotExist, e:
+            except template.TemplateDoesNotExist as e:
                 settings.TEMPLATE_DEBUG = old_td
                 self.assertEqual(e.args[0], 'missing.html')
             self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r)
@@ -313,7 +313,7 @@ class Templates(unittest.TestCase):
             r = None
             try:
                 r = tmpl.render(template.Context({}))
-            except template.TemplateDoesNotExist, e:
+            except template.TemplateDoesNotExist as e:
                 settings.TEMPLATE_DEBUG = old_td
                 self.assertEqual(e.args[0], 'missing.html')
             self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r)
@@ -340,7 +340,7 @@ class Templates(unittest.TestCase):
             r = None
             try:
                 r = tmpl.render(template.Context({}))
-            except template.TemplateDoesNotExist, e:
+            except template.TemplateDoesNotExist as e:
                 self.assertEqual(e.args[0], 'missing.html')
             self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r)
 
@@ -349,7 +349,7 @@ class Templates(unittest.TestCase):
             tmpl = loader.get_template(load_name)
             try:
                 tmpl.render(template.Context({}))
-            except template.TemplateDoesNotExist, e:
+            except template.TemplateDoesNotExist as e:
                 self.assertEqual(e.args[0], 'missing.html')
             self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r)
         finally:
@@ -393,7 +393,7 @@ class Templates(unittest.TestCase):
         from django.template import Template, TemplateSyntaxError
         try:
             t = Template("{% if 1 %}lala{% endblock %}{% endif %}")
-        except TemplateSyntaxError, e:
+        except TemplateSyntaxError as e:
             self.assertEqual(e.args[0], "Invalid block tag: 'endblock', expected 'elif', 'else' or 'endif'")
 
     def test_templates(self):
@@ -1714,7 +1714,7 @@ class TemplateTagLoading(unittest.TestCase):
         self.assertRaises(template.TemplateSyntaxError, template.Template, ttext)
         try:
             template.Template(ttext)
-        except template.TemplateSyntaxError, e:
+        except template.TemplateSyntaxError as e:
             self.assertTrue('ImportError' in e.args[0])
             self.assertTrue('Xtemplate' in e.args[0])
 
@@ -1726,7 +1726,7 @@ class TemplateTagLoading(unittest.TestCase):
         self.assertRaises(template.TemplateSyntaxError, template.Template, ttext)
         try:
             template.Template(ttext)
-        except template.TemplateSyntaxError, e:
+        except template.TemplateSyntaxError as e:
             self.assertTrue('ImportError' in e.args[0])
             self.assertTrue('Xtemplate' in e.args[0])
 
diff --git a/tests/regressiontests/test_client_regress/models.py b/tests/regressiontests/test_client_regress/models.py
index 0f98b2c..72ceff4 100644
--- a/tests/regressiontests/test_client_regress/models.py
+++ b/tests/regressiontests/test_client_regress/models.py
@@ -39,83 +39,83 @@ class AssertContainsTests(TestCase):
 
         try:
             self.assertContains(response, 'text', status_code=999)
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("Couldn't retrieve content: Response code was 200 (expected 999)", str(e))
         try:
             self.assertContains(response, 'text', status_code=999, msg_prefix='abc')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("abc: Couldn't retrieve content: Response code was 200 (expected 999)", str(e))
 
         try:
             self.assertNotContains(response, 'text', status_code=999)
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("Couldn't retrieve content: Response code was 200 (expected 999)", str(e))
         try:
             self.assertNotContains(response, 'text', status_code=999, msg_prefix='abc')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("abc: Couldn't retrieve content: Response code was 200 (expected 999)", str(e))
 
         try:
             self.assertNotContains(response, 'once')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("Response should not contain 'once'", str(e))
         try:
             self.assertNotContains(response, 'once', msg_prefix='abc')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("abc: Response should not contain 'once'", str(e))
 
         try:
             self.assertContains(response, 'never', 1)
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("Found 0 instances of 'never' in response (expected 1)", str(e))
         try:
             self.assertContains(response, 'never', 1, msg_prefix='abc')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("abc: Found 0 instances of 'never' in response (expected 1)", str(e))
 
         try:
             self.assertContains(response, 'once', 0)
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("Found 1 instances of 'once' in response (expected 0)", str(e))
         try:
             self.assertContains(response, 'once', 0, msg_prefix='abc')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("abc: Found 1 instances of 'once' in response (expected 0)", str(e))
 
         try:
             self.assertContains(response, 'once', 2)
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("Found 1 instances of 'once' in response (expected 2)", str(e))
         try:
             self.assertContains(response, 'once', 2, msg_prefix='abc')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("abc: Found 1 instances of 'once' in response (expected 2)", str(e))
 
         try:
             self.assertContains(response, 'twice', 1)
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("Found 2 instances of 'twice' in response (expected 1)", str(e))
         try:
             self.assertContains(response, 'twice', 1, msg_prefix='abc')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("abc: Found 2 instances of 'twice' in response (expected 1)", str(e))
 
         try:
             self.assertContains(response, 'thrice')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("Couldn't find 'thrice' in response", str(e))
         try:
             self.assertContains(response, 'thrice', msg_prefix='abc')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("abc: Couldn't find 'thrice' in response", str(e))
 
         try:
             self.assertContains(response, 'thrice', 3)
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("Found 0 instances of 'thrice' in response (expected 3)", str(e))
         try:
             self.assertContains(response, 'thrice', 3, msg_prefix='abc')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("abc: Found 0 instances of 'thrice' in response (expected 3)", str(e))
 
     def test_unicode_contains(self):
@@ -176,12 +176,12 @@ class AssertTemplateUsedTests(TestCase):
 
         try:
             self.assertTemplateUsed(response, 'GET Template')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("No templates used to render the response", str(e))
 
         try:
             self.assertTemplateUsed(response, 'GET Template', msg_prefix='abc')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("abc: No templates used to render the response", str(e))
 
     def test_single_context(self):
@@ -190,22 +190,22 @@ class AssertTemplateUsedTests(TestCase):
 
         try:
             self.assertTemplateNotUsed(response, 'Empty GET Template')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("Template 'Empty GET Template' was used unexpectedly in rendering the response", str(e))
 
         try:
             self.assertTemplateNotUsed(response, 'Empty GET Template', msg_prefix='abc')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("abc: Template 'Empty GET Template' was used unexpectedly in rendering the response", str(e))
 
         try:
             self.assertTemplateUsed(response, 'Empty POST Template')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template", str(e))
 
         try:
             self.assertTemplateUsed(response, 'Empty POST Template', msg_prefix='abc')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("abc: Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template", str(e))
 
     def test_multiple_context(self):
@@ -221,17 +221,17 @@ class AssertTemplateUsedTests(TestCase):
         self.assertContains(response, 'POST data OK')
         try:
             self.assertTemplateNotUsed(response, "form_view.html")
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("Template 'form_view.html' was used unexpectedly in rendering the response", str(e))
 
         try:
             self.assertTemplateNotUsed(response, 'base.html')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("Template 'base.html' was used unexpectedly in rendering the response", str(e))
 
         try:
             self.assertTemplateUsed(response, "Valid POST Template")
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("Template 'Valid POST Template' was not a template used to render the response. Actual template(s) used: form_view.html, base.html", str(e))
 
 class AssertRedirectsTests(TestCase):
@@ -241,12 +241,12 @@ class AssertRedirectsTests(TestCase):
         response = self.client.get('/test_client/permanent_redirect_view/')
         try:
             self.assertRedirects(response, '/test_client/get_view/')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("Response didn't redirect as expected: Response code was 301 (expected 302)", str(e))
 
         try:
             self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("abc: Response didn't redirect as expected: Response code was 301 (expected 302)", str(e))
 
     def test_lost_query(self):
@@ -254,12 +254,12 @@ class AssertRedirectsTests(TestCase):
         response = self.client.get('/test_client/redirect_view/', {'var': 'value'})
         try:
             self.assertRedirects(response, '/test_client/get_view/')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("Response redirected to 'http://testserver/test_client/get_view/?var=value', expected 'http://testserver/test_client/get_view/'", str(e))
 
         try:
             self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("abc: Response redirected to 'http://testserver/test_client/get_view/?var=value', expected 'http://testserver/test_client/get_view/'", str(e))
 
     def test_incorrect_target(self):
@@ -268,7 +268,7 @@ class AssertRedirectsTests(TestCase):
         try:
             # Should redirect to get_view
             self.assertRedirects(response, '/test_client/some_view/')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("Response didn't redirect as expected: Response code was 301 (expected 302)", str(e))
 
     def test_target_page(self):
@@ -277,13 +277,13 @@ class AssertRedirectsTests(TestCase):
         try:
             # The redirect target responds with a 301 code, not 200
             self.assertRedirects(response, 'http://testserver/test_client/permanent_redirect_view/')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)", str(e))
 
         try:
             # The redirect target responds with a 301 code, not 200
             self.assertRedirects(response, 'http://testserver/test_client/permanent_redirect_view/', msg_prefix='abc')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("abc: Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)", str(e))
 
     def test_redirect_chain(self):
@@ -386,12 +386,12 @@ class AssertRedirectsTests(TestCase):
         response = self.client.get('/test_client/get_view/', follow=True)
         try:
             self.assertRedirects(response, '/test_client/get_view/')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
 
         try:
             self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("abc: Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
 
     def test_redirect_on_non_redirect_page(self):
@@ -400,12 +400,12 @@ class AssertRedirectsTests(TestCase):
         response = self.client.get('/test_client/get_view/')
         try:
             self.assertRedirects(response, '/test_client/get_view/')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
 
         try:
             self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("abc: Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
 
 
@@ -425,11 +425,11 @@ class AssertFormErrorTests(TestCase):
 
         try:
             self.assertFormError(response, 'wrong_form', 'some_field', 'Some error.')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("The form 'wrong_form' was not used to render the response", str(e))
         try:
             self.assertFormError(response, 'wrong_form', 'some_field', 'Some error.', msg_prefix='abc')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("abc: The form 'wrong_form' was not used to render the response", str(e))
 
     def test_unknown_field(self):
@@ -447,11 +447,11 @@ class AssertFormErrorTests(TestCase):
 
         try:
             self.assertFormError(response, 'form', 'some_field', 'Some error.')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("The form 'form' in context 0 does not contain the field 'some_field'", str(e))
         try:
             self.assertFormError(response, 'form', 'some_field', 'Some error.', msg_prefix='abc')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("abc: The form 'form' in context 0 does not contain the field 'some_field'", str(e))
 
     def test_noerror_field(self):
@@ -469,11 +469,11 @@ class AssertFormErrorTests(TestCase):
 
         try:
             self.assertFormError(response, 'form', 'value', 'Some error.')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("The field 'value' on form 'form' in context 0 contains no errors", str(e))
         try:
             self.assertFormError(response, 'form', 'value', 'Some error.', msg_prefix='abc')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("abc: The field 'value' on form 'form' in context 0 contains no errors", str(e))
 
     def test_unknown_error(self):
@@ -491,11 +491,11 @@ class AssertFormErrorTests(TestCase):
 
         try:
             self.assertFormError(response, 'form', 'email', 'Some error.')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [u'Enter a valid e-mail address.'])", str(e))
         try:
             self.assertFormError(response, 'form', 'email', 'Some error.', msg_prefix='abc')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("abc: The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [u'Enter a valid e-mail address.'])", str(e))
 
     def test_unknown_nonfield_error(self):
@@ -516,11 +516,11 @@ class AssertFormErrorTests(TestCase):
 
         try:
             self.assertFormError(response, 'form', None, 'Some error.')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("The form 'form' in context 0 does not contain the non-field error 'Some error.' (actual errors: )", str(e))
         try:
             self.assertFormError(response, 'form', None, 'Some error.', msg_prefix='abc')
-        except AssertionError, e:
+        except AssertionError as e:
             self.assertIn("abc: The form 'form' in context 0 does not contain the non-field error 'Some error.' (actual errors: )", str(e))
 
 class LoginTests(TestCase):
@@ -677,7 +677,7 @@ class ContextTests(TestCase):
         try:
             response.context['does-not-exist']
             self.fail('Should not be able to retrieve non-existent key')
-        except KeyError, e:
+        except KeyError as e:
             self.assertEqual(e.args[0], 'does-not-exist')
 
     def test_inherited_context(self):
@@ -693,7 +693,7 @@ class ContextTests(TestCase):
         try:
             response.context['does-not-exist']
             self.fail('Should not be able to retrieve non-existent key')
-        except KeyError, e:
+        except KeyError as e:
             self.assertEqual(e.args[0], 'does-not-exist')
 
     def test_15368(self):
diff --git a/tests/regressiontests/urlpatterns_reverse/tests.py b/tests/regressiontests/urlpatterns_reverse/tests.py
index a1c9244..d25235e 100644
--- a/tests/regressiontests/urlpatterns_reverse/tests.py
+++ b/tests/regressiontests/urlpatterns_reverse/tests.py
@@ -161,7 +161,7 @@ class URLPatternReverse(TestCase):
         for name, expected, args, kwargs in test_data:
             try:
                 got = reverse(name, args=args, kwargs=kwargs)
-            except NoReverseMatch, e:
+            except NoReverseMatch as e:
                 self.assertEqual(expected, NoReverseMatch)
             else:
                 self.assertEqual(got, expected)
@@ -207,7 +207,7 @@ class ResolverTests(unittest.TestCase):
         try:
             resolve('/included/non-existent-url', urlconf=urls)
             self.fail('resolve did not raise a 404')
-        except Resolver404, e:
+        except Resolver404 as e:
             # make sure we at least matched the root ('/') url resolver:
             self.assertTrue('tried' in e.args[0])
             tried = e.args[0]['tried']
