From c3791463a5a9674f8e0148fbab57eae23c138896 Mon Sep 17 00:00:00 2001
From: Jason Myers <jason@jasonamyers.com>
Date: Sat, 2 Nov 2013 16:34:05 -0500
Subject: [PATCH 1/8] Fixing E302 Errors

Signed-off-by: Jason Myers <jason@jasonamyers.com>
---
 django/forms/widgets.py                       | 14 ++-
 setup.cfg                                     |  2 +-
 tests/multiple_database/tests.py              | 36 +++++---
 tests/mutually_referential/models.py          |  1 +
 tests/nested_foreign_keys/models.py           |  2 +
 tests/null_fk/models.py                       |  7 ++
 tests/null_fk_ordering/models.py              |  4 +
 tests/null_queries/models.py                  |  5 +
 tests/one_to_one/models.py                    |  9 +-
 tests/one_to_one/tests.py                     |  1 +
 tests/order_with_respect_to/models.py         |  2 +
 tests/ordering/models.py                      |  1 +
 tests/prefetch_related/models.py              |  5 +
 tests/proxy_model_inheritance/models.py       |  2 +
 tests/proxy_models/models.py                  | 26 ++++++
 tests/queries/models.py                       | 91 +++++++++++++++++++
 tests/queries/tests.py                        | 44 ++++++---
 tests/queryset_pickle/models.py               |  6 ++
 tests/raw_query/models.py                     |  4 +
 tests/responses/tests.py                      |  1 +
 tests/reverse_lookup/models.py                |  2 +
 tests/reverse_single_related/models.py        |  2 +
 tests/select_related/models.py                | 10 ++
 tests/select_related_onetoone/models.py       |  2 +
 tests/select_related_regress/models.py        | 28 ++++++
 tests/serializers/tests.py                    | 12 ++-
 tests/serializers_regress/models.py           | 63 +++++++++++++
 tests/serializers_regress/tests.py            | 48 +++++++---
 tests/servers/tests.py                        |  1 +
 tests/settings_tests/tests.py                 |  1 +
 tests/signals/models.py                       |  1 +
 tests/signals/tests.py                        |  2 +
 tests/signals_regress/models.py               |  1 +
 tests/signing/tests.py                        |  1 +
 tests/sites_framework/models.py               |  6 ++
 tests/staticfiles_tests/storage.py            |  1 +
 tests/str/models.py                           |  1 +
 tests/string_lookup/models.py                 |  5 +
 tests/syndication/tests.py                    |  1 +
 tests/tablespaces/models.py                   |  4 +
 tests/tablespaces/tests.py                    |  2 +
 tests/template_tests/filters.py               | 13 ++-
 tests/template_tests/templatetags/bad_tag.py  |  2 +
 tests/template_tests/templatetags/custom.py   | 49 ++++++++++
 .../templatetags/subpackage/echo.py           |  1 +
 tests/template_tests/test_callables.py        |  1 +
 tests/template_tests/test_loaders.py          | 13 +--
 tests/template_tests/test_nodelist.py         |  3 +-
 tests/template_tests/test_response.py         |  5 +-
 tests/template_tests/test_smartif.py          |  1 +
 tests/template_tests/tests.py                 | 31 +++++--
 tests/template_tests/views.py                 |  5 +
 tests/test_client/tests.py                    |  4 +-
 tests/test_client/views.py                    | 22 +++++
 tests/test_client_regress/session.py          |  1 +
 tests/test_client_regress/tests.py            | 28 ++++--
 tests/test_client_regress/views.py            | 18 ++++
 tests/test_runner/models.py                   |  1 +
 tests/test_runner_deprecation_app/tests.py    |  1 +
 tests/test_utils/models.py                    |  1 +
 tests/timezones/admin.py                      |  2 +
 tests/timezones/forms.py                      |  5 +
 tests/timezones/models.py                     |  6 ++
 tests/transactions/tests.py                   | 16 +++-
 tests/transactions_regress/models.py          |  2 +
 tests/transactions_regress/tests.py           |  5 +-
 tests/unmanaged_models/models.py              | 13 ++-
 tests/update/models.py                        |  4 +
 tests/update_only_fields/models.py            |  1 +
 .../erroneous_views_module.py                 |  1 +
 tests/urlpatterns_reverse/middleware.py       |  5 +
 tests/urlpatterns_reverse/tests.py            | 12 ++-
 tests/urlpatterns_reverse/urlconf_inner.py    |  1 +
 tests/urlpatterns_reverse/views.py            | 10 ++
 .../commands/leave_locale_alone_false.py      |  1 +
 .../commands/leave_locale_alone_true.py       |  1 +
 tests/utils_tests/test_baseconv.py            |  1 +
 tests/utils_tests/test_checksums.py           |  1 +
 tests/utils_tests/test_datetime_safe.py       |  1 +
 tests/utils_tests/test_decorators.py          |  1 +
 tests/utils_tests/test_ipv6.py                |  1 +
 tests/utils_tests/test_jslex.py               |  3 +
 tests/utils_tests/test_module_loading.py      |  5 +
 tests/utils_tests/test_simplelazyobject.py    |  1 +
 tests/utils_tests/test_text.py                |  1 +
 tests/utils_tests/test_tzinfo.py              |  9 +-
 tests/validation/models.py                    | 13 +++
 tests/validation/test_unique.py               |  1 +
 tests/validation/tests.py                     |  3 +-
 tests/validators/tests.py                     | 10 +-
 tests/version/tests.py                        |  1 +
 tests/view_tests/__init__.py                  |  1 +
 tests/view_tests/models.py                    |  5 +
 tests/view_tests/templatetags/debugtags.py    |  1 +
 tests/view_tests/tests/test_debug.py          |  9 +-
 tests/view_tests/tests/test_shortcuts.py      |  1 +
 tests/view_tests/views.py                     | 32 +++++++
 tests/wsgi/urls.py                            |  1 +
 98 files changed, 748 insertions(+), 96 deletions(-)

diff --git a/django/forms/widgets.py b/django/forms/widgets.py
index 88dc28d664..e6707f9557 100644
--- a/django/forms/widgets.py
+++ b/django/forms/widgets.py
@@ -104,6 +104,7 @@ class Media(object):
             getattr(combined, 'add_' + name)(getattr(other, '_' + name, None))
         return combined
 
+
 def media_property(cls):
     def _media(self):
         # Get the media property of the superclass, if it exists
@@ -131,6 +132,7 @@ def media_property(cls):
             return base
     return property(_media)
 
+
 class MediaDefiningClass(type):
     """
     Metaclass for classes that can have media definitions.
@@ -162,6 +164,7 @@ class SubWidget(object):
             args.append(self.choices)
         return self.parent_widget.render(*args)
 
+
 class Widget(six.with_metaclass(MediaDefiningClass)):
     is_hidden = False             # Determines whether this corresponds to an <input type="hidden">.
     needs_multipart_form = False  # Determines does this widget need multipart form
@@ -224,6 +227,7 @@ class Widget(six.with_metaclass(MediaDefiningClass)):
         """
         return id_
 
+
 class Input(Widget):
     """
     Base class for all <input> widgets (except type='checkbox' and
@@ -279,10 +283,12 @@ class PasswordInput(TextInput):
             value = None
         return super(PasswordInput, self).render(name, value, attrs)
 
+
 class HiddenInput(Input):
     input_type = 'hidden'
     is_hidden = True
 
+
 class MultipleHiddenInput(HiddenInput):
     """
     A widget that handles <input type="hidden"> for fields that have a list
@@ -313,6 +319,7 @@ class MultipleHiddenInput(HiddenInput):
             return data.getlist(name)
         return data.get(name, None)
 
+
 class FileInput(Input):
     input_type = 'file'
     needs_multipart_form = True
@@ -327,6 +334,7 @@ class FileInput(Input):
 
 FILE_INPUT_CONTRADICTION = object()
 
+
 class ClearableFileInput(FileInput):
     initial_text = ugettext_lazy('Currently')
     input_text = ugettext_lazy('Change')
@@ -379,7 +387,8 @@ class ClearableFileInput(FileInput):
     def value_from_datadict(self, data, files, name):
         upload = super(ClearableFileInput, self).value_from_datadict(data, files, name)
         if not self.is_required and CheckboxInput().value_from_datadict(
-            data, files, self.clear_checkbox_name(name)):
+                data, files, self.clear_checkbox_name(name)):
+
             if upload:
                 # If the user contradicts themselves (uploads a new file AND
                 # checks the "clear" checkbox), we return a unique marker
@@ -389,6 +398,7 @@ class ClearableFileInput(FileInput):
             return False
         return upload
 
+
 class Textarea(Widget):
     def __init__(self, attrs=None):
         # The 'rows' and 'cols' attributes are required for HTML correctness.
@@ -515,6 +525,7 @@ class Select(Widget):
                 output.append(self.render_option(selected_choices, option_value, option_label))
         return '\n'.join(output)
 
+
 class NullBooleanSelect(Select):
     """
     A Select Widget intended to be used with NullBooleanField.
@@ -849,6 +860,7 @@ class SplitDateTimeWidget(MultiWidget):
             return [value.date(), value.time().replace(microsecond=0)]
         return [None, None]
 
+
 class SplitHiddenDateTimeWidget(SplitDateTimeWidget):
     """
     A Widget that splits datetime input into two <input type="hidden"> inputs.
diff --git a/setup.cfg b/setup.cfg
index dd708a5d9a..9a4776a319 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -4,7 +4,7 @@ install-script = scripts/rpm-install.sh
 
 [flake8]
 exclude=./django/utils/dictconfig.py,./django/contrib/comments/*,./django/utils/unittest.py,./tests/comment_tests/*,./django/test/_doctest.py,./django/utils/six.py,./django/conf/app_template/*
-ignore=E124,E125,E127,E128,E226,E251,E302,E501,E261,W601
+ignore=E124,E125,E127,E128,E226,E251,E501,E261,W601
 
 [metadata]
 license-file = LICENSE
diff --git a/tests/multiple_database/tests.py b/tests/multiple_database/tests.py
index f7c5862167..046b8fb14b 100644
--- a/tests/multiple_database/tests.py
+++ b/tests/multiple_database/tests.py
@@ -50,7 +50,8 @@ class QueryTestCase(TestCase):
         except Book.DoesNotExist:
             self.fail('"Pro Django" should exist on default database')
 
-        self.assertRaises(Book.DoesNotExist,
+        self.assertRaises(
+            Book.DoesNotExist,
             Book.objects.using('other').get,
             title="Pro Django"
         )
@@ -61,7 +62,8 @@ class QueryTestCase(TestCase):
         except Book.DoesNotExist:
             self.fail('"Dive into Python" should exist on default database')
 
-        self.assertRaises(Book.DoesNotExist,
+        self.assertRaises(
+            Book.DoesNotExist,
             Book.objects.using('other').get,
             title="Dive into Python"
         )
@@ -84,11 +86,13 @@ class QueryTestCase(TestCase):
         except Book.DoesNotExist:
             self.fail('"Pro Django" should exist on other database')
 
-        self.assertRaises(Book.DoesNotExist,
+        self.assertRaises(
+            Book.DoesNotExist,
             Book.objects.get,
             title="Pro Django"
         )
-        self.assertRaises(Book.DoesNotExist,
+        self.assertRaises(
+            Book.DoesNotExist,
             Book.objects.using('default').get,
             title="Pro Django"
         )
@@ -98,11 +102,13 @@ class QueryTestCase(TestCase):
         except Book.DoesNotExist:
             self.fail('"Dive into Python" should exist on other database')
 
-        self.assertRaises(Book.DoesNotExist,
+        self.assertRaises(
+            Book.DoesNotExist,
             Book.objects.get,
             title="Dive into Python"
         )
-        self.assertRaises(Book.DoesNotExist,
+        self.assertRaises(
+            Book.DoesNotExist,
             Book.objects.using('default').get,
             title="Dive into Python"
         )
@@ -164,14 +170,14 @@ class QueryTestCase(TestCase):
 
         # Check that queries work across m2m joins
         self.assertEqual(list(Book.objects.using('default').filter(authors__name='Marty Alchin').values_list('title', flat=True)),
-                          ['Pro Django'])
+            ['Pro Django'])
         self.assertEqual(list(Book.objects.using('other').filter(authors__name='Marty Alchin').values_list('title', flat=True)),
-                          [])
+            [])
 
         self.assertEqual(list(Book.objects.using('default').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
-                          [])
+            [])
         self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
-                          ['Dive into Python'])
+            ['Dive into Python'])
 
         # Reget the objects to clear caches
         dive = Book.objects.using('other').get(title="Dive into Python")
@@ -179,10 +185,10 @@ class QueryTestCase(TestCase):
 
         # Retrive related object by descriptor. Related objects should be database-baound
         self.assertEqual(list(dive.authors.all().values_list('name', flat=True)),
-                          ['Mark Pilgrim'])
+            ['Mark Pilgrim'])
 
         self.assertEqual(list(mark.book_set.all().values_list('title', flat=True)),
-                          ['Dive into Python'])
+            ['Dive into Python'])
 
     def test_m2m_forward_operations(self):
         "M2M forward manipulations are all constrained to a single DB"
@@ -198,13 +204,13 @@ class QueryTestCase(TestCase):
         # Add a second author
         john = Person.objects.using('other').create(name="John Smith")
         self.assertEqual(list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)),
-                          [])
+            [])
 
         dive.authors.add(john)
         self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
-                          ['Dive into Python'])
+            ['Dive into Python'])
         self.assertEqual(list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)),
-                          ['Dive into Python'])
+            ['Dive into Python'])
 
         # Remove the second author
         dive.authors.remove(john)
diff --git a/tests/mutually_referential/models.py b/tests/mutually_referential/models.py
index 0f1bd65cb1..25bc45731f 100644
--- a/tests/mutually_referential/models.py
+++ b/tests/mutually_referential/models.py
@@ -13,6 +13,7 @@ class Parent(models.Model):
     # Use a simple string for forward declarations.
     bestchild = models.ForeignKey("Child", null=True, related_name="favoured_by")
 
+
 class Child(models.Model):
     name = models.CharField(max_length=100)
 
diff --git a/tests/nested_foreign_keys/models.py b/tests/nested_foreign_keys/models.py
index 50d447951b..3b99cfcb67 100644
--- a/tests/nested_foreign_keys/models.py
+++ b/tests/nested_foreign_keys/models.py
@@ -17,6 +17,7 @@ class Event(models.Model):
 class Screening(Event):
     movie = models.ForeignKey(Movie)
 
+
 class ScreeningNullFK(Event):
     movie = models.ForeignKey(Movie, null=True)
 
@@ -24,5 +25,6 @@ class ScreeningNullFK(Event):
 class Package(models.Model):
     screening = models.ForeignKey(Screening, null=True)
 
+
 class PackageNullFK(models.Model):
     screening = models.ForeignKey(ScreeningNullFK, null=True)
diff --git a/tests/null_fk/models.py b/tests/null_fk/models.py
index c86ee8a5a9..9309ae940f 100644
--- a/tests/null_fk/models.py
+++ b/tests/null_fk/models.py
@@ -9,14 +9,17 @@ from django.utils.encoding import python_2_unicode_compatible
 class SystemDetails(models.Model):
     details = models.TextField()
 
+
 class SystemInfo(models.Model):
     system_details = models.ForeignKey(SystemDetails)
     system_name = models.CharField(max_length=32)
 
+
 class Forum(models.Model):
     system_info = models.ForeignKey(SystemInfo)
     forum_name = models.CharField(max_length=32)
 
+
 @python_2_unicode_compatible
 class Post(models.Model):
     forum = models.ForeignKey(Forum, null=True)
@@ -25,6 +28,7 @@ class Post(models.Model):
     def __str__(self):
         return self.title
 
+
 @python_2_unicode_compatible
 class Comment(models.Model):
     post = models.ForeignKey(Post, null=True)
@@ -38,12 +42,15 @@ class Comment(models.Model):
 
 # Ticket 15823
 
+
 class Item(models.Model):
     title = models.CharField(max_length=100)
 
+
 class PropertyValue(models.Model):
     label = models.CharField(max_length=100)
 
+
 class Property(models.Model):
     item = models.ForeignKey(Item, related_name='props')
     key = models.CharField(max_length=100)
diff --git a/tests/null_fk_ordering/models.py b/tests/null_fk_ordering/models.py
index 3caff0d594..dac1c4f6ae 100644
--- a/tests/null_fk_ordering/models.py
+++ b/tests/null_fk_ordering/models.py
@@ -15,6 +15,7 @@ from django.utils.encoding import python_2_unicode_compatible
 class Author(models.Model):
     name = models.CharField(max_length=150)
 
+
 @python_2_unicode_compatible
 class Article(models.Model):
     title = models.CharField(max_length=150)
@@ -31,10 +32,12 @@ class Article(models.Model):
 class SystemInfo(models.Model):
     system_name = models.CharField(max_length=32)
 
+
 class Forum(models.Model):
     system_info = models.ForeignKey(SystemInfo)
     forum_name = models.CharField(max_length=32)
 
+
 @python_2_unicode_compatible
 class Post(models.Model):
     forum = models.ForeignKey(Forum, null=True)
@@ -43,6 +46,7 @@ class Post(models.Model):
     def __str__(self):
         return self.title
 
+
 @python_2_unicode_compatible
 class Comment(models.Model):
     post = models.ForeignKey(Post, null=True)
diff --git a/tests/null_queries/models.py b/tests/null_queries/models.py
index 9070dd4873..1c3808f407 100644
--- a/tests/null_queries/models.py
+++ b/tests/null_queries/models.py
@@ -11,6 +11,7 @@ class Poll(models.Model):
     def __str__(self):
         return "Q: %s " % self.question
 
+
 @python_2_unicode_compatible
 class Choice(models.Model):
     poll = models.ForeignKey(Poll)
@@ -20,12 +21,16 @@ class Choice(models.Model):
         return "Choice: %s in poll %s" % (self.choice, self.poll)
 
 # A set of models with an inner one pointing to two outer ones.
+
+
 class OuterA(models.Model):
     pass
 
+
 class OuterB(models.Model):
     data = models.CharField(max_length=10)
 
+
 class Inner(models.Model):
     first = models.ForeignKey(OuterA)
     # second would clash with the __second lookup.
diff --git a/tests/one_to_one/models.py b/tests/one_to_one/models.py
index ff809be22d..b54cabbaa3 100644
--- a/tests/one_to_one/models.py
+++ b/tests/one_to_one/models.py
@@ -19,6 +19,7 @@ class Place(models.Model):
     def __str__(self):
         return "%s the place" % self.name
 
+
 @python_2_unicode_compatible
 class Restaurant(models.Model):
     place = models.OneToOneField(Place, primary_key=True)
@@ -28,6 +29,7 @@ class Restaurant(models.Model):
     def __str__(self):
         return "%s the restaurant" % self.place.name
 
+
 @python_2_unicode_compatible
 class Waiter(models.Model):
     restaurant = models.ForeignKey(Restaurant)
@@ -36,13 +38,16 @@ class Waiter(models.Model):
     def __str__(self):
         return "%s the waiter at %s" % (self.name, self.restaurant)
 
+
 class ManualPrimaryKey(models.Model):
     primary_key = models.CharField(max_length=10, primary_key=True)
-    name = models.CharField(max_length = 50)
+    name = models.CharField(max_length=50)
+
 
 class RelatedModel(models.Model):
     link = models.OneToOneField(ManualPrimaryKey)
-    name = models.CharField(max_length = 50)
+    name = models.CharField(max_length=50)
+
 
 @python_2_unicode_compatible
 class MultiModel(models.Model):
diff --git a/tests/one_to_one/tests.py b/tests/one_to_one/tests.py
index da36908d28..84ada2cc51 100644
--- a/tests/one_to_one/tests.py
+++ b/tests/one_to_one/tests.py
@@ -6,6 +6,7 @@ from django.test import TestCase
 from .models import (Place, Restaurant, Waiter, ManualPrimaryKey, RelatedModel,
     MultiModel)
 
+
 class OneToOneTests(TestCase):
 
     def setUp(self):
diff --git a/tests/order_with_respect_to/models.py b/tests/order_with_respect_to/models.py
index 06bb56b141..18dbd08dbc 100644
--- a/tests/order_with_respect_to/models.py
+++ b/tests/order_with_respect_to/models.py
@@ -10,6 +10,7 @@ from django.utils.encoding import python_2_unicode_compatible
 class Question(models.Model):
     text = models.CharField(max_length=200)
 
+
 @python_2_unicode_compatible
 class Answer(models.Model):
     text = models.CharField(max_length=200)
@@ -21,6 +22,7 @@ class Answer(models.Model):
     def __str__(self):
         return six.text_type(self.text)
 
+
 @python_2_unicode_compatible
 class Post(models.Model):
     title = models.CharField(max_length=200)
diff --git a/tests/ordering/models.py b/tests/ordering/models.py
index e516c2f5a8..415b28bb41 100644
--- a/tests/ordering/models.py
+++ b/tests/ordering/models.py
@@ -28,6 +28,7 @@ class Article(models.Model):
     def __str__(self):
         return self.headline
 
+
 @python_2_unicode_compatible
 class ArticlePKOrdering(models.Model):
     headline = models.CharField(max_length=100)
diff --git a/tests/prefetch_related/models.py b/tests/prefetch_related/models.py
index 307cee1900..5e4bf4a3e4 100644
--- a/tests/prefetch_related/models.py
+++ b/tests/prefetch_related/models.py
@@ -5,6 +5,7 @@ from django.utils.encoding import python_2_unicode_compatible
 
 ## Basic tests
 
+
 @python_2_unicode_compatible
 class Author(models.Model):
     name = models.CharField(max_length=50, unique=True)
@@ -55,6 +56,7 @@ class Book(models.Model):
     class Meta:
         ordering = ['id']
 
+
 class BookWithYear(Book):
     book = models.OneToOneField(Book, parent_link=True)
     published_year = models.IntegerField()
@@ -73,12 +75,14 @@ class Reader(models.Model):
     class Meta:
         ordering = ['id']
 
+
 class BookReview(models.Model):
     book = models.ForeignKey(BookWithYear)
     notes = models.TextField(null=True, blank=True)
 
 ## Models for default manager tests
 
+
 class Qualification(models.Model):
     name = models.CharField(max_length=10)
 
@@ -161,6 +165,7 @@ class House(models.Model):
     class Meta:
         ordering = ['id']
 
+
 class Room(models.Model):
     name = models.CharField(max_length=50)
     house = models.ForeignKey(House, related_name='rooms')
diff --git a/tests/proxy_model_inheritance/models.py b/tests/proxy_model_inheritance/models.py
index ef9ac6b0d3..7a10b77c90 100644
--- a/tests/proxy_model_inheritance/models.py
+++ b/tests/proxy_model_inheritance/models.py
@@ -5,9 +5,11 @@ from django.db import models
 class ConcreteModel(models.Model):
     pass
 
+
 class ConcreteModelSubclass(ConcreteModel):
     pass
 
+
 class ConcreteModelSubclassProxy(ConcreteModelSubclass):
     class Meta:
         proxy = True
diff --git a/tests/proxy_models/models.py b/tests/proxy_models/models.py
index 2e5741ab6b..2e28c3b996 100644
--- a/tests/proxy_models/models.py
+++ b/tests/proxy_models/models.py
@@ -9,14 +9,17 @@ from django.utils.encoding import python_2_unicode_compatible
 
 # A couple of managers for testing managing overriding in proxy model cases.
 
+
 class PersonManager(models.Manager):
     def get_queryset(self):
         return super(PersonManager, self).get_queryset().exclude(name="fred")
 
+
 class SubManager(models.Manager):
     def get_queryset(self):
         return super(SubManager, self).get_queryset().exclude(name="wilma")
 
+
 @python_2_unicode_compatible
 class Person(models.Model):
     """
@@ -29,6 +32,7 @@ class Person(models.Model):
     def __str__(self):
         return self.name
 
+
 class Abstract(models.Model):
     """
     A simple abstract base class, to be used for error checking.
@@ -38,6 +42,7 @@ class Abstract(models.Model):
     class Meta:
         abstract = True
 
+
 class MyPerson(Person):
     """
     A proxy subclass, this should not get a new table. Overrides the default
@@ -56,12 +61,14 @@ class MyPerson(Person):
     def has_special_name(self):
         return self.name.lower() == "special"
 
+
 class ManagerMixin(models.Model):
     excluder = SubManager()
 
     class Meta:
         abstract = True
 
+
 class OtherPerson(Person, ManagerMixin):
     """
     A class with the default manager from Person, plus an secondary manager.
@@ -70,6 +77,7 @@ class OtherPerson(Person, ManagerMixin):
         proxy = True
         ordering = ["name"]
 
+
 class StatusPerson(MyPerson):
     """
     A non-proxy subclass of a proxy, it should get a new table.
@@ -77,13 +85,17 @@ class StatusPerson(MyPerson):
     status = models.CharField(max_length=80)
 
 # We can even have proxies of proxies (and subclass of those).
+
+
 class MyPersonProxy(MyPerson):
     class Meta:
         proxy = True
 
+
 class LowerStatusPerson(MyPersonProxy):
     status = models.CharField(max_length=80)
 
+
 @python_2_unicode_compatible
 class User(models.Model):
     name = models.CharField(max_length=100)
@@ -91,18 +103,23 @@ class User(models.Model):
     def __str__(self):
         return self.name
 
+
 class UserProxy(User):
     class Meta:
         proxy = True
 
+
 class UserProxyProxy(UserProxy):
     class Meta:
         proxy = True
 
 # We can still use `select_related()` to include related models in our querysets.
+
+
 class Country(models.Model):
     name = models.CharField(max_length=50)
 
+
 @python_2_unicode_compatible
 class State(models.Model):
     name = models.CharField(max_length=50)
@@ -111,12 +128,15 @@ class State(models.Model):
     def __str__(self):
         return self.name
 
+
 class StateProxy(State):
     class Meta:
         proxy = True
 
 # Proxy models still works with filters (on related fields)
 # and select_related, even when mixed with model inheritance
+
+
 @python_2_unicode_compatible
 class BaseUser(models.Model):
     name = models.CharField(max_length=255)
@@ -124,9 +144,11 @@ class BaseUser(models.Model):
     def __str__(self):
         return ':'.join((self.__class__.__name__, self.name,))
 
+
 class TrackerUser(BaseUser):
     status = models.CharField(max_length=50)
 
+
 class ProxyTrackerUser(TrackerUser):
     class Meta:
         proxy = True
@@ -140,10 +162,12 @@ class Issue(models.Model):
     def __str__(self):
         return ':'.join((self.__class__.__name__, self.summary,))
 
+
 class Bug(Issue):
     version = models.CharField(max_length=50)
     reporter = models.ForeignKey(BaseUser)
 
+
 class ProxyBug(Bug):
     """
     Proxy of an inherited class
@@ -159,6 +183,7 @@ class ProxyProxyBug(ProxyBug):
     class Meta:
         proxy = True
 
+
 class Improvement(Issue):
     """
     A model that has relation to a proxy model
@@ -168,6 +193,7 @@ class Improvement(Issue):
     reporter = models.ForeignKey(ProxyTrackerUser)
     associated_bug = models.ForeignKey(ProxyProxyBug)
 
+
 class ProxyImprovement(Improvement):
     class Meta:
         proxy = True
diff --git a/tests/queries/models.py b/tests/queries/models.py
index 53b716abd1..ec924c03c2 100644
--- a/tests/queries/models.py
+++ b/tests/queries/models.py
@@ -13,10 +13,12 @@ from django.utils.encoding import python_2_unicode_compatible
 class DumbCategory(models.Model):
     pass
 
+
 class ProxyCategory(DumbCategory):
     class Meta:
         proxy = True
 
+
 @python_2_unicode_compatible
 class NamedCategory(DumbCategory):
     name = models.CharField(max_length=10)
@@ -24,6 +26,7 @@ class NamedCategory(DumbCategory):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Tag(models.Model):
     name = models.CharField(max_length=10)
@@ -37,6 +40,7 @@ class Tag(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Note(models.Model):
     note = models.CharField(max_length=100)
@@ -55,6 +59,7 @@ class Note(models.Model):
         # that use objects of that type as an argument.
         self.lock = threading.Lock()
 
+
 @python_2_unicode_compatible
 class Annotation(models.Model):
     name = models.CharField(max_length=10)
@@ -64,6 +69,7 @@ class Annotation(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class ExtraInfo(models.Model):
     info = models.CharField(max_length=100)
@@ -76,6 +82,7 @@ class ExtraInfo(models.Model):
     def __str__(self):
         return self.info
 
+
 @python_2_unicode_compatible
 class Author(models.Model):
     name = models.CharField(max_length=10)
@@ -88,6 +95,7 @@ class Author(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Item(models.Model):
     name = models.CharField(max_length=10)
@@ -103,6 +111,7 @@ class Item(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Report(models.Model):
     name = models.CharField(max_length=10)
@@ -111,6 +120,7 @@ class Report(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Ranking(models.Model):
     rank = models.IntegerField()
@@ -123,6 +133,7 @@ class Ranking(models.Model):
     def __str__(self):
         return '%d: %s' % (self.rank, self.author.name)
 
+
 @python_2_unicode_compatible
 class Cover(models.Model):
     title = models.CharField(max_length=50)
@@ -134,6 +145,7 @@ class Cover(models.Model):
     def __str__(self):
         return self.title
 
+
 @python_2_unicode_compatible
 class Number(models.Model):
     num = models.IntegerField()
@@ -143,6 +155,8 @@ class Number(models.Model):
 
 # Symmetrical m2m field with a normal field using the reverse accesor name
 # ("valid").
+
+
 class Valid(models.Model):
     valid = models.CharField(max_length=10)
     parent = models.ManyToManyField('self')
@@ -152,38 +166,49 @@ class Valid(models.Model):
 
 # Some funky cross-linked models for testing a couple of infinite recursion
 # cases.
+
+
 class X(models.Model):
     y = models.ForeignKey('Y')
 
+
 class Y(models.Model):
     x1 = models.ForeignKey(X, related_name='y1')
 
 # Some models with a cycle in the default ordering. This would be bad if we
 # didn't catch the infinite loop.
+
+
 class LoopX(models.Model):
     y = models.ForeignKey('LoopY')
 
     class Meta:
         ordering = ['y']
 
+
 class LoopY(models.Model):
     x = models.ForeignKey(LoopX)
 
     class Meta:
         ordering = ['x']
 
+
 class LoopZ(models.Model):
     z = models.ForeignKey('self')
 
     class Meta:
         ordering = ['z']
 
+
 # A model and custom default manager combination.
+
+
 class CustomManager(models.Manager):
     def get_queryset(self):
         qs = super(CustomManager, self).get_queryset()
         return qs.filter(public=True, tag__name='t1')
 
+
 @python_2_unicode_compatible
 class ManagedModel(models.Model):
     data = models.CharField(max_length=10)
@@ -197,24 +222,31 @@ class ManagedModel(models.Model):
         return self.data
 
 # An inter-related setup with multiple paths from Child to Detail.
+
+
 class Detail(models.Model):
     data = models.CharField(max_length=10)
 
+
 class MemberManager(models.Manager):
     def get_queryset(self):
         return super(MemberManager, self).get_queryset().select_related("details")
 
+
 class Member(models.Model):
     name = models.CharField(max_length=10)
     details = models.OneToOneField(Detail, primary_key=True)
 
     objects = MemberManager()
 
+
 class Child(models.Model):
     person = models.OneToOneField(Member, primary_key=True)
     parent = models.ForeignKey(Member, related_name="children")
 
 # Custom primary keys interfered with ordering in the past.
+
+
 class CustomPk(models.Model):
     name = models.CharField(max_length=10, primary_key=True)
     extra = models.CharField(max_length=10)
@@ -222,12 +254,14 @@ class CustomPk(models.Model):
     class Meta:
         ordering = ['name', 'extra']
 
+
 class Related(models.Model):
     custom = models.ForeignKey(CustomPk)
 
 # An inter-related setup with a model subclass that has a nullable
 # path to another model, and a return path from that model.
 
+
 @python_2_unicode_compatible
 class Celebrity(models.Model):
     name = models.CharField("Name", max_length=20)
@@ -236,13 +270,17 @@ class Celebrity(models.Model):
     def __str__(self):
         return self.name
 
+
 class TvChef(Celebrity):
     pass
 
+
 class Fan(models.Model):
     fan_of = models.ForeignKey(Celebrity)
 
 # Multiple foreign keys
+
+
 @python_2_unicode_compatible
 class LeafA(models.Model):
     data = models.CharField(max_length=10)
@@ -250,13 +288,16 @@ class LeafA(models.Model):
     def __str__(self):
         return self.data
 
+
 class LeafB(models.Model):
     data = models.CharField(max_length=10)
 
+
 class Join(models.Model):
     a = models.ForeignKey(LeafA)
     b = models.ForeignKey(LeafB)
 
+
 @python_2_unicode_compatible
 class ReservedName(models.Model):
     name = models.CharField(max_length=20)
@@ -266,6 +307,8 @@ class ReservedName(models.Model):
         return self.name
 
 # A simpler shared-foreign-key setup that can expose some problems.
+
+
 @python_2_unicode_compatible
 class SharedConnection(models.Model):
     data = models.CharField(max_length=10)
@@ -273,13 +316,17 @@ class SharedConnection(models.Model):
     def __str__(self):
         return self.data
 
+
 class PointerA(models.Model):
     connection = models.ForeignKey(SharedConnection)
 
+
 class PointerB(models.Model):
     connection = models.ForeignKey(SharedConnection)
 
 # Multi-layer ordering
+
+
 @python_2_unicode_compatible
 class SingleObject(models.Model):
     name = models.CharField(max_length=10)
@@ -290,6 +337,7 @@ class SingleObject(models.Model):
     def __str__(self):
         return self.name
 
+
 class RelatedObject(models.Model):
     single = models.ForeignKey(SingleObject, null=True)
     f = models.IntegerField(null=True)
@@ -297,6 +345,7 @@ class RelatedObject(models.Model):
     class Meta:
         ordering = ['single']
 
+
 @python_2_unicode_compatible
 class Plaything(models.Model):
     name = models.CharField(max_length=10)
@@ -308,10 +357,12 @@ class Plaything(models.Model):
     def __str__(self):
         return self.name
 
+
 class Article(models.Model):
     name = models.CharField(max_length=20)
     created = models.DateTimeField()
 
+
 @python_2_unicode_compatible
 class Food(models.Model):
     name = models.CharField(max_length=20, unique=True)
@@ -319,6 +370,7 @@ class Food(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Eaten(models.Model):
     food = models.ForeignKey(Food, to_field="name", null=True)
@@ -327,6 +379,7 @@ class Eaten(models.Model):
     def __str__(self):
         return "%s at %s" % (self.food, self.meal)
 
+
 @python_2_unicode_compatible
 class Node(models.Model):
     num = models.IntegerField(unique=True)
@@ -336,6 +389,8 @@ class Node(models.Model):
         return "%s" % self.num
 
 # Bug #12252
+
+
 @python_2_unicode_compatible
 class ObjectA(models.Model):
     name = models.CharField(max_length=50)
@@ -343,6 +398,7 @@ class ObjectA(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class ObjectB(models.Model):
     name = models.CharField(max_length=50)
@@ -352,6 +408,7 @@ class ObjectB(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class ObjectC(models.Model):
     name = models.CharField(max_length=50)
@@ -361,6 +418,7 @@ class ObjectC(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class SimpleCategory(models.Model):
     name = models.CharField(max_length=15)
@@ -368,6 +426,7 @@ class SimpleCategory(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class SpecialCategory(SimpleCategory):
     special_name = models.CharField(max_length=15)
@@ -375,6 +434,7 @@ class SpecialCategory(SimpleCategory):
     def __str__(self):
         return self.name + " " + self.special_name
 
+
 @python_2_unicode_compatible
 class CategoryItem(models.Model):
     category = models.ForeignKey(SimpleCategory)
@@ -382,6 +442,7 @@ class CategoryItem(models.Model):
     def __str__(self):
         return "category item: " + str(self.category)
 
+
 @python_2_unicode_compatible
 class OneToOneCategory(models.Model):
     new_name = models.CharField(max_length=15)
@@ -390,31 +451,38 @@ class OneToOneCategory(models.Model):
     def __str__(self):
         return "one2one " + self.new_name
 
+
 class CategoryRelationship(models.Model):
     first = models.ForeignKey(SimpleCategory, related_name='first_rel')
     second = models.ForeignKey(SimpleCategory, related_name='second_rel')
 
+
 class NullableName(models.Model):
     name = models.CharField(max_length=20, null=True)
 
     class Meta:
         ordering = ['id']
 
+
 class ModelD(models.Model):
     name = models.TextField()
 
+
 class ModelC(models.Model):
     name = models.TextField()
 
+
 class ModelB(models.Model):
     name = models.TextField()
     c = models.ForeignKey(ModelC)
 
+
 class ModelA(models.Model):
     name = models.TextField()
     b = models.ForeignKey(ModelB, null=True)
     d = models.ForeignKey(ModelD)
 
+
 @python_2_unicode_compatible
 class Job(models.Model):
     name = models.CharField(max_length=20, unique=True)
@@ -422,10 +490,12 @@ class Job(models.Model):
     def __str__(self):
         return self.name
 
+
 class JobResponsibilities(models.Model):
     job = models.ForeignKey(Job, to_field='name')
     responsibility = models.ForeignKey('Responsibility', to_field='description')
 
+
 @python_2_unicode_compatible
 class Responsibility(models.Model):
     description = models.CharField(max_length=20, unique=True)
@@ -436,23 +506,29 @@ class Responsibility(models.Model):
         return self.description
 
 # Models for disjunction join promotion low level testing.
+
+
 class FK1(models.Model):
     f1 = models.TextField()
     f2 = models.TextField()
 
+
 class FK2(models.Model):
     f1 = models.TextField()
     f2 = models.TextField()
 
+
 class FK3(models.Model):
     f1 = models.TextField()
     f2 = models.TextField()
 
+
 class BaseA(models.Model):
     a = models.ForeignKey(FK1, null=True)
     b = models.ForeignKey(FK2, null=True)
     c = models.ForeignKey(FK3, null=True)
 
+
 @python_2_unicode_compatible
 class Identifier(models.Model):
     name = models.CharField(max_length=100)
@@ -460,17 +536,21 @@ class Identifier(models.Model):
     def __str__(self):
         return self.name
 
+
 class Program(models.Model):
     identifier = models.OneToOneField(Identifier)
 
+
 class Channel(models.Model):
     programs = models.ManyToManyField(Program)
     identifier = models.OneToOneField(Identifier)
 
+
 class Book(models.Model):
     title = models.TextField()
     chapter = models.ForeignKey('Chapter')
 
+
 class Chapter(models.Model):
     title = models.TextField()
     paragraph = models.ForeignKey('Paragraph')
@@ -480,15 +560,19 @@ class Paragraph(models.Model):
     text = models.TextField()
     page = models.ManyToManyField('Page')
 
+
 class Page(models.Model):
     text = models.TextField()
 
+
 class MyObject(models.Model):
     parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
     data = models.CharField(max_length=100)
     created_at = models.DateTimeField(auto_now_add=True)
 
 # Models for #17600 regressions
+
+
 @python_2_unicode_compatible
 class Order(models.Model):
     id = models.IntegerField(primary_key=True)
@@ -499,6 +583,7 @@ class Order(models.Model):
     def __str__(self):
         return '%s' % self.pk
 
+
 @python_2_unicode_compatible
 class OrderItem(models.Model):
     order = models.ForeignKey(Order, related_name='items')
@@ -510,9 +595,11 @@ class OrderItem(models.Model):
     def __str__(self):
         return '%s' % self.pk
 
+
 class BaseUser(models.Model):
     pass
 
+
 @python_2_unicode_compatible
 class Task(models.Model):
     title = models.CharField(max_length=10)
@@ -522,6 +609,7 @@ class Task(models.Model):
     def __str__(self):
         return self.title
 
+
 @python_2_unicode_compatible
 class Staff(models.Model):
     name = models.CharField(max_length=10)
@@ -529,6 +617,7 @@ class Staff(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class StaffUser(BaseUser):
     staff = models.OneToOneField(Staff, related_name='user')
@@ -536,11 +625,13 @@ class StaffUser(BaseUser):
     def __str__(self):
         return self.staff
 
+
 class Ticket21203Parent(models.Model):
     parentid = models.AutoField(primary_key=True)
     parent_bool = models.BooleanField(default=True)
     created = models.DateTimeField(auto_now=True)
 
+
 class Ticket21203Child(models.Model):
     childid = models.AutoField(primary_key=True)
     parent = models.ForeignKey(Ticket21203Parent)
diff --git a/tests/queries/tests.py b/tests/queries/tests.py
index c1d461f485..d1e9bd7363 100644
--- a/tests/queries/tests.py
+++ b/tests/queries/tests.py
@@ -28,6 +28,7 @@ from .models import (
     CategoryRelationship, Ticket21203Parent, Ticket21203Child, Person,
     Company, Employment)
 
+
 class BaseQuerysetTest(TestCase):
     def assertValueQuerysetEqual(self, qs, values):
         return self.assertQuerysetEqual(qs, values, transform=lambda x: x)
@@ -827,7 +828,7 @@ class Queries1Tests(BaseQuerysetTest):
         qs = Tag.objects.values_list('id', flat=True).order_by('id')
         qs.query.bump_prefix(qs.query)
         first = qs[0]
-        self.assertEqual(list(qs), list(range(first, first+5)))
+        self.assertEqual(list(qs), list(range(first, first + 5)))
 
     def test_ticket8439(self):
         # Complex combinations of conjunctions, disjunctions and nullable
@@ -1262,6 +1263,7 @@ class Queries3Tests(BaseQuerysetTest):
             Item.objects.datetimes, 'name', 'month'
         )
 
+
 class Queries4Tests(BaseQuerysetTest):
     def setUp(self):
         generic = NamedCategory.objects.create(name="Generic")
@@ -1445,8 +1447,8 @@ class Queries4Tests(BaseQuerysetTest):
         c0 = SimpleCategory.objects.create(name="cat0")
         c1 = SimpleCategory.objects.create(name="category1")
 
-        OneToOneCategory.objects.create(category = c1, new_name="new1")
-        OneToOneCategory.objects.create(category = c0, new_name="new2")
+        OneToOneCategory.objects.create(category=c1, new_name="new1")
+        OneToOneCategory.objects.create(category=c0, new_name="new2")
 
         CategoryItem.objects.create(category=c)
         ci2 = CategoryItem.objects.create(category=c0)
@@ -1461,8 +1463,8 @@ class Queries4Tests(BaseQuerysetTest):
         c0 = SimpleCategory.objects.create(name="cat0")
         c1 = SimpleCategory.objects.create(name="category1")
 
-        OneToOneCategory.objects.create(category = c1, new_name="new1")
-        OneToOneCategory.objects.create(category = c0, new_name="new2")
+        OneToOneCategory.objects.create(category=c1, new_name="new1")
+        OneToOneCategory.objects.create(category=c0, new_name="new2")
 
         ci1 = CategoryItem.objects.create(category=c)
         CategoryItem.objects.create(category=c0)
@@ -1477,8 +1479,8 @@ class Queries4Tests(BaseQuerysetTest):
         c0 = SimpleCategory.objects.create(name="cat0")
         c1 = SimpleCategory.objects.create(name="category1")
 
-        OneToOneCategory.objects.create(category = c1, new_name="new1")
-        OneToOneCategory.objects.create(category = c0, new_name="new2")
+        OneToOneCategory.objects.create(category=c1, new_name="new1")
+        OneToOneCategory.objects.create(category=c0, new_name="new2")
 
         ci1 = CategoryItem.objects.create(category=c)
         CategoryItem.objects.create(category=c0)
@@ -1493,8 +1495,8 @@ class Queries4Tests(BaseQuerysetTest):
         c0 = SimpleCategory.objects.create(name="cat0")
         c1 = SimpleCategory.objects.create(name="category1")
 
-        OneToOneCategory.objects.create(category = c1, new_name="new1")
-        OneToOneCategory.objects.create(category = c0, new_name="new2")
+        OneToOneCategory.objects.create(category=c1, new_name="new1")
+        OneToOneCategory.objects.create(category=c0, new_name="new2")
 
         CategoryItem.objects.create(category=c)
         ci2 = CategoryItem.objects.create(category=c0)
@@ -2019,6 +2021,7 @@ class CloneTests(TestCase):
             else:
                 opts_class.__deepcopy__ = note_deepcopy
 
+
 class EmptyQuerySetTests(TestCase):
     def test_emptyqueryset_values(self):
         # #14366 -- Calling .values() on an empty QuerySet and then cloning
@@ -2224,12 +2227,12 @@ class ConditionalTests(BaseQuerysetTest):
         self.assertRaisesMessage(
             FieldError,
             'Infinite loop caused by ordering.',
-            lambda: list(LoopX.objects.all()) # Force queryset evaluation with list()
+            lambda: list(LoopX.objects.all())  # Force queryset evaluation with list()
         )
         self.assertRaisesMessage(
             FieldError,
             'Infinite loop caused by ordering.',
-            lambda: list(LoopZ.objects.all()) # Force queryset evaluation with list()
+            lambda: list(LoopZ.objects.all())  # Force queryset evaluation with list()
         )
 
         # Note that this doesn't cause an infinite loop, since the default
@@ -2353,6 +2356,7 @@ class DefaultValuesInsertTest(TestCase):
         except TypeError:
             self.fail("Creation of an instance of a model with only the PK field shouldn't error out after bulk insert refactoring (#17056)")
 
+
 class ExcludeTests(TestCase):
     def setUp(self):
         f1 = Food.objects.create(name='apples')
@@ -2504,6 +2508,7 @@ class ExcludeTest17600(TestCase):
             Order.objects.exclude(~Q(items__status=1)).distinct(),
             ['<Order: 1>'])
 
+
 class Exclude15786(TestCase):
     """Regression test for #15786"""
     def test_ticket15786(self):
@@ -2562,6 +2567,7 @@ class NullInExcludeTest(TestCase):
             'IS NOT NULL',
             str(NullableName.objects.filter(~~Q(name='i1')).query))
 
+
 class EmptyStringsAsNullTest(TestCase):
     """
     Test that filtering on non-null character fields works as expected.
@@ -2591,6 +2597,7 @@ class EmptyStringsAsNullTest(TestCase):
             [foo.pk], attrgetter('pk')
         )
 
+
 class ProxyQueryCleanupTest(TestCase):
     def test_evaluated_proxy_count(self):
         """
@@ -2603,6 +2610,7 @@ class ProxyQueryCleanupTest(TestCase):
         str(qs.query)
         self.assertEqual(qs.count(), 1)
 
+
 class WhereNodeTest(TestCase):
     class DummyNode(object):
         def as_sql(self, qn, connection):
@@ -2768,6 +2776,7 @@ class NullJoinPromotionOrTest(TestCase):
         self.assertQuerysetEqual(
             qs.order_by('name'), [r2, r1], lambda x: x)
 
+
 class ReverseJoinTrimmingTest(TestCase):
     def test_reverse_trimming(self):
         # Check that we don't accidentally trim reverse joins - we can't know
@@ -2778,6 +2787,7 @@ class ReverseJoinTrimmingTest(TestCase):
         self.assertIn('INNER JOIN', str(qs.query))
         self.assertEqual(list(qs), [])
 
+
 class JoinReuseTest(TestCase):
     """
     Test that the queries reuse joins sensibly (for example, direct joins
@@ -2811,6 +2821,7 @@ class JoinReuseTest(TestCase):
         qs = Author.objects.filter(report__name='r4').filter(report__name='r1')
         self.assertEqual(str(qs.query).count('JOIN'), 2)
 
+
 class DisjunctionPromotionTests(TestCase):
     def test_disjuction_promotion_select_related(self):
         fk1 = FK1.objects.create(f1='f1', f2='f2')
@@ -2986,6 +2997,7 @@ class ManyToManyExcludeTest(TestCase):
         self.assertIn(b2, q)
         self.assertIn(b3, q)
 
+
 class RelabelCloneTest(TestCase):
     def test_ticket_19964(self):
         my1 = MyObject.objects.create(data='foo')
@@ -3000,6 +3012,7 @@ class RelabelCloneTest(TestCase):
         self.assertEqual(list(children), [my2])
         self.assertEqual(list(parents), [my1])
 
+
 class Ticket20101Tests(TestCase):
     def test_ticket_20101(self):
         """
@@ -3016,6 +3029,7 @@ class Ticket20101Tests(TestCase):
         self.assertFalse(n in qs2)
         self.assertTrue(n in (qs1 | qs2))
 
+
 class EmptyStringPromotionTests(TestCase):
     def test_empty_string_promotion(self):
         qs = RelatedObject.objects.filter(single__name='')
@@ -3024,6 +3038,7 @@ class EmptyStringPromotionTests(TestCase):
         else:
             self.assertNotIn('LEFT OUTER JOIN', str(qs.query))
 
+
 class ValuesSubqueryTests(TestCase):
     def test_values_in_subquery(self):
         # Check that if a values() queryset is used, then the given values
@@ -3041,6 +3056,7 @@ class ValuesSubqueryTests(TestCase):
             Order.objects.filter(items__in=OrderItem.objects.values_list('status')),
             [o1.pk], lambda x: x.pk)
 
+
 class DoubleInSubqueryTests(TestCase):
     def test_double_subquery_in(self):
         lfa1 = LeafA.objects.create(data='foo')
@@ -3055,6 +3071,7 @@ class DoubleInSubqueryTests(TestCase):
         self.assertQuerysetEqual(
             qs, [lfb1], lambda x: x)
 
+
 class Ticket18785Tests(TestCase):
     def test_ticket_18785(self):
         # Test join trimming from ticket18785
@@ -3085,6 +3102,7 @@ class Ticket20788Tests(TestCase):
         self.assertQuerysetEqual(
             sentences_not_in_pub, [book2], lambda x: x)
 
+
 class Ticket12807Tests(TestCase):
     def test_ticket_12807(self):
         p1 = Paragraph.objects.create()
@@ -3111,6 +3129,7 @@ class RelatedLookupTypeTests(TestCase):
             ObjectB.objects.filter(objecta__in=[wrong_type]),
             [ob], lambda x: x)
 
+
 class Ticket14056Tests(TestCase):
     def test_ticket_14056(self):
         s1 = SharedConnection.objects.create(data='s1')
@@ -3126,6 +3145,7 @@ class Ticket14056Tests(TestCase):
             expected_ordering, lambda x: x
         )
 
+
 class Ticket20955Tests(TestCase):
     def test_ticket_20955(self):
         jack = Staff.objects.create(name='jackstaff')
@@ -3146,6 +3166,7 @@ class Ticket20955Tests(TestCase):
             self.assertEqual(task_select_related.owner.staffuser.staff,
                              task_get.owner.staffuser.staff)
 
+
 class Ticket21203Tests(TestCase):
     def test_ticket_21203(self):
         p = Ticket21203Parent.objects.create(parent_bool=True)
@@ -3154,6 +3175,7 @@ class Ticket21203Tests(TestCase):
         self.assertQuerysetEqual(qs, [c], lambda x: x)
         self.assertIs(qs[0].parent.parent_bool, True)
 
+
 class ValuesJoinPromotionTests(TestCase):
     def test_values_no_promotion_for_existing(self):
         qs = Node.objects.filter(parent__parent__isnull=False)
diff --git a/tests/queryset_pickle/models.py b/tests/queryset_pickle/models.py
index 10d34180e4..1e73774cd2 100644
--- a/tests/queryset_pickle/models.py
+++ b/tests/queryset_pickle/models.py
@@ -7,6 +7,7 @@ from django.utils.translation import ugettext_lazy as _
 def standalone_number():
     return 1
 
+
 class Numbers(object):
     @staticmethod
     def get_static_number():
@@ -21,12 +22,15 @@ class Numbers(object):
 
 nn = Numbers()
 
+
 class Group(models.Model):
     name = models.CharField(_('name'), max_length=100)
 
+
 class Event(models.Model):
     group = models.ForeignKey(Group)
 
+
 class Happening(models.Model):
     when = models.DateTimeField(blank=True, default=datetime.datetime.now)
     name = models.CharField(blank=True, max_length=100, default=lambda: "test")
@@ -35,6 +39,7 @@ class Happening(models.Model):
     number3 = models.IntegerField(blank=True, default=Numbers.get_class_number)
     number4 = models.IntegerField(blank=True, default=nn.get_member_number)
 
+
 class Container(object):
     # To test pickling we need a class that isn't defined on module, but
     # is still available from app-cache. So, the Container class moves
@@ -42,5 +47,6 @@ class Container(object):
     class SomeModel(models.Model):
         somefield = models.IntegerField()
 
+
 class M2MModel(models.Model):
     groups = models.ManyToManyField(Group)
diff --git a/tests/raw_query/models.py b/tests/raw_query/models.py
index 33f754958e..1e5e176bcf 100644
--- a/tests/raw_query/models.py
+++ b/tests/raw_query/models.py
@@ -15,17 +15,21 @@ class Author(models.Model):
             assert k in [f.attname for f in self._meta.fields], \
                 "Author.__init__ got an unexpected parameter: %s" % k
 
+
 class Book(models.Model):
     title = models.CharField(max_length=255)
     author = models.ForeignKey(Author)
     paperback = models.BooleanField(default=False)
     opening_line = models.TextField()
 
+
 class Coffee(models.Model):
     brand = models.CharField(max_length=255, db_column="name")
 
+
 class Reviewer(models.Model):
     reviewed = models.ManyToManyField(Book)
 
+
 class FriendlyAuthor(Author):
     pass
diff --git a/tests/responses/tests.py b/tests/responses/tests.py
index e5320f5af9..afdd4220fb 100644
--- a/tests/responses/tests.py
+++ b/tests/responses/tests.py
@@ -1,6 +1,7 @@
 from django.http import HttpResponse
 import unittest
 
+
 class HttpResponseTests(unittest.TestCase):
 
     def test_status_code(self):
diff --git a/tests/reverse_lookup/models.py b/tests/reverse_lookup/models.py
index ed58177770..b216c03120 100644
--- a/tests/reverse_lookup/models.py
+++ b/tests/reverse_lookup/models.py
@@ -15,6 +15,7 @@ class User(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Poll(models.Model):
     question = models.CharField(max_length=200)
@@ -23,6 +24,7 @@ class Poll(models.Model):
     def __str__(self):
         return self.question
 
+
 @python_2_unicode_compatible
 class Choice(models.Model):
     name = models.CharField(max_length=100)
diff --git a/tests/reverse_single_related/models.py b/tests/reverse_single_related/models.py
index 5d53e04772..c7ec2edc6b 100644
--- a/tests/reverse_single_related/models.py
+++ b/tests/reverse_single_related/models.py
@@ -5,9 +5,11 @@ class SourceManager(models.Manager):
     def get_queryset(self):
         return super(SourceManager, self).get_queryset().filter(is_public=True)
 
+
 class Source(models.Model):
     is_public = models.BooleanField(default=False)
     objects = SourceManager()
 
+
 class Item(models.Model):
     source = models.ForeignKey(Source)
diff --git a/tests/select_related/models.py b/tests/select_related/models.py
index 3b796acdaf..93d699f73e 100644
--- a/tests/select_related/models.py
+++ b/tests/select_related/models.py
@@ -12,6 +12,7 @@ from django.utils.encoding import python_2_unicode_compatible
 
 # Who remembers high school biology?
 
+
 @python_2_unicode_compatible
 class Domain(models.Model):
     name = models.CharField(max_length=50)
@@ -19,6 +20,7 @@ class Domain(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Kingdom(models.Model):
     name = models.CharField(max_length=50)
@@ -27,6 +29,7 @@ class Kingdom(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Phylum(models.Model):
     name = models.CharField(max_length=50)
@@ -35,6 +38,7 @@ class Phylum(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Klass(models.Model):
     name = models.CharField(max_length=50)
@@ -43,6 +47,7 @@ class Klass(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Order(models.Model):
     name = models.CharField(max_length=50)
@@ -51,6 +56,7 @@ class Order(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Family(models.Model):
     name = models.CharField(max_length=50)
@@ -59,6 +65,7 @@ class Family(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Genus(models.Model):
     name = models.CharField(max_length=50)
@@ -67,6 +74,7 @@ class Genus(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Species(models.Model):
     name = models.CharField(max_length=50)
@@ -76,6 +84,8 @@ class Species(models.Model):
         return self.name
 
 # and we'll invent a new thing so we have a model with two foreign keys
+
+
 @python_2_unicode_compatible
 class HybridSpecies(models.Model):
     name = models.CharField(max_length=50)
diff --git a/tests/select_related_onetoone/models.py b/tests/select_related_onetoone/models.py
index d32faafbb9..9af1b3f31b 100644
--- a/tests/select_related_onetoone/models.py
+++ b/tests/select_related_onetoone/models.py
@@ -95,8 +95,10 @@ class Child2(Parent1):
     def __str__(self):
         return self.name1
 
+
 class Child3(Child2):
     value3 = models.IntegerField()
 
+
 class Child4(Child1):
     value4 = models.IntegerField()
diff --git a/tests/select_related_regress/models.py b/tests/select_related_regress/models.py
index 0858c8fc2c..c2611b4843 100644
--- a/tests/select_related_regress/models.py
+++ b/tests/select_related_regress/models.py
@@ -11,6 +11,7 @@ class Building(models.Model):
     def __str__(self):
         return "Building: %s" % self.name
 
+
 @python_2_unicode_compatible
 class Device(models.Model):
     building = models.ForeignKey('Building')
@@ -19,6 +20,7 @@ class Device(models.Model):
     def __str__(self):
         return "device '%s' in building %s" % (self.name, self.building)
 
+
 @python_2_unicode_compatible
 class Port(models.Model):
     device = models.ForeignKey('Device')
@@ -27,6 +29,7 @@ class Port(models.Model):
     def __str__(self):
         return "%s/%s" % (self.device.name, self.port_number)
 
+
 @python_2_unicode_compatible
 class Connection(models.Model):
     start = models.ForeignKey(Port, related_name='connection_start',
@@ -38,45 +41,60 @@ class Connection(models.Model):
 
 # Another non-tree hierarchy that exercises code paths similar to the above
 # example, but in a slightly different configuration.
+
+
 class TUser(models.Model):
     name = models.CharField(max_length=200)
 
+
 class Person(models.Model):
     user = models.ForeignKey(TUser, unique=True)
 
+
 class Organizer(models.Model):
     person = models.ForeignKey(Person)
 
+
 class Student(models.Model):
     person = models.ForeignKey(Person)
 
+
 class Class(models.Model):
     org = models.ForeignKey(Organizer)
 
+
 class Enrollment(models.Model):
     std = models.ForeignKey(Student)
     cls = models.ForeignKey(Class)
 
 # Models for testing bug #8036.
+
+
 class Country(models.Model):
     name = models.CharField(max_length=50)
 
+
 class State(models.Model):
     name = models.CharField(max_length=50)
     country = models.ForeignKey(Country)
 
+
 class ClientStatus(models.Model):
     name = models.CharField(max_length=50)
 
+
 class Client(models.Model):
     name = models.CharField(max_length=50)
     state = models.ForeignKey(State, null=True)
     status = models.ForeignKey(ClientStatus)
 
+
 class SpecialClient(Client):
     value = models.IntegerField()
 
 # Some model inheritance exercises
+
+
 @python_2_unicode_compatible
 class Parent(models.Model):
     name = models.CharField(max_length=10)
@@ -84,9 +102,11 @@ class Parent(models.Model):
     def __str__(self):
         return self.name
 
+
 class Child(Parent):
     value = models.IntegerField()
 
+
 @python_2_unicode_compatible
 class Item(models.Model):
     name = models.CharField(max_length=10)
@@ -96,6 +116,8 @@ class Item(models.Model):
         return self.name
 
 # Models for testing bug #19870.
+
+
 @python_2_unicode_compatible
 class Fowl(models.Model):
     name = models.CharField(max_length=10)
@@ -103,12 +125,15 @@ class Fowl(models.Model):
     def __str__(self):
         return self.name
 
+
 class Hen(Fowl):
     pass
 
+
 class Chick(Fowl):
     mother = models.ForeignKey(Hen)
 
+
 class Base(models.Model):
     name = models.CharField(max_length=10)
     lots_of_text = models.TextField()
@@ -116,12 +141,15 @@ class Base(models.Model):
     class Meta:
         abstract = True
 
+
 class A(Base):
     a_field = models.CharField(max_length=10)
 
+
 class B(Base):
     b_field = models.CharField(max_length=10)
 
+
 class C(Base):
     c_a = models.ForeignKey(A)
     c_b = models.ForeignKey(B)
diff --git a/tests/serializers/tests.py b/tests/serializers/tests.py
index a381396b40..b9e3bb543f 100644
--- a/tests/serializers/tests.py
+++ b/tests/serializers/tests.py
@@ -26,7 +26,7 @@ from .models import (Category, Author, Article, AuthorProfile, Actor, Movie,
 
 
 @override_settings(
-    SERIALIZATION_MODULES = {
+    SERIALIZATION_MODULES={
         "json2": "django.core.serializers.json",
     }
 )
@@ -71,6 +71,7 @@ class SerializerRegistrationTests(TestCase):
         self.assertIn('python', all_formats)
         self.assertNotIn('python', public_formats)
 
+
 class SerializersTestBase(object):
     @staticmethod
     def _comparison_value(value):
@@ -241,9 +242,9 @@ class SerializersTestBase(object):
         # Regression for #12524 -- dates before 1000AD get prefixed
         # 0's on the year
         a = Article.objects.create(
-            author = self.jane,
-            headline = "Nobody remembers the early years",
-            pub_date = datetime(1, 2, 3, 4, 5, 6))
+            author=self.jane,
+            headline="Nobody remembers the early years",
+            pub_date=datetime(1, 2, 3, 4, 5, 6))
 
         serial_str = serializers.serialize(self.serializer_name, [a])
         date_values = self._get_field_values(serial_str, "pub_date")
@@ -338,6 +339,7 @@ class XmlSerializerTestCase(SerializersTestBase, TestCase):
                 ret_list.append("".join(temp))
         return ret_list
 
+
 class XmlSerializerTransactionTestCase(SerializersTransactionTestBase, TransactionTestCase):
     serializer_name = "xml"
     fwd_ref_str = """<?xml version="1.0" encoding="utf-8"?>
@@ -438,6 +440,8 @@ class JsonSerializerTransactionTestCase(SerializersTransactionTestBase, Transact
 
 
 YAML_IMPORT_ERROR_MESSAGE = r'No module named yaml'
+
+
 class YamlImportModuleMock(object):
     """Provides a wrapped import_module function to simulate yaml ImportError
 
diff --git a/tests/serializers_regress/models.py b/tests/serializers_regress/models.py
index 9403a2d534..2c4a43123e 100644
--- a/tests/serializers_regress/models.py
+++ b/tests/serializers_regress/models.py
@@ -13,74 +13,96 @@ from django.contrib.contenttypes.models import ContentType
 # The following classes are for testing basic data
 # marshalling, including NULL values, where allowed.
 
+
 class BinaryData(models.Model):
     data = models.BinaryField(null=True)
 
+
 class BooleanData(models.Model):
     data = models.BooleanField(default=False)
 
+
 class CharData(models.Model):
     data = models.CharField(max_length=30, null=True)
 
+
 class DateData(models.Model):
     data = models.DateField(null=True)
 
+
 class DateTimeData(models.Model):
     data = models.DateTimeField(null=True)
 
+
 class DecimalData(models.Model):
     data = models.DecimalField(null=True, decimal_places=3, max_digits=5)
 
+
 class EmailData(models.Model):
     data = models.EmailField(null=True)
 
+
 class FileData(models.Model):
     data = models.FileField(null=True, upload_to='/foo/bar')
 
+
 class FilePathData(models.Model):
     data = models.FilePathField(null=True)
 
+
 class FloatData(models.Model):
     data = models.FloatField(null=True)
 
+
 class IntegerData(models.Model):
     data = models.IntegerField(null=True)
 
+
 class BigIntegerData(models.Model):
     data = models.BigIntegerField(null=True)
 
 # class ImageData(models.Model):
 #    data = models.ImageField(null=True)
 
+
 class IPAddressData(models.Model):
     with warnings.catch_warnings(record=True) as w:
         warnings.simplefilter("always")
         data = models.IPAddressField(null=True)
 
+
 class GenericIPAddressData(models.Model):
     data = models.GenericIPAddressField(null=True)
 
+
 class NullBooleanData(models.Model):
     data = models.NullBooleanField(null=True)
 
+
 class PositiveIntegerData(models.Model):
     data = models.PositiveIntegerField(null=True)
 
+
 class PositiveSmallIntegerData(models.Model):
     data = models.PositiveSmallIntegerField(null=True)
 
+
 class SlugData(models.Model):
     data = models.SlugField(null=True)
 
+
 class SmallData(models.Model):
     data = models.SmallIntegerField(null=True)
 
+
 class TextData(models.Model):
     data = models.TextField(null=True)
 
+
 class TimeData(models.Model):
     data = models.TimeField(null=True)
 
+
 class Tag(models.Model):
     """A tag on an item."""
     data = models.SlugField()
@@ -92,6 +114,7 @@ class Tag(models.Model):
     class Meta:
         ordering = ["data"]
 
+
 class GenericData(models.Model):
     data = models.CharField(max_length=30)
 
@@ -101,6 +124,7 @@ class GenericData(models.Model):
 # of related objects; in particular, forward, backward,
 # and self references.
 
+
 class Anchor(models.Model):
     """This is a model that can be used as
     something for other models to point at"""
@@ -110,10 +134,12 @@ class Anchor(models.Model):
     class Meta:
         ordering = ('id',)
 
+
 class NaturalKeyAnchorManager(models.Manager):
     def get_by_natural_key(self, data):
         return self.get(data=data)
 
+
 class NaturalKeyAnchor(models.Model):
     objects = NaturalKeyAnchorManager()
 
@@ -123,40 +149,51 @@ class NaturalKeyAnchor(models.Model):
     def natural_key(self):
         return (self.data,)
 
+
 class UniqueAnchor(models.Model):
     """This is a model that can be used as
     something for other models to point at"""
 
     data = models.CharField(unique=True, max_length=30)
 
+
 class FKData(models.Model):
     data = models.ForeignKey(Anchor, null=True)
 
+
 class FKDataNaturalKey(models.Model):
     data = models.ForeignKey(NaturalKeyAnchor, null=True)
 
+
 class M2MData(models.Model):
     data = models.ManyToManyField(Anchor, null=True)
 
+
 class O2OData(models.Model):
     # One to one field can't be null here, since it is a PK.
     data = models.OneToOneField(Anchor, primary_key=True)
 
+
 class FKSelfData(models.Model):
     data = models.ForeignKey('self', null=True)
 
+
 class M2MSelfData(models.Model):
     data = models.ManyToManyField('self', null=True, symmetrical=False)
 
+
 class FKDataToField(models.Model):
     data = models.ForeignKey(UniqueAnchor, null=True, to_field='data')
 
+
 class FKDataToO2O(models.Model):
     data = models.ForeignKey(O2OData, null=True)
 
+
 class M2MIntermediateData(models.Model):
     data = models.ManyToManyField(Anchor, null=True, through='Intermediate')
 
+
 class Intermediate(models.Model):
     left = models.ForeignKey(M2MIntermediateData)
     right = models.ForeignKey(Anchor)
@@ -169,9 +206,11 @@ class Intermediate(models.Model):
 # because they can't be used as a primary key on one
 # or all database backends.
 
+
 class BooleanPKData(models.Model):
     data = models.BooleanField(primary_key=True, default=False)
 
+
 class CharPKData(models.Model):
     data = models.CharField(max_length=30, primary_key=True)
 
@@ -181,32 +220,39 @@ class CharPKData(models.Model):
 # class DateTimePKData(models.Model):
 #    data = models.DateTimeField(primary_key=True)
 
+
 class DecimalPKData(models.Model):
     data = models.DecimalField(primary_key=True, decimal_places=3, max_digits=5)
 
+
 class EmailPKData(models.Model):
     data = models.EmailField(primary_key=True)
 
 # class FilePKData(models.Model):
 #    data = models.FileField(primary_key=True, upload_to='/foo/bar')
 
+
 class FilePathPKData(models.Model):
     data = models.FilePathField(primary_key=True)
 
+
 class FloatPKData(models.Model):
     data = models.FloatField(primary_key=True)
 
+
 class IntegerPKData(models.Model):
     data = models.IntegerField(primary_key=True)
 
 # class ImagePKData(models.Model):
 #    data = models.ImageField(primary_key=True)
 
+
 class IPAddressPKData(models.Model):
     with warnings.catch_warnings(record=True) as w:
         warnings.simplefilter("always")
         data = models.IPAddressField(primary_key=True)
 
+
 class GenericIPAddressPKData(models.Model):
     data = models.GenericIPAddressField(primary_key=True)
 
@@ -214,15 +260,19 @@ class GenericIPAddressPKData(models.Model):
 # class NullBooleanPKData(models.Model):
 #     data = models.NullBooleanField(primary_key=True)
 
+
 class PositiveIntegerPKData(models.Model):
     data = models.PositiveIntegerField(primary_key=True)
 
+
 class PositiveSmallIntegerPKData(models.Model):
     data = models.PositiveSmallIntegerField(primary_key=True)
 
+
 class SlugPKData(models.Model):
     data = models.SlugField(primary_key=True)
 
+
 class SmallPKData(models.Model):
     data = models.SmallIntegerField(primary_key=True)
 
@@ -232,6 +282,7 @@ class SmallPKData(models.Model):
 # class TimePKData(models.Model):
 #    data = models.TimeField(primary_key=True)
 
+
 class ComplexModel(models.Model):
     field1 = models.CharField(max_length=10)
     field2 = models.CharField(max_length=10)
@@ -239,9 +290,12 @@ class ComplexModel(models.Model):
 
 # Tests for handling fields with pre_save functions, or
 # models with save functions that modify data
+
+
 class AutoNowDateTimeData(models.Model):
     data = models.DateTimeField(null=True, auto_now=True)
 
+
 class ModifyingSaveData(models.Model):
     data = models.IntegerField(null=True)
 
@@ -256,33 +310,42 @@ class ModifyingSaveData(models.Model):
 
 # Tests for serialization of models using inheritance.
 # Regression for #7202, #7350
+
+
 class AbstractBaseModel(models.Model):
     parent_data = models.IntegerField()
 
     class Meta:
         abstract = True
 
+
 class InheritAbstractModel(AbstractBaseModel):
     child_data = models.IntegerField()
 
+
 class BaseModel(models.Model):
     parent_data = models.IntegerField()
 
+
 class InheritBaseModel(BaseModel):
     child_data = models.IntegerField()
 
+
 class ExplicitInheritBaseModel(BaseModel):
     parent = models.OneToOneField(BaseModel)
     child_data = models.IntegerField()
 
+
 class ProxyBaseModel(BaseModel):
     class Meta:
         proxy = True
 
+
 class ProxyProxyBaseModel(ProxyBaseModel):
     class Meta:
         proxy = True
 
+
 class LengthModel(models.Model):
     data = models.IntegerField()
 
diff --git a/tests/serializers_regress/tests.py b/tests/serializers_regress/tests.py
index a56abe0b6b..c8f29f471e 100644
--- a/tests/serializers_regress/tests.py
+++ b/tests/serializers_regress/tests.py
@@ -48,12 +48,15 @@ from .models import (BinaryData, BooleanData, CharData, DateData, DateTimeData,
 # The save method is a raw base model save, to make
 # sure that the data in the database matches the
 # exact test case.
+
+
 def data_create(pk, klass, data):
     instance = klass(id=pk)
     instance.data = data
     models.Model.save_base(instance, raw=True)
     return [instance]
 
+
 def generic_create(pk, klass, data):
     instance = klass(id=pk)
     instance.data = data[0]
@@ -62,23 +65,27 @@ def generic_create(pk, klass, data):
         instance.tags.create(data=tag)
     return [instance]
 
+
 def fk_create(pk, klass, data):
     instance = klass(id=pk)
     setattr(instance, 'data_id', data)
     models.Model.save_base(instance, raw=True)
     return [instance]
 
+
 def m2m_create(pk, klass, data):
     instance = klass(id=pk)
     models.Model.save_base(instance, raw=True)
     instance.data = data
     return [instance]
 
+
 def im2m_create(pk, klass, data):
     instance = klass(id=pk)
     models.Model.save_base(instance, raw=True)
     return [instance]
 
+
 def im_create(pk, klass, data):
     instance = klass(id=pk)
     instance.right_id = data['right']
@@ -88,18 +95,21 @@ def im_create(pk, klass, data):
     models.Model.save_base(instance, raw=True)
     return [instance]
 
+
 def o2o_create(pk, klass, data):
     instance = klass()
     instance.data_id = data
     models.Model.save_base(instance, raw=True)
     return [instance]
 
+
 def pk_create(pk, klass, data):
     instance = klass()
     instance.data = data
     models.Model.save_base(instance, raw=True)
     return [instance]
 
+
 def inherited_create(pk, klass, data):
     instance = klass(id=pk, **data)
     # This isn't a raw save because:
@@ -115,6 +125,8 @@ def inherited_create(pk, klass, data):
 
 # A set of functions that can be used to compare
 # test data objects of various kinds
+
+
 def data_compare(testcase, pk, klass, data):
     instance = klass.objects.get(id=pk)
     if klass == BinaryData and data is not None:
@@ -129,23 +141,28 @@ def data_compare(testcase, pk, klass, data):
                  pk, data, type(data), instance, type(instance.data))
         )
 
+
 def generic_compare(testcase, pk, klass, data):
     instance = klass.objects.get(id=pk)
     testcase.assertEqual(data[0], instance.data)
     testcase.assertEqual(data[1:], [t.data for t in instance.tags.order_by('id')])
 
+
 def fk_compare(testcase, pk, klass, data):
     instance = klass.objects.get(id=pk)
     testcase.assertEqual(data, instance.data_id)
 
+
 def m2m_compare(testcase, pk, klass, data):
     instance = klass.objects.get(id=pk)
     testcase.assertEqual(data, [obj.id for obj in instance.data.order_by('id')])
 
+
 def im2m_compare(testcase, pk, klass, data):
     klass.objects.get(id=pk)
     # actually nothing else to check, the instance just should exist
 
+
 def im_compare(testcase, pk, klass, data):
     instance = klass.objects.get(id=pk)
     testcase.assertEqual(data['left'], instance.left_id)
@@ -155,14 +172,17 @@ def im_compare(testcase, pk, klass, data):
     else:
         testcase.assertEqual("doesn't matter", instance.extra)
 
+
 def o2o_compare(testcase, pk, klass, data):
     instance = klass.objects.get(data=data)
     testcase.assertEqual(data, instance.data_id)
 
+
 def pk_compare(testcase, pk, klass, data):
     instance = klass.objects.get(data=data)
     testcase.assertEqual(data, instance.data)
 
+
 def inherited_compare(testcase, pk, klass, data):
     instance = klass.objects.get(id=pk)
     for key, value in data.items():
@@ -256,21 +276,21 @@ The end."""),
     (data_obj, 301, Anchor, "Anchor 2"),
     (data_obj, 302, UniqueAnchor, "UAnchor 1"),
 
-    (fk_obj, 400, FKData, 300), # Post reference
-    (fk_obj, 401, FKData, 500), # Pre reference
-    (fk_obj, 402, FKData, None), # Empty reference
+    (fk_obj, 400, FKData, 300),  # Post reference
+    (fk_obj, 401, FKData, 500),  # Pre reference
+    (fk_obj, 402, FKData, None),  # Empty reference
 
-    (m2m_obj, 410, M2MData, []), # Empty set
-    (m2m_obj, 411, M2MData, [300, 301]), # Post reference
-    (m2m_obj, 412, M2MData, [500, 501]), # Pre reference
-    (m2m_obj, 413, M2MData, [300, 301, 500, 501]), # Pre and Post reference
+    (m2m_obj, 410, M2MData, []),  # Empty set
+    (m2m_obj, 411, M2MData, [300, 301]),  # Post reference
+    (m2m_obj, 412, M2MData, [500, 501]),  # Pre reference
+    (m2m_obj, 413, M2MData, [300, 301, 500, 501]),  # Pre and Post reference
 
-    (o2o_obj, None, O2OData, 300), # Post reference
-    (o2o_obj, None, O2OData, 500), # Pre reference
+    (o2o_obj, None, O2OData, 300),  # Post reference
+    (o2o_obj, None, O2OData, 500),  # Pre reference
 
-    (fk_obj, 430, FKSelfData, 431), # Pre reference
-    (fk_obj, 431, FKSelfData, 430), # Post reference
-    (fk_obj, 432, FKSelfData, None), # Empty reference
+    (fk_obj, 430, FKSelfData, 431),  # Pre reference
+    (fk_obj, 431, FKSelfData, 430),  # Post reference
+    (fk_obj, 432, FKSelfData, None),  # Empty reference
 
     (m2m_obj, 440, M2MSelfData, []),
     (m2m_obj, 441, M2MSelfData, []),
@@ -380,6 +400,8 @@ if connection.features.allows_primary_key_0:
 
 # Dynamically create serializer tests to ensure that all
 # registered serializers are automatically tested.
+
+
 class SerializerTests(TestCase):
     def test_get_unknown_serializer(self):
         """
@@ -496,6 +518,7 @@ def naturalKeySerializerTest(format, self):
     for klass, count in instance_count.items():
         self.assertEqual(count, klass.objects.count())
 
+
 def fieldsTest(format, self):
     obj = ComplexModel(field1='first', field2='second', field3='third')
     obj.save_base(raw=True)
@@ -509,6 +532,7 @@ def fieldsTest(format, self):
     self.assertEqual(result.object.field2, '')
     self.assertEqual(result.object.field3, 'third')
 
+
 def streamTest(format, self):
     obj = ComplexModel(field1='first', field2='second', field3='third')
     obj.save_base(raw=True)
diff --git a/tests/servers/tests.py b/tests/servers/tests.py
index 77c2e39521..5ce86d3529 100644
--- a/tests/servers/tests.py
+++ b/tests/servers/tests.py
@@ -107,6 +107,7 @@ class LiveServerAddress(LiveServerBase):
         # test runner and the overridden setUpClass() method is executed.
         pass
 
+
 class LiveServerViews(LiveServerBase):
     def test_404(self):
         """
diff --git a/tests/settings_tests/tests.py b/tests/settings_tests/tests.py
index b1321d50f3..3597982457 100644
--- a/tests/settings_tests/tests.py
+++ b/tests/settings_tests/tests.py
@@ -76,6 +76,7 @@ class ClassDecoratedTestCase(ClassDecoratedTestCaseSuper):
 class ParentDecoratedTestCase(TestCase):
     pass
 
+
 @override_settings(TEST='override-child')
 class ChildDecoratedTestCase(ParentDecoratedTestCase):
     def test_override_settings_inheritance(self):
diff --git a/tests/signals/models.py b/tests/signals/models.py
index e54a22fce9..765230a44e 100644
--- a/tests/signals/models.py
+++ b/tests/signals/models.py
@@ -15,6 +15,7 @@ class Person(models.Model):
     def __str__(self):
         return "%s %s" % (self.first_name, self.last_name)
 
+
 @python_2_unicode_compatible
 class Car(models.Model):
     make = models.CharField(max_length=20)
diff --git a/tests/signals/tests.py b/tests/signals/tests.py
index b7ee222c94..1eb2ffb4a3 100644
--- a/tests/signals/tests.py
+++ b/tests/signals/tests.py
@@ -18,6 +18,7 @@ class PostDeleteHandler(object):
             (instance, instance.id is None)
         )
 
+
 class MyReceiver(object):
     def __init__(self, param):
         self.param = param
@@ -27,6 +28,7 @@ class MyReceiver(object):
         self._run = True
         signal.disconnect(receiver=self, sender=sender)
 
+
 class SignalTests(TestCase):
     def test_basic(self):
         # Save up the number of connected signals so that we can check at the
diff --git a/tests/signals_regress/models.py b/tests/signals_regress/models.py
index 829314c06c..5c28b76669 100644
--- a/tests/signals_regress/models.py
+++ b/tests/signals_regress/models.py
@@ -9,6 +9,7 @@ class Author(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Book(models.Model):
     name = models.CharField(max_length=20)
diff --git a/tests/signing/tests.py b/tests/signing/tests.py
index 3486cf0591..fc8390e9e8 100644
--- a/tests/signing/tests.py
+++ b/tests/signing/tests.py
@@ -105,6 +105,7 @@ class TestSigner(TestCase):
             self.assertRaises(
                 signing.BadSignature, signing.loads, transform(encoded))
 
+
 class TestTimestampSigner(TestCase):
 
     def test_timestamp_signer(self):
diff --git a/tests/sites_framework/models.py b/tests/sites_framework/models.py
index 55c4f4992e..12b1d08dd8 100644
--- a/tests/sites_framework/models.py
+++ b/tests/sites_framework/models.py
@@ -3,6 +3,7 @@ from django.contrib.sites.models import Site
 from django.db import models
 from django.utils.encoding import python_2_unicode_compatible
 
+
 @python_2_unicode_compatible
 class AbstractArticle(models.Model):
     title = models.CharField(max_length=50)
@@ -16,23 +17,28 @@ class AbstractArticle(models.Model):
     def __str__(self):
         return self.title
 
+
 class SyndicatedArticle(AbstractArticle):
     sites = models.ManyToManyField(Site)
 
+
 class ExclusiveArticle(AbstractArticle):
     site = models.ForeignKey(Site)
 
+
 class CustomArticle(AbstractArticle):
     places_this_article_should_appear = models.ForeignKey(Site)
 
     objects = models.Manager()
     on_site = CurrentSiteManager("places_this_article_should_appear")
 
+
 class InvalidArticle(AbstractArticle):
     site = models.ForeignKey(Site)
 
     objects = models.Manager()
     on_site = CurrentSiteManager("places_this_article_should_appear")
 
+
 class ConfusedArticle(AbstractArticle):
     site = models.IntegerField()
diff --git a/tests/staticfiles_tests/storage.py b/tests/staticfiles_tests/storage.py
index 4d49e6fbb2..e47af18b22 100644
--- a/tests/staticfiles_tests/storage.py
+++ b/tests/staticfiles_tests/storage.py
@@ -2,6 +2,7 @@ from datetime import datetime
 from django.core.files import storage
 from django.contrib.staticfiles.storage import CachedStaticFilesStorage
 
+
 class DummyStorage(storage.Storage):
     """
     A storage class that does implement modified_time() but raises
diff --git a/tests/str/models.py b/tests/str/models.py
index 488012e861..e203de411e 100644
--- a/tests/str/models.py
+++ b/tests/str/models.py
@@ -27,6 +27,7 @@ class Article(models.Model):
         # in ASCII.
         return self.headline
 
+
 @python_2_unicode_compatible
 class InternationalArticle(models.Model):
     headline = models.CharField(max_length=100)
diff --git a/tests/string_lookup/models.py b/tests/string_lookup/models.py
index 43ed90a462..4037c2950e 100644
--- a/tests/string_lookup/models.py
+++ b/tests/string_lookup/models.py
@@ -14,6 +14,7 @@ class Foo(models.Model):
     def __str__(self):
         return "Foo %s" % self.name
 
+
 @python_2_unicode_compatible
 class Bar(models.Model):
     name = models.CharField(max_length=50)
@@ -24,6 +25,7 @@ class Bar(models.Model):
     def __str__(self):
         return "Bar %s" % self.place.name
 
+
 @python_2_unicode_compatible
 class Whiz(models.Model):
     name = models.CharField(max_length=50)
@@ -31,6 +33,7 @@ class Whiz(models.Model):
     def __str__(self):
         return "Whiz %s" % self.name
 
+
 @python_2_unicode_compatible
 class Child(models.Model):
     parent = models.OneToOneField('Base')
@@ -39,6 +42,7 @@ class Child(models.Model):
     def __str__(self):
         return "Child %s" % self.name
 
+
 @python_2_unicode_compatible
 class Base(models.Model):
     name = models.CharField(max_length=50)
@@ -46,6 +50,7 @@ class Base(models.Model):
     def __str__(self):
         return "Base %s" % self.name
 
+
 @python_2_unicode_compatible
 class Article(models.Model):
     name = models.CharField(max_length=50)
diff --git a/tests/syndication/tests.py b/tests/syndication/tests.py
index eeadf85600..a3b75369be 100644
--- a/tests/syndication/tests.py
+++ b/tests/syndication/tests.py
@@ -49,6 +49,7 @@ class FeedTestCase(TestCase):
 # Feed view
 ######################################
 
+
 class SyndicationFeedTest(FeedTestCase):
     """
     Tests for the high-level syndication feed framework.
diff --git a/tests/tablespaces/models.py b/tests/tablespaces/models.py
index d5d179303f..ecd1944294 100644
--- a/tests/tablespaces/models.py
+++ b/tests/tablespaces/models.py
@@ -7,15 +7,18 @@ from django.db import models
 # "reference" models to avoid errors when other tests run 'migrate'
 # (proxy_models_inheritance does).
 
+
 class ScientistRef(models.Model):
     name = models.CharField(max_length=50)
 
+
 class ArticleRef(models.Model):
     title = models.CharField(max_length=50, unique=True)
     code = models.CharField(max_length=50, unique=True)
     authors = models.ManyToManyField(ScientistRef, related_name='articles_written_set')
     reviewers = models.ManyToManyField(ScientistRef, related_name='articles_reviewed_set')
 
+
 class Scientist(models.Model):
     name = models.CharField(max_length=50)
 
@@ -24,6 +27,7 @@ class Scientist(models.Model):
         db_tablespace = 'tbl_tbsp'
         managed = False
 
+
 class Article(models.Model):
     title = models.CharField(max_length=50, unique=True)
     code = models.CharField(max_length=50, unique=True, db_tablespace='idx_tbsp')
diff --git a/tests/tablespaces/tests.py b/tests/tablespaces/tests.py
index f04bf29611..6a81643a0c 100644
--- a/tests/tablespaces/tests.py
+++ b/tests/tablespaces/tests.py
@@ -14,9 +14,11 @@ from .models import Article, ArticleRef, Authors, Reviewers, Scientist, Scientis
 # because they're evaluated when the model class is defined. As a consequence,
 # @override_settings doesn't work, and the tests depend
 
+
 def sql_for_table(model):
     return '\n'.join(connection.creation.sql_create_model(model, no_style())[0])
 
+
 def sql_for_index(model):
     return '\n'.join(connection.creation.sql_indexes_for_model(model, no_style()))
 
diff --git a/tests/template_tests/filters.py b/tests/template_tests/filters.py
index 36a519fd90..0531fb09cf 100644
--- a/tests/template_tests/filters.py
+++ b/tests/template_tests/filters.py
@@ -16,11 +16,14 @@ from django.utils.safestring import mark_safe
 from django.utils import timezone
 
 # These two classes are used to test auto-escaping of __unicode__ output.
+
+
 @python_2_unicode_compatible
 class UnsafeClass:
     def __str__(self):
         return 'you & me'
 
+
 @python_2_unicode_compatible
 class SafeClass:
     def __str__(self):
@@ -29,6 +32,8 @@ class SafeClass:
 # RESULT SYNTAX --
 # 'template_name': ('template contents', 'context dict',
 #                   'expected string output' or Exception class)
+
+
 def get_filter_tests():
     now = datetime.now()
     now_tz = timezone.make_aware(now, timezone.get_default_timezone())
@@ -38,9 +43,9 @@ def get_filter_tests():
     # NOTE: \xa0 avoids wrapping between value and unit
     return {
         # Default compare with datetime.now()
-        'filter-timesince01': ('{{ a|timesince }}', {'a': datetime.now() + timedelta(minutes=-1, seconds = -10)}, '1\xa0minute'),
-        'filter-timesince02': ('{{ a|timesince }}', {'a': datetime.now() - timedelta(days=1, minutes = 1)}, '1\xa0day'),
-        'filter-timesince03': ('{{ a|timesince }}', {'a': datetime.now() - timedelta(hours=1, minutes=25, seconds = 10)}, '1\xa0hour, 25\xa0minutes'),
+        'filter-timesince01': ('{{ a|timesince }}', {'a': datetime.now() + timedelta(minutes=-1, seconds=-10)}, '1\xa0minute'),
+        'filter-timesince02': ('{{ a|timesince }}', {'a': datetime.now() - timedelta(days=1, minutes=1)}, '1\xa0day'),
+        'filter-timesince03': ('{{ a|timesince }}', {'a': datetime.now() - timedelta(hours=1, minutes=25, seconds=10)}, '1\xa0hour, 25\xa0minutes'),
 
         # Compare to a given parameter
         'filter-timesince04': ('{{ a|timesince:b }}', {'a': now - timedelta(days=2), 'b': now - timedelta(days=1)}, '1\xa0day'),
@@ -71,7 +76,7 @@ def get_filter_tests():
         # Default compare with datetime.now()
         'filter-timeuntil01': ('{{ a|timeuntil }}', {'a': datetime.now() + timedelta(minutes=2, seconds=10)}, '2\xa0minutes'),
         'filter-timeuntil02': ('{{ a|timeuntil }}', {'a': (datetime.now() + timedelta(days=1, seconds=10))}, '1\xa0day'),
-        'filter-timeuntil03': ('{{ a|timeuntil }}', {'a': (datetime.now() + timedelta(hours=8, minutes=10, seconds = 10))}, '8\xa0hours, 10\xa0minutes'),
+        'filter-timeuntil03': ('{{ a|timeuntil }}', {'a': (datetime.now() + timedelta(hours=8, minutes=10, seconds=10))}, '8\xa0hours, 10\xa0minutes'),
 
         # Compare to a given parameter
         'filter-timeuntil04': ('{{ a|timeuntil:b }}', {'a': now - timedelta(days=1), 'b': now - timedelta(days=2)}, '1\xa0day'),
diff --git a/tests/template_tests/templatetags/bad_tag.py b/tests/template_tests/templatetags/bad_tag.py
index 3cceb31eb0..b806423df3 100644
--- a/tests/template_tests/templatetags/bad_tag.py
+++ b/tests/template_tests/templatetags/bad_tag.py
@@ -3,10 +3,12 @@ from django import template
 
 register = template.Library()
 
+
 @register.tag
 def badtag(parser, token):
     raise RuntimeError("I am a bad tag")
 
+
 @register.simple_tag
 def badsimpletag():
     raise RuntimeError("I am a bad simpletag")
diff --git a/tests/template_tests/templatetags/custom.py b/tests/template_tests/templatetags/custom.py
index 9d328f8d54..9aa51931e0 100644
--- a/tests/template_tests/templatetags/custom.py
+++ b/tests/template_tests/templatetags/custom.py
@@ -7,11 +7,13 @@ from django.utils import six
 
 register = template.Library()
 
+
 @register.filter
 @stringfilter
 def trim(value, num):
     return value[:num]
 
+
 @register.filter
 def noop(value, param=None):
     """A noop filter that always return its first argument and does nothing with
@@ -19,60 +21,70 @@ def noop(value, param=None):
     Useful for testing out whitespace in filter arguments (see #19882)."""
     return value
 
+
 @register.simple_tag
 def no_params():
     """Expected no_params __doc__"""
     return "no_params - Expected result"
 no_params.anything = "Expected no_params __dict__"
 
+
 @register.simple_tag
 def one_param(arg):
     """Expected one_param __doc__"""
     return "one_param - Expected result: %s" % arg
 one_param.anything = "Expected one_param __dict__"
 
+
 @register.simple_tag(takes_context=False)
 def explicit_no_context(arg):
     """Expected explicit_no_context __doc__"""
     return "explicit_no_context - Expected result: %s" % arg
 explicit_no_context.anything = "Expected explicit_no_context __dict__"
 
+
 @register.simple_tag(takes_context=True)
 def no_params_with_context(context):
     """Expected no_params_with_context __doc__"""
     return "no_params_with_context - Expected result (context value: %s)" % context['value']
 no_params_with_context.anything = "Expected no_params_with_context __dict__"
 
+
 @register.simple_tag(takes_context=True)
 def params_and_context(context, arg):
     """Expected params_and_context __doc__"""
     return "params_and_context - Expected result (context value: %s): %s" % (context['value'], arg)
 params_and_context.anything = "Expected params_and_context __dict__"
 
+
 @register.simple_tag
 def simple_two_params(one, two):
     """Expected simple_two_params __doc__"""
     return "simple_two_params - Expected result: %s, %s" % (one, two)
 simple_two_params.anything = "Expected simple_two_params __dict__"
 
+
 @register.simple_tag
 def simple_one_default(one, two='hi'):
     """Expected simple_one_default __doc__"""
     return "simple_one_default - Expected result: %s, %s" % (one, two)
 simple_one_default.anything = "Expected simple_one_default __dict__"
 
+
 @register.simple_tag
 def simple_unlimited_args(one, two='hi', *args):
     """Expected simple_unlimited_args __doc__"""
     return "simple_unlimited_args - Expected result: %s" % (', '.join(six.text_type(arg) for arg in [one, two] + list(args)))
 simple_unlimited_args.anything = "Expected simple_unlimited_args __dict__"
 
+
 @register.simple_tag
 def simple_only_unlimited_args(*args):
     """Expected simple_only_unlimited_args __doc__"""
     return "simple_only_unlimited_args - Expected result: %s" % ', '.join(six.text_type(arg) for arg in args)
 simple_only_unlimited_args.anything = "Expected simple_only_unlimited_args __dict__"
 
+
 @register.simple_tag
 def simple_unlimited_args_kwargs(one, two='hi', *args, **kwargs):
     """Expected simple_unlimited_args_kwargs __doc__"""
@@ -84,146 +96,171 @@ def simple_unlimited_args_kwargs(one, two='hi', *args, **kwargs):
     )
 simple_unlimited_args_kwargs.anything = "Expected simple_unlimited_args_kwargs __dict__"
 
+
 @register.simple_tag(takes_context=True)
 def simple_tag_without_context_parameter(arg):
     """Expected simple_tag_without_context_parameter __doc__"""
     return "Expected result"
 simple_tag_without_context_parameter.anything = "Expected simple_tag_without_context_parameter __dict__"
 
+
 @register.simple_tag(takes_context=True)
 def current_app(context):
     return "%s" % context.current_app
 
+
 @register.simple_tag(takes_context=True)
 def use_l10n(context):
     return "%s" % context.use_l10n
 
+
 @register.simple_tag(name='minustwo')
 def minustwo_overridden_name(value):
     return value - 2
 
 register.simple_tag(lambda x: x - 1, name='minusone')
 
+
 @register.inclusion_tag('inclusion.html')
 def inclusion_no_params():
     """Expected inclusion_no_params __doc__"""
     return {"result": "inclusion_no_params - Expected result"}
 inclusion_no_params.anything = "Expected inclusion_no_params __dict__"
 
+
 @register.inclusion_tag(get_template('inclusion.html'))
 def inclusion_no_params_from_template():
     """Expected inclusion_no_params_from_template __doc__"""
     return {"result": "inclusion_no_params_from_template - Expected result"}
 inclusion_no_params_from_template.anything = "Expected inclusion_no_params_from_template __dict__"
 
+
 @register.inclusion_tag('inclusion.html')
 def inclusion_one_param(arg):
     """Expected inclusion_one_param __doc__"""
     return {"result": "inclusion_one_param - Expected result: %s" % arg}
 inclusion_one_param.anything = "Expected inclusion_one_param __dict__"
 
+
 @register.inclusion_tag(get_template('inclusion.html'))
 def inclusion_one_param_from_template(arg):
     """Expected inclusion_one_param_from_template __doc__"""
     return {"result": "inclusion_one_param_from_template - Expected result: %s" % arg}
 inclusion_one_param_from_template.anything = "Expected inclusion_one_param_from_template __dict__"
 
+
 @register.inclusion_tag('inclusion.html', takes_context=False)
 def inclusion_explicit_no_context(arg):
     """Expected inclusion_explicit_no_context __doc__"""
     return {"result": "inclusion_explicit_no_context - Expected result: %s" % arg}
 inclusion_explicit_no_context.anything = "Expected inclusion_explicit_no_context __dict__"
 
+
 @register.inclusion_tag(get_template('inclusion.html'), takes_context=False)
 def inclusion_explicit_no_context_from_template(arg):
     """Expected inclusion_explicit_no_context_from_template __doc__"""
     return {"result": "inclusion_explicit_no_context_from_template - Expected result: %s" % arg}
 inclusion_explicit_no_context_from_template.anything = "Expected inclusion_explicit_no_context_from_template __dict__"
 
+
 @register.inclusion_tag('inclusion.html', takes_context=True)
 def inclusion_no_params_with_context(context):
     """Expected inclusion_no_params_with_context __doc__"""
     return {"result": "inclusion_no_params_with_context - Expected result (context value: %s)" % context['value']}
 inclusion_no_params_with_context.anything = "Expected inclusion_no_params_with_context __dict__"
 
+
 @register.inclusion_tag(get_template('inclusion.html'), takes_context=True)
 def inclusion_no_params_with_context_from_template(context):
     """Expected inclusion_no_params_with_context_from_template __doc__"""
     return {"result": "inclusion_no_params_with_context_from_template - Expected result (context value: %s)" % context['value']}
 inclusion_no_params_with_context_from_template.anything = "Expected inclusion_no_params_with_context_from_template __dict__"
 
+
 @register.inclusion_tag('inclusion.html', takes_context=True)
 def inclusion_params_and_context(context, arg):
     """Expected inclusion_params_and_context __doc__"""
     return {"result": "inclusion_params_and_context - Expected result (context value: %s): %s" % (context['value'], arg)}
 inclusion_params_and_context.anything = "Expected inclusion_params_and_context __dict__"
 
+
 @register.inclusion_tag(get_template('inclusion.html'), takes_context=True)
 def inclusion_params_and_context_from_template(context, arg):
     """Expected inclusion_params_and_context_from_template __doc__"""
     return {"result": "inclusion_params_and_context_from_template - Expected result (context value: %s): %s" % (context['value'], arg)}
 inclusion_params_and_context_from_template.anything = "Expected inclusion_params_and_context_from_template __dict__"
 
+
 @register.inclusion_tag('inclusion.html')
 def inclusion_two_params(one, two):
     """Expected inclusion_two_params __doc__"""
     return {"result": "inclusion_two_params - Expected result: %s, %s" % (one, two)}
 inclusion_two_params.anything = "Expected inclusion_two_params __dict__"
 
+
 @register.inclusion_tag(get_template('inclusion.html'))
 def inclusion_two_params_from_template(one, two):
     """Expected inclusion_two_params_from_template __doc__"""
     return {"result": "inclusion_two_params_from_template - Expected result: %s, %s" % (one, two)}
 inclusion_two_params_from_template.anything = "Expected inclusion_two_params_from_template __dict__"
 
+
 @register.inclusion_tag('inclusion.html')
 def inclusion_one_default(one, two='hi'):
     """Expected inclusion_one_default __doc__"""
     return {"result": "inclusion_one_default - Expected result: %s, %s" % (one, two)}
 inclusion_one_default.anything = "Expected inclusion_one_default __dict__"
 
+
 @register.inclusion_tag(get_template('inclusion.html'))
 def inclusion_one_default_from_template(one, two='hi'):
     """Expected inclusion_one_default_from_template __doc__"""
     return {"result": "inclusion_one_default_from_template - Expected result: %s, %s" % (one, two)}
 inclusion_one_default_from_template.anything = "Expected inclusion_one_default_from_template __dict__"
 
+
 @register.inclusion_tag('inclusion.html')
 def inclusion_unlimited_args(one, two='hi', *args):
     """Expected inclusion_unlimited_args __doc__"""
     return {"result": "inclusion_unlimited_args - Expected result: %s" % (', '.join(six.text_type(arg) for arg in [one, two] + list(args)))}
 inclusion_unlimited_args.anything = "Expected inclusion_unlimited_args __dict__"
 
+
 @register.inclusion_tag(get_template('inclusion.html'))
 def inclusion_unlimited_args_from_template(one, two='hi', *args):
     """Expected inclusion_unlimited_args_from_template __doc__"""
     return {"result": "inclusion_unlimited_args_from_template - Expected result: %s" % (', '.join(six.text_type(arg) for arg in [one, two] + list(args)))}
 inclusion_unlimited_args_from_template.anything = "Expected inclusion_unlimited_args_from_template __dict__"
 
+
 @register.inclusion_tag('inclusion.html')
 def inclusion_only_unlimited_args(*args):
     """Expected inclusion_only_unlimited_args __doc__"""
     return {"result": "inclusion_only_unlimited_args - Expected result: %s" % (', '.join(six.text_type(arg) for arg in args))}
 inclusion_only_unlimited_args.anything = "Expected inclusion_only_unlimited_args __dict__"
 
+
 @register.inclusion_tag(get_template('inclusion.html'))
 def inclusion_only_unlimited_args_from_template(*args):
     """Expected inclusion_only_unlimited_args_from_template __doc__"""
     return {"result": "inclusion_only_unlimited_args_from_template - Expected result: %s" % (', '.join(six.text_type(arg) for arg in args))}
 inclusion_only_unlimited_args_from_template.anything = "Expected inclusion_only_unlimited_args_from_template __dict__"
 
+
 @register.inclusion_tag('test_incl_tag_current_app.html', takes_context=True)
 def inclusion_tag_current_app(context):
     """Expected inclusion_tag_current_app __doc__"""
     return {}
 inclusion_tag_current_app.anything = "Expected inclusion_tag_current_app __dict__"
 
+
 @register.inclusion_tag('test_incl_tag_use_l10n.html', takes_context=True)
 def inclusion_tag_use_l10n(context):
     """Expected inclusion_tag_use_l10n __doc__"""
     return {}
 inclusion_tag_use_l10n.anything = "Expected inclusion_tag_use_l10n __dict__"
 
+
 @register.inclusion_tag('inclusion.html')
 def inclusion_unlimited_args_kwargs(one, two='hi', *args, **kwargs):
     """Expected inclusion_unlimited_args_kwargs __doc__"""
@@ -235,66 +272,77 @@ def inclusion_unlimited_args_kwargs(one, two='hi', *args, **kwargs):
     )}
 inclusion_unlimited_args_kwargs.anything = "Expected inclusion_unlimited_args_kwargs __dict__"
 
+
 @register.inclusion_tag('inclusion.html', takes_context=True)
 def inclusion_tag_without_context_parameter(arg):
     """Expected inclusion_tag_without_context_parameter __doc__"""
     return {}
 inclusion_tag_without_context_parameter.anything = "Expected inclusion_tag_without_context_parameter __dict__"
 
+
 @register.assignment_tag
 def assignment_no_params():
     """Expected assignment_no_params __doc__"""
     return "assignment_no_params - Expected result"
 assignment_no_params.anything = "Expected assignment_no_params __dict__"
 
+
 @register.assignment_tag
 def assignment_one_param(arg):
     """Expected assignment_one_param __doc__"""
     return "assignment_one_param - Expected result: %s" % arg
 assignment_one_param.anything = "Expected assignment_one_param __dict__"
 
+
 @register.assignment_tag(takes_context=False)
 def assignment_explicit_no_context(arg):
     """Expected assignment_explicit_no_context __doc__"""
     return "assignment_explicit_no_context - Expected result: %s" % arg
 assignment_explicit_no_context.anything = "Expected assignment_explicit_no_context __dict__"
 
+
 @register.assignment_tag(takes_context=True)
 def assignment_no_params_with_context(context):
     """Expected assignment_no_params_with_context __doc__"""
     return "assignment_no_params_with_context - Expected result (context value: %s)" % context['value']
 assignment_no_params_with_context.anything = "Expected assignment_no_params_with_context __dict__"
 
+
 @register.assignment_tag(takes_context=True)
 def assignment_params_and_context(context, arg):
     """Expected assignment_params_and_context __doc__"""
     return "assignment_params_and_context - Expected result (context value: %s): %s" % (context['value'], arg)
 assignment_params_and_context.anything = "Expected assignment_params_and_context __dict__"
 
+
 @register.assignment_tag
 def assignment_two_params(one, two):
     """Expected assignment_two_params __doc__"""
     return "assignment_two_params - Expected result: %s, %s" % (one, two)
 assignment_two_params.anything = "Expected assignment_two_params __dict__"
 
+
 @register.assignment_tag
 def assignment_one_default(one, two='hi'):
     """Expected assignment_one_default __doc__"""
     return "assignment_one_default - Expected result: %s, %s" % (one, two)
 assignment_one_default.anything = "Expected assignment_one_default __dict__"
 
+
 @register.assignment_tag
 def assignment_unlimited_args(one, two='hi', *args):
     """Expected assignment_unlimited_args __doc__"""
     return "assignment_unlimited_args - Expected result: %s" % (', '.join(six.text_type(arg) for arg in [one, two] + list(args)))
 assignment_unlimited_args.anything = "Expected assignment_unlimited_args __dict__"
 
+
 @register.assignment_tag
 def assignment_only_unlimited_args(*args):
     """Expected assignment_only_unlimited_args __doc__"""
     return "assignment_only_unlimited_args - Expected result: %s" % ', '.join(six.text_type(arg) for arg in args)
 assignment_only_unlimited_args.anything = "Expected assignment_only_unlimited_args __dict__"
 
+
 @register.assignment_tag
 def assignment_unlimited_args_kwargs(one, two='hi', *args, **kwargs):
     """Expected assignment_unlimited_args_kwargs __doc__"""
@@ -306,6 +354,7 @@ def assignment_unlimited_args_kwargs(one, two='hi', *args, **kwargs):
     )
 assignment_unlimited_args_kwargs.anything = "Expected assignment_unlimited_args_kwargs __dict__"
 
+
 @register.assignment_tag(takes_context=True)
 def assignment_tag_without_context_parameter(arg):
     """Expected assignment_tag_without_context_parameter __doc__"""
diff --git a/tests/template_tests/templatetags/subpackage/echo.py b/tests/template_tests/templatetags/subpackage/echo.py
index 0e4e862887..43cf107b3d 100644
--- a/tests/template_tests/templatetags/subpackage/echo.py
+++ b/tests/template_tests/templatetags/subpackage/echo.py
@@ -2,6 +2,7 @@ from django import template
 
 register = template.Library()
 
+
 @register.simple_tag
 def echo2(arg):
     return arg
diff --git a/tests/template_tests/test_callables.py b/tests/template_tests/test_callables.py
index d4e551e1df..9a47a5b96f 100644
--- a/tests/template_tests/test_callables.py
+++ b/tests/template_tests/test_callables.py
@@ -4,6 +4,7 @@ from unittest import TestCase
 
 from django import template
 
+
 class CallableVariablesTests(TestCase):
 
     def test_callable(self):
diff --git a/tests/template_tests/test_loaders.py b/tests/template_tests/test_loaders.py
index 1eef3942a6..57da0af56e 100644
--- a/tests/template_tests/test_loaders.py
+++ b/tests/template_tests/test_loaders.py
@@ -34,6 +34,7 @@ from django.utils.six import StringIO
 class MockLoader(object):
     pass
 
+
 def create_egg(name, resources):
     """
     Creates a mock egg with a list of resources.
@@ -105,7 +106,7 @@ class EggLoaderTest(TestCase):
 
 
 @override_settings(
-    TEMPLATE_LOADERS = (
+    TEMPLATE_LOADERS=(
         ('django.template.loaders.cached.Loader', (
             'django.template.loaders.filesystem.Loader',
         )),
@@ -139,7 +140,7 @@ class CachedLoader(TestCase):
 
 
 @override_settings(
-    TEMPLATE_DIRS = (
+    TEMPLATE_DIRS=(
         os.path.join(os.path.dirname(upath(__file__)), 'templates'),
     )
 )
@@ -160,13 +161,13 @@ class RenderToStringTest(TestCase):
 
     def test_empty_list(self):
         six.assertRaisesRegex(self, TemplateDoesNotExist,
-                                'No template names provided$',
-                                loader.render_to_string, [])
+            'No template names provided$',
+            loader.render_to_string, [])
 
     def test_select_templates_from_empty_list(self):
         six.assertRaisesRegex(self, TemplateDoesNotExist,
-                                'No template names provided$',
-                                loader.select_template, [])
+            'No template names provided$',
+            loader.select_template, [])
 
 
 class TemplateDirsOverrideTest(unittest.TestCase):
diff --git a/tests/template_tests/test_nodelist.py b/tests/template_tests/test_nodelist.py
index 755c0c3bea..12abd20331 100644
--- a/tests/template_tests/test_nodelist.py
+++ b/tests/template_tests/test_nodelist.py
@@ -4,6 +4,7 @@ from django.template import VariableNode, Context
 from django.template.loader import get_template_from_string
 from django.test.utils import override_settings
 
+
 class NodelistTest(TestCase):
 
     def test_for(self):
@@ -36,7 +37,7 @@ class ErrorIndexTest(TestCase):
     Checks whether index of error is calculated correctly in
     template debugger in for loops. Refs ticket #5831
     """
-    @override_settings(DEBUG=True, TEMPLATE_DEBUG = True)
+    @override_settings(DEBUG=True, TEMPLATE_DEBUG=True)
     def test_correct_exception_index(self):
         tests = [
             ('{% load bad_tag %}{% for i in range %}{% badsimpletag %}{% endfor %}', (38, 56)),
diff --git a/tests/template_tests/test_response.py b/tests/template_tests/test_response.py
index dc8ffd1a0a..f5f6158b2f 100644
--- a/tests/template_tests/test_response.py
+++ b/tests/template_tests/test_response.py
@@ -13,6 +13,7 @@ from django.template.response import (TemplateResponse, SimpleTemplateResponse,
 from django.test.utils import override_settings
 from django.utils._os import upath
 
+
 def test_processor(request):
     return {'processors': 'yes'}
 test_processor_name = 'template_tests.test_response.test_processor'
@@ -119,7 +120,7 @@ class SimpleTemplateResponseTest(TestCase):
         self.assertEqual(response.content, b'bar')
 
     def test_kwargs(self):
-        response = self._response(content_type = 'application/json', status=504)
+        response = self._response(content_type='application/json', status=504)
         self.assertEqual(response['content-type'], 'application/json')
         self.assertEqual(response.status_code, 504)
 
@@ -233,7 +234,7 @@ class TemplateResponseTest(TestCase):
         self.assertEqual(response.content, b'bar')
 
     def test_kwargs(self):
-        response = self._response(content_type = 'application/json',
+        response = self._response(content_type='application/json',
                                   status=504)
         self.assertEqual(response['content-type'], 'application/json')
         self.assertEqual(response.status_code, 504)
diff --git a/tests/template_tests/test_smartif.py b/tests/template_tests/test_smartif.py
index d23a023708..9115acef4e 100644
--- a/tests/template_tests/test_smartif.py
+++ b/tests/template_tests/test_smartif.py
@@ -2,6 +2,7 @@ import unittest
 
 from django.template.smartif import IfParser
 
+
 class SmartIfTests(unittest.TestCase):
 
     def assertCalcEqual(self, expected, tokens):
diff --git a/tests/template_tests/tests.py b/tests/template_tests/tests.py
index a39f952e4c..9ee845ec51 100644
--- a/tests/template_tests/tests.py
+++ b/tests/template_tests/tests.py
@@ -45,6 +45,7 @@ from . import filters
 
 register = template.Library()
 
+
 class EchoNode(template.Node):
     def __init__(self, contents):
         self.contents = contents
@@ -52,9 +53,11 @@ class EchoNode(template.Node):
     def render(self, context):
         return " ".join(self.contents)
 
+
 def do_echo(parser, token):
     return EchoNode(token.contents.split()[1:])
 
+
 def do_upper(value):
     return value.upper()
 
@@ -68,18 +71,23 @@ template.libraries['testtags'] = register
 # Helper objects for template tests #
 #####################################
 
+
 class SomeException(Exception):
     silent_variable_failure = True
 
+
 class SomeOtherException(Exception):
     pass
 
+
 class ContextStackException(Exception):
     pass
 
+
 class ShouldNotExecuteException(Exception):
     pass
 
+
 class SomeClass:
     def __init__(self):
         self.otherclass = OtherClass()
@@ -114,10 +122,12 @@ class SomeClass:
         raise SomeOtherException
     noisy_fail_attribute = property(noisy_fail_attribute)
 
+
 class OtherClass:
     def method(self):
         return "OtherClass.method"
 
+
 class TestObj(object):
     def is_true(self):
         return True
@@ -128,15 +138,18 @@ class TestObj(object):
     def is_bad(self):
         raise ShouldNotExecuteException()
 
+
 class SilentGetItemClass(object):
     def __getitem__(self, key):
         raise SomeException
 
+
 class SilentAttrClass(object):
     def b(self):
         raise SomeException
     b = property(b)
 
+
 @python_2_unicode_compatible
 class UTF8Class:
     "Class whose __str__ returns non-ASCII data on Python 2"
@@ -643,7 +656,7 @@ class TemplateTests(TransRealMixin, TestCase):
         settings.ALLOWED_INCLUDE_ROOTS = old_allowed_include_roots
 
         self.assertEqual(failures, [], "Tests failed:\n%s\n%s" %
-            ('-'*70, ("\n%s\n" % ('-'*70)).join(failures)))
+            ('-' * 70, ("\n%s\n" % ('-' * 70)).join(failures)))
 
     def render(self, test_template, vals):
         context = template.Context(vals[1])
@@ -1538,10 +1551,10 @@ class TemplateTests(TransRealMixin, TestCase):
                           '{% endfor %},'
                           '{% endfor %}',
                           {'data': [{'foo': 'c', 'bar': 1},
-                                     {'foo': 'd', 'bar': 1},
-                                     {'foo': 'a', 'bar': 2},
-                                     {'foo': 'b', 'bar': 2},
-                                     {'foo': 'x', 'bar': 3}]},
+                                    {'foo': 'd', 'bar': 1},
+                                    {'foo': 'a', 'bar': 2},
+                                    {'foo': 'b', 'bar': 2},
+                                    {'foo': 'x', 'bar': 3}]},
                           '1:cd,2:ab,3:x,'),
 
             # Test for silent failure when target variable isn't found
@@ -1582,13 +1595,13 @@ class TemplateTests(TransRealMixin, TestCase):
 
             # Test syntax
             'regroup05': ('{% regroup data by bar as %}', {},
-                           template.TemplateSyntaxError),
+                template.TemplateSyntaxError),
             'regroup06': ('{% regroup data by bar thisaintright grouped %}', {},
-                           template.TemplateSyntaxError),
+                template.TemplateSyntaxError),
             'regroup07': ('{% regroup data thisaintright bar as grouped %}', {},
-                           template.TemplateSyntaxError),
+                template.TemplateSyntaxError),
             'regroup08': ('{% regroup data by bar as grouped toomanyargs %}', {},
-                           template.TemplateSyntaxError),
+                template.TemplateSyntaxError),
 
             ### SSI TAG ########################################################
 
diff --git a/tests/template_tests/views.py b/tests/template_tests/views.py
index ed15893239..d031bdc2b6 100644
--- a/tests/template_tests/views.py
+++ b/tests/template_tests/views.py
@@ -6,17 +6,22 @@ from django.template.response import TemplateResponse
 def index(request):
     pass
 
+
 def client(request, id):
     pass
 
+
 def client_action(request, id, action):
     pass
 
+
 def client2(request, tag):
     pass
 
+
 def template_response_view(request):
     return TemplateResponse(request, 'response.html', {})
 
+
 def snark(request):
     return HttpResponse('Found him!')
diff --git a/tests/test_client/tests.py b/tests/test_client/tests.py
index cd59f50213..75801427d3 100644
--- a/tests/test_client/tests.py
+++ b/tests/test_client/tests.py
@@ -28,6 +28,7 @@ from django.test.utils import override_settings
 
 from .views import get_view
 
+
 @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
 class ClientTest(TestCase):
     fixtures = ['testdata.json']
@@ -479,7 +480,7 @@ class ClientTest(TestCase):
 
 
 @override_settings(
-    MIDDLEWARE_CLASSES = ('django.middleware.csrf.CsrfViewMiddleware',)
+    MIDDLEWARE_CLASSES=('django.middleware.csrf.CsrfViewMiddleware',)
 )
 class CSRFEnabledClientTests(TestCase):
     def test_csrf_enabled_client(self):
@@ -498,6 +499,7 @@ class CSRFEnabledClientTests(TestCase):
 class CustomTestClient(Client):
     i_am_customized = "Yes"
 
+
 class CustomTestClientTest(TestCase):
     client_class = CustomTestClient
 
diff --git a/tests/test_client/views.py b/tests/test_client/views.py
index 85aefd47bb..53d008d5b1 100644
--- a/tests/test_client/views.py
+++ b/tests/test_client/views.py
@@ -11,6 +11,7 @@ from django.template import Context, Template
 from django.utils.decorators import method_decorator
 from django.utils.six.moves.urllib.parse import urlencode
 
+
 def get_view(request):
     "A simple view that expects a GET request, and returns a rendered template"
     t = Template('This is a test. {{ var }} is the value.', name='GET Template')
@@ -18,6 +19,7 @@ def get_view(request):
 
     return HttpResponse(t.render(c))
 
+
 def post_view(request):
     """A view that expects a POST, and returns a different template depending
     on whether any POST data is available
@@ -35,12 +37,14 @@ def post_view(request):
 
     return HttpResponse(t.render(c))
 
+
 def view_with_header(request):
     "A view that has a custom header"
     response = HttpResponse()
     response['X-DJANGO-TEST'] = 'Slartibartfast'
     return response
 
+
 def raw_post_view(request):
     """A view which expects raw XML to be posted and returns content extracted
     from the XML"""
@@ -56,6 +60,7 @@ def raw_post_view(request):
 
     return HttpResponse(t.render(c))
 
+
 def redirect_view(request):
     "A view that redirects all requests to the GET view"
     if request.GET:
@@ -64,6 +69,7 @@ def redirect_view(request):
         query = ''
     return HttpResponseRedirect('/test_client/get_view/' + query)
 
+
 def view_with_secure(request):
     "A view that indicates if the request was secure"
     response = HttpResponse()
@@ -71,10 +77,12 @@ def view_with_secure(request):
     response.test_server_port = request.META.get('SERVER_PORT', 80)
     return response
 
+
 def double_redirect_view(request):
     "A view that redirects all requests to a redirection view"
     return HttpResponseRedirect('/test_client/permanent_redirect_view/')
 
+
 def bad_view(request):
     "A view that returns a 404 with some error content"
     return HttpResponseNotFound('Not found!. This page contains some MAGIC content')
@@ -87,6 +95,7 @@ TestChoices = (
     ('e', 'Fifth Choice')
 )
 
+
 class TestForm(Form):
     text = fields.CharField()
     email = fields.EmailField()
@@ -100,6 +109,7 @@ class TestForm(Form):
             raise ValidationError("Non-field error.")
         return cleaned_data
 
+
 def form_view(request):
     "A view that tests a simple form"
     if request.method == 'POST':
@@ -117,6 +127,7 @@ def form_view(request):
 
     return HttpResponse(t.render(c))
 
+
 def form_view_with_template(request):
     "A view that tests a simple form"
     if request.method == 'POST':
@@ -135,6 +146,7 @@ def form_view_with_template(request):
         }
     )
 
+
 class BaseTestFormSet(BaseFormSet):
     def clean(self):
         """Checks that no two email addresses are the same."""
@@ -154,6 +166,7 @@ class BaseTestFormSet(BaseFormSet):
 
 TestFormSet = formset_factory(TestForm, BaseTestFormSet)
 
+
 def formset_view(request):
     "A view that tests a simple formset"
     if request.method == 'POST':
@@ -172,6 +185,7 @@ def formset_view(request):
         c = Context({'my_formset': formset})
     return HttpResponse(t.render(c))
 
+
 def login_protected_view(request):
     "A simple view that is login protected."
     t = Template('This is a login protected test. Username is {{ user.username }}.', name='Login Template')
@@ -180,6 +194,7 @@ def login_protected_view(request):
     return HttpResponse(t.render(c))
 login_protected_view = login_required(login_protected_view)
 
+
 def login_protected_view_changed_redirect(request):
     "A simple view that is login protected with a custom redirect field set"
     t = Template('This is a login protected test. Username is {{ user.username }}.', name='Login Template')
@@ -188,6 +203,7 @@ def login_protected_view_changed_redirect(request):
     return HttpResponse(t.render(c))
 login_protected_view_changed_redirect = login_required(redirect_field_name="redirect_to")(login_protected_view_changed_redirect)
 
+
 def _permission_protected_view(request):
     "A simple view that is permission protected."
     t = Template('This is a permission protected test. '
@@ -199,6 +215,7 @@ def _permission_protected_view(request):
 permission_protected_view = permission_required('permission_not_granted')(_permission_protected_view)
 permission_protected_view_exception = permission_required('permission_not_granted', raise_exception=True)(_permission_protected_view)
 
+
 class _ViewManager(object):
     @method_decorator(login_required)
     def login_protected_view(self, request):
@@ -221,6 +238,7 @@ _view_manager = _ViewManager()
 login_protected_method_view = _view_manager.login_protected_view
 permission_protected_method_view = _view_manager.permission_protected_view
 
+
 def session_view(request):
     "A view that modifies the session"
     request.session['tobacconist'] = 'hovercraft'
@@ -230,10 +248,12 @@ def session_view(request):
     c = Context()
     return HttpResponse(t.render(c))
 
+
 def broken_view(request):
     """A view which just raises an exception, simulating a broken view."""
     raise KeyError("Oops! Looks like you wrote some bad code.")
 
+
 def mail_sending_view(request):
     mail.EmailMessage(
         "Test message",
@@ -242,6 +262,7 @@ def mail_sending_view(request):
         ['first@example.com', 'second@example.com']).send()
     return HttpResponse("Mail sent")
 
+
 def mass_mail_sending_view(request):
     m1 = mail.EmailMessage(
         'First Test message',
@@ -259,5 +280,6 @@ def mass_mail_sending_view(request):
 
     return HttpResponse("Mail sent")
 
+
 def django_project_redirect(request):
     return HttpResponseRedirect('https://www.djangoproject.com/')
diff --git a/tests/test_client_regress/session.py b/tests/test_client_regress/session.py
index 665729cf00..47c192718b 100644
--- a/tests/test_client_regress/session.py
+++ b/tests/test_client_regress/session.py
@@ -1,5 +1,6 @@
 from django.contrib.sessions.backends.base import SessionBase
 
+
 class SessionStore(SessionBase):
     """
     A simple cookie-based session storage implementation.
diff --git a/tests/test_client_regress/tests.py b/tests/test_client_regress/tests.py
index 8a371cb52b..83d6a0097e 100644
--- a/tests/test_client_regress/tests.py
+++ b/tests/test_client_regress/tests.py
@@ -23,6 +23,7 @@ from django.contrib.auth.models import User
 from .models import CustomUser
 from .views import CustomTestException
 
+
 @override_settings(
     TEMPLATE_DIRS=(os.path.join(os.path.dirname(upath(__file__)), 'templates'),)
 )
@@ -185,6 +186,7 @@ class AssertContainsTests(TestCase):
         response = HttpResponse('Hello')
         self.assertNotContains(response, 'Bye')
 
+
 @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
 class AssertTemplateUsedTests(TestCase):
     fixtures = ['testdata.json']
@@ -256,6 +258,7 @@ class AssertTemplateUsedTests(TestCase):
         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):
     def test_redirect_page(self):
         "An assertion is raised if the original page couldn't be retrieved as expected"
@@ -545,6 +548,7 @@ class AssertFormErrorTests(TestCase):
         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 AssertFormsetErrorTests(TestCase):
     msg_prefixes = [("", {}), ("abc: ", {"msg_prefix": "abc"})]
 
@@ -737,6 +741,7 @@ class AssertFormsetErrorTests(TestCase):
                                     'addresses.',
                                     **kwargs)
 
+
 @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
 class LoginTests(TestCase):
     fixtures = ['testdata']
@@ -801,6 +806,7 @@ class URLEscapingTests(TestCase):
         self.assertEqual(response.status_code, 200)
         self.assertEqual(response.content, b'Hi, Arthur')
 
+
 @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
 class ExceptionTests(TestCase):
     fixtures = ['testdata.json']
@@ -846,6 +852,7 @@ class TemplateExceptionTests(TestCase):
         except TemplateSyntaxError:
             pass
 
+
 # We need two different tests to check URLconf substitution -  one to check
 # it was changed, and another one (without self.urls) to check it was reverted on
 # teardown. This pair of tests relies upon the alphabetical ordering of test execution.
@@ -857,6 +864,7 @@ class UrlconfSubstitutionTests(TestCase):
         url = reverse('arg_view', args=['somename'])
         self.assertEqual(url, '/arg_view/somename/')
 
+
 # This test needs to run *after* UrlconfSubstitutionTests; the zz prefix in the
 # name is to ensure alphabetical ordering.
 class zzUrlconfSubstitutionTests(TestCase):
@@ -865,6 +873,7 @@ class zzUrlconfSubstitutionTests(TestCase):
         url = reverse('arg_view', args=['somename'])
         self.assertEqual(url, '/test_client_regress/arg_view/somename/')
 
+
 @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
 class ContextTests(TestCase):
     fixtures = ['testdata']
@@ -1114,6 +1123,7 @@ class RequestMethodStringDataTests(TestCase):
         self.assertEqual(response.status_code, 200)
         self.assertEqual(response.content, b'request method: PATCH')
 
+
 class QueryStringTests(TestCase):
     def test_get_like_requests(self):
         # See: https://code.djangoproject.com/ticket/10571.
@@ -1166,6 +1176,7 @@ class QueryStringTests(TestCase):
         self.assertEqual(response.context['request-foo'], 'whiz')
         self.assertEqual(response.context['request-bar'], 'bang')
 
+
 class UnicodePayloadTests(TestCase):
     def test_simple_unicode_payload(self):
         "A simple ASCII-only unicode JSON document can be POSTed"
@@ -1199,6 +1210,7 @@ class UnicodePayloadTests(TestCase):
                                     content_type="application/json; charset=koi8-r")
         self.assertEqual(response.content, json.encode('koi8-r'))
 
+
 class DummyFile(object):
     def __init__(self, filename):
         self.name = filename
@@ -1206,6 +1218,7 @@ class DummyFile(object):
     def read(self):
         return b'TEST_FILE_CONTENT'
 
+
 class UploadedFileEncodingTest(TestCase):
     def test_file_encoding(self):
         encoded_file = encode_file('TEST_BOUNDARY', 'TEST_KEY', DummyFile('test_name.bin'))
@@ -1226,6 +1239,7 @@ class UploadedFileEncodingTest(TestCase):
         self.assertEqual(b'Content-Type: application/octet-stream',
                          encode_file('IGNORE', 'IGNORE', DummyFile("file.unknown"))[2])
 
+
 class RequestHeadersTest(TestCase):
     def test_client_headers(self):
         "A test client can receive custom headers"
@@ -1268,17 +1282,19 @@ class ReadLimitedStreamTest(TestCase):
         """HttpRequest.read() on a test client PUT request with some payload
         should return that payload."""
         payload = b'foobar'
-        self.assertEqual(self.client.put("/test_client_regress/read_all/",
-                                          data=payload,
-                                          content_type='text/plain').content, payload)
+        self.assertEqual(self.client.put(
+            "/test_client_regress/read_all/",
+            data=payload,
+            content_type='text/plain').content, payload)
 
     def test_read_numbytes_from_nonempty_request(self):
         """HttpRequest.read(LARGE_BUFFER) on a test client PUT request with
         some payload should return that payload."""
         payload = b'foobar'
-        self.assertEqual(self.client.put("/test_client_regress/read_buffer/",
-                                          data=payload,
-                                          content_type='text/plain').content, payload)
+        self.assertEqual(
+            self.client.put("/test_client_regress/read_buffer/",
+            data=payload,
+            content_type='text/plain').content, payload)
 
 
 class RequestFactoryStateTest(TestCase):
diff --git a/tests/test_client_regress/views.py b/tests/test_client_regress/views.py
index d4bbd55b6f..2fbbce0c43 100644
--- a/tests/test_client_regress/views.py
+++ b/tests/test_client_regress/views.py
@@ -15,10 +15,12 @@ from django.test.utils import setup_test_environment
 class CustomTestException(Exception):
     pass
 
+
 def no_template_view(request):
     "A simple view that expects a GET request, and returns a rendered template"
     return HttpResponse("No template used. Sample content: twice once twice. Content ends.")
 
+
 def staff_only_view(request):
     "A view that can only be visited by staff. Non staff members get an exception"
     if request.user.is_staff:
@@ -26,11 +28,13 @@ def staff_only_view(request):
     else:
         raise CustomTestException()
 
+
 def get_view(request):
     "A simple login protected view"
     return HttpResponse("Hello world")
 get_view = login_required(get_view)
 
+
 def request_data(request, template='base.html', data='sausage'):
     "A simple view that returns the request data in the context"
 
@@ -50,6 +54,7 @@ def request_data(request, template='base.html', data='sausage'):
         'data': data,
     })
 
+
 def view_with_argument(request, name):
     """A view that takes a string argument
 
@@ -62,6 +67,7 @@ def view_with_argument(request, name):
     else:
         return HttpResponse('Howdy, %s' % name)
 
+
 def nested_view(request):
     """
     A view that uses test client to call another view.
@@ -71,32 +77,39 @@ def nested_view(request):
     c.get("/test_client_regress/no_template_view")
     return render_to_response('base.html', {'nested': 'yes'})
 
+
 def login_protected_redirect_view(request):
     "A view that redirects all requests to the GET view"
     return HttpResponseRedirect('/test_client_regress/get_view/')
 login_protected_redirect_view = login_required(login_protected_redirect_view)
 
+
 def set_session_view(request):
     "A view that sets a session variable"
     request.session['session_var'] = 'YES'
     return HttpResponse('set_session')
 
+
 def check_session_view(request):
     "A view that reads a session variable"
     return HttpResponse(request.session.get('session_var', 'NO'))
 
+
 def request_methods_view(request):
     "A view that responds with the request method"
     return HttpResponse('request method: %s' % request.method)
 
+
 def return_unicode(request):
     return render_to_response('unicode.html')
 
+
 def return_undecodable_binary(request):
     return HttpResponse(
         b'%PDF-1.4\r\n%\x93\x8c\x8b\x9e ReportLab Generated PDF document http://www.reportlab.com'
     )
 
+
 def return_json_file(request):
     "A view that parses and returns a JSON string as a file."
     match = CONTENT_TYPE_RE.match(request.META['CONTENT_TYPE'])
@@ -113,22 +126,27 @@ def return_json_file(request):
     response['Content-Disposition'] = 'attachment; filename=testfile.json'
     return response
 
+
 def check_headers(request):
     "A view that responds with value of the X-ARG-CHECK header"
     return HttpResponse('HTTP_X_ARG_CHECK: %s' % request.META.get('HTTP_X_ARG_CHECK', 'Undefined'))
 
+
 def body(request):
     "A view that is requested with GET and accesses request.body. Refs #14753."
     return HttpResponse(request.body)
 
+
 def read_all(request):
     "A view that is requested with accesses request.read()."
     return HttpResponse(request.read())
 
+
 def read_buffer(request):
     "A view that is requested with accesses request.read(LARGE_BUFFER)."
     return HttpResponse(request.read(99999))
 
+
 def request_context_view(request):
     # Special attribute that won't be present on a plain HttpRequest
     request.special_path = request.path
diff --git a/tests/test_runner/models.py b/tests/test_runner/models.py
index 9a072e627c..20cb384b03 100644
--- a/tests/test_runner/models.py
+++ b/tests/test_runner/models.py
@@ -1,5 +1,6 @@
 from django.db import models
 
+
 class Person(models.Model):
     first_name = models.CharField(max_length=20)
     last_name = models.CharField(max_length=20)
diff --git a/tests/test_runner_deprecation_app/tests.py b/tests/test_runner_deprecation_app/tests.py
index 24d716f2bb..0d947c35c2 100644
--- a/tests/test_runner_deprecation_app/tests.py
+++ b/tests/test_runner_deprecation_app/tests.py
@@ -4,6 +4,7 @@ from django.test import TestCase
 
 warnings.warn("module-level warning from deprecation_app", DeprecationWarning)
 
+
 class DummyTest(TestCase):
     def test_warn(self):
         warnings.warn("warning from test", DeprecationWarning)
diff --git a/tests/test_utils/models.py b/tests/test_utils/models.py
index 85a1031c02..4c6ee0d19a 100644
--- a/tests/test_utils/models.py
+++ b/tests/test_utils/models.py
@@ -1,6 +1,7 @@
 from django.db import models
 from django.utils.encoding import python_2_unicode_compatible
 
+
 @python_2_unicode_compatible
 class Person(models.Model):
     name = models.CharField(max_length=100)
diff --git a/tests/timezones/admin.py b/tests/timezones/admin.py
index 81b49a4ab6..bd6c4e10c8 100644
--- a/tests/timezones/admin.py
+++ b/tests/timezones/admin.py
@@ -2,11 +2,13 @@ from django.contrib import admin
 
 from .models import Event, Timestamp
 
+
 class EventAdmin(admin.ModelAdmin):
     list_display = ('dt',)
 
 admin.site.register(Event, EventAdmin)
 
+
 class TimestampAdmin(admin.ModelAdmin):
     readonly_fields = ('created', 'updated')
 
diff --git a/tests/timezones/forms.py b/tests/timezones/forms.py
index d99c9b77d5..b92562396e 100644
--- a/tests/timezones/forms.py
+++ b/tests/timezones/forms.py
@@ -2,20 +2,25 @@ from django import forms
 
 from .models import Event
 
+
 class EventForm(forms.Form):
     dt = forms.DateTimeField()
 
+
 class EventSplitForm(forms.Form):
     dt = forms.SplitDateTimeField()
 
+
 class EventLocalizedForm(forms.Form):
     dt = forms.DateTimeField(localize=True)
 
+
 class EventModelForm(forms.ModelForm):
     class Meta:
         model = Event
         fields = '__all__'
 
+
 class EventLocalizedModelForm(forms.ModelForm):
     class Meta:
         model = Event
diff --git a/tests/timezones/models.py b/tests/timezones/models.py
index c49e42f887..73b198f32c 100644
--- a/tests/timezones/models.py
+++ b/tests/timezones/models.py
@@ -1,21 +1,27 @@
 from django.db import models
 
+
 class Event(models.Model):
     dt = models.DateTimeField()
 
+
 class MaybeEvent(models.Model):
     dt = models.DateTimeField(blank=True, null=True)
 
+
 class Session(models.Model):
     name = models.CharField(max_length=20)
 
+
 class SessionEvent(models.Model):
     dt = models.DateTimeField()
     session = models.ForeignKey(Session, related_name='events')
 
+
 class Timestamp(models.Model):
     created = models.DateTimeField(auto_now_add=True)
     updated = models.DateTimeField(auto_now=True)
 
+
 class AllDayEvent(models.Model):
     day = models.DateField()
diff --git a/tests/transactions/tests.py b/tests/transactions/tests.py
index 8c0c535d31..5c38bc8ef2 100644
--- a/tests/transactions/tests.py
+++ b/tests/transactions/tests.py
@@ -395,7 +395,8 @@ class TransactionTests(IgnoreDeprecationWarningsMixin, TransactionTestCase):
         """
         The default behavior is to autocommit after each save() action.
         """
-        self.assertRaises(Exception,
+        self.assertRaises(
+            Exception,
             self.create_a_reporter_then_fail,
             "Alice", "Smith"
         )
@@ -411,7 +412,8 @@ class TransactionTests(IgnoreDeprecationWarningsMixin, TransactionTestCase):
         autocomitted_create_then_fail = transaction.autocommit(
             self.create_a_reporter_then_fail
         )
-        self.assertRaises(Exception,
+        self.assertRaises(
+            Exception,
             autocomitted_create_then_fail,
             "Alice", "Smith"
         )
@@ -426,7 +428,8 @@ class TransactionTests(IgnoreDeprecationWarningsMixin, TransactionTestCase):
         autocomitted_create_then_fail = transaction.autocommit(using='default')(
             self.create_a_reporter_then_fail
         )
-        self.assertRaises(Exception,
+        self.assertRaises(
+            Exception,
             autocomitted_create_then_fail,
             "Alice", "Smith"
         )
@@ -453,7 +456,8 @@ class TransactionTests(IgnoreDeprecationWarningsMixin, TransactionTestCase):
         using_committed_on_success = transaction.commit_on_success(using='default')(
             self.create_a_reporter_then_fail
         )
-        self.assertRaises(Exception,
+        self.assertRaises(
+            Exception,
             using_committed_on_success,
             "Dirk", "Gently"
         )
@@ -519,7 +523,8 @@ class TransactionTests(IgnoreDeprecationWarningsMixin, TransactionTestCase):
         using_manually_managed_mistake = transaction.commit_manually(using='default')(
             self.manually_managed_mistake
         )
-        self.assertRaises(transaction.TransactionManagementError,
+        self.assertRaises(
+            transaction.TransactionManagementError,
             using_manually_managed_mistake
         )
 
@@ -544,6 +549,7 @@ class TransactionRollbackTests(IgnoreDeprecationWarningsMixin, TransactionTestCa
         self.assertRaises(IntegrityError, execute_bad_sql)
         transaction.rollback()
 
+
 class TransactionContextManagerTests(IgnoreDeprecationWarningsMixin, TransactionTestCase):
 
     available_apps = ['transactions']
diff --git a/tests/transactions_regress/models.py b/tests/transactions_regress/models.py
index e09e81d93d..32234d9ba4 100644
--- a/tests/transactions_regress/models.py
+++ b/tests/transactions_regress/models.py
@@ -4,9 +4,11 @@ from django.db import models
 class Mod(models.Model):
     fld = models.IntegerField()
 
+
 class SubMod(Mod):
     cnt = models.IntegerField(unique=True)
 
+
 class M2mA(models.Model):
     others = models.ManyToManyField('M2mB')
 
diff --git a/tests/transactions_regress/tests.py b/tests/transactions_regress/tests.py
index a67d36e4eb..24bd860731 100644
--- a/tests/transactions_regress/tests.py
+++ b/tests/transactions_regress/tests.py
@@ -10,6 +10,7 @@ from django.test.utils import override_settings, IgnoreDeprecationWarningsMixin
 
 from .models import Mod, M2mA, M2mB, SubMod
 
+
 class ModelInheritanceTests(TransactionTestCase):
 
     available_apps = ['transactions_regress']
@@ -31,6 +32,7 @@ class ModelInheritanceTests(TransactionTestCase):
         self.assertEqual(SubMod.objects.count(), 1)
         self.assertEqual(Mod.objects.count(), 1)
 
+
 class TestTransactionClosing(IgnoreDeprecationWarningsMixin, TransactionTestCase):
     """
     Tests to make sure that transactions are properly closed
@@ -191,6 +193,7 @@ class TestTransactionClosing(IgnoreDeprecationWarningsMixin, TransactionTestCase
         """
         self.test_failing_query_transaction_closed()
 
+
 @skipIf(connection.vendor == 'sqlite'
         and connection.settings_dict['TEST_NAME'] in (None, '', ':memory:'),
         "Cannot establish two connections to an in-memory SQLite database.")
@@ -372,7 +375,7 @@ class SavepointTest(IgnoreDeprecationWarningsMixin, TransactionTestCase):
         # _mysql_storage_engine issues a query and as such can't be applied in
         # a skipIf decorator since that would execute the query on module load.
         if (connection.vendor == 'mysql' and
-            connection.features._mysql_storage_engine == 'MyISAM'):
+                connection.features._mysql_storage_engine == 'MyISAM'):
             raise SkipTest("MyISAM MySQL storage engine doesn't support savepoints")
 
         @commit_manually
diff --git a/tests/unmanaged_models/models.py b/tests/unmanaged_models/models.py
index 0eef69977c..b0dd5c8719 100644
--- a/tests/unmanaged_models/models.py
+++ b/tests/unmanaged_models/models.py
@@ -8,6 +8,7 @@ from django.utils.encoding import python_2_unicode_compatible
 
 #  All of these models are created in the database by Django.
 
+
 @python_2_unicode_compatible
 class A01(models.Model):
     f_a = models.CharField(max_length=10, db_index=True)
@@ -19,6 +20,7 @@ class A01(models.Model):
     def __str__(self):
         return self.f_a
 
+
 @python_2_unicode_compatible
 class B01(models.Model):
     fk_a = models.ForeignKey(A01)
@@ -33,6 +35,7 @@ class B01(models.Model):
     def __str__(self):
         return self.f_a
 
+
 @python_2_unicode_compatible
 class C01(models.Model):
     mm_a = models.ManyToManyField(A01, db_table='d01')
@@ -49,6 +52,7 @@ class C01(models.Model):
 # of possibly a subset of the columns). There should be no creation errors,
 # since we have told Django they aren't managed by Django.
 
+
 @python_2_unicode_compatible
 class A02(models.Model):
     f_a = models.CharField(max_length=10, db_index=True)
@@ -60,6 +64,7 @@ class A02(models.Model):
     def __str__(self):
         return self.f_a
 
+
 @python_2_unicode_compatible
 class B02(models.Model):
     class Meta:
@@ -73,6 +78,7 @@ class B02(models.Model):
     def __str__(self):
         return self.f_a
 
+
 # To re-use the many-to-many intermediate table, we need to manually set up
 # things up.
 @python_2_unicode_compatible
@@ -88,6 +94,7 @@ class C02(models.Model):
     def __str__(self):
         return self.f_a
 
+
 class Intermediate(models.Model):
     a02 = models.ForeignKey(A02, db_column="a01_id")
     c02 = models.ForeignKey(C02, db_column="c01_id")
@@ -96,7 +103,7 @@ class Intermediate(models.Model):
         db_table = 'd01'
         managed = False
 
-#
+
 # These next models test the creation (or not) of many to many join tables
 # between managed and unmanaged models. A join table between two unmanaged
 # models shouldn't be automatically created (see #10647).
@@ -109,15 +116,18 @@ class Proxy1(models.Model):
     class Meta:
         db_table = "unmanaged_models_proxy1"
 
+
 class Proxy2(models.Model):
     class Meta:
         db_table = "unmanaged_models_proxy2"
 
+
 class Unmanaged1(models.Model):
     class Meta:
         managed = False
         db_table = "unmanaged_models_proxy1"
 
+
 # Unmanged with an m2m to unmanaged: the intermediary table won't be created.
 class Unmanaged2(models.Model):
     mm = models.ManyToManyField(Unmanaged1)
@@ -126,6 +136,7 @@ class Unmanaged2(models.Model):
         managed = False
         db_table = "unmanaged_models_proxy2"
 
+
 # Here's an unmanaged model with an m2m to a managed one; the intermediary
 # table *will* be created (unless given a custom `through` as for C02 above).
 class Managed1(models.Model):
diff --git a/tests/update/models.py b/tests/update/models.py
index 08472d98b1..ebc9c3353c 100644
--- a/tests/update/models.py
+++ b/tests/update/models.py
@@ -17,6 +17,7 @@ class DataPoint(models.Model):
     def __str__(self):
         return six.text_type(self.name)
 
+
 @python_2_unicode_compatible
 class RelatedPoint(models.Model):
     name = models.CharField(max_length=20)
@@ -29,12 +30,15 @@ class RelatedPoint(models.Model):
 class A(models.Model):
     x = models.IntegerField(default=10)
 
+
 class B(models.Model):
     a = models.ForeignKey(A)
     y = models.IntegerField(default=10)
 
+
 class C(models.Model):
     y = models.IntegerField(default=10)
 
+
 class D(C):
     a = models.ForeignKey(A)
diff --git a/tests/update_only_fields/models.py b/tests/update_only_fields/models.py
index bf5dd99166..ea319834c0 100644
--- a/tests/update_only_fields/models.py
+++ b/tests/update_only_fields/models.py
@@ -7,6 +7,7 @@ GENDER_CHOICES = (
     ('F', 'Female'),
 )
 
+
 class Account(models.Model):
     num = models.IntegerField()
 
diff --git a/tests/urlpatterns_reverse/erroneous_views_module.py b/tests/urlpatterns_reverse/erroneous_views_module.py
index 52b9bc5163..3f7f5b2ac7 100644
--- a/tests/urlpatterns_reverse/erroneous_views_module.py
+++ b/tests/urlpatterns_reverse/erroneous_views_module.py
@@ -1,4 +1,5 @@
 import non_existent  # NOQA
 
+
 def erroneous_view(request):
     pass
diff --git a/tests/urlpatterns_reverse/middleware.py b/tests/urlpatterns_reverse/middleware.py
index 0de692835f..cc80f14145 100644
--- a/tests/urlpatterns_reverse/middleware.py
+++ b/tests/urlpatterns_reverse/middleware.py
@@ -8,24 +8,29 @@ class ChangeURLconfMiddleware(object):
     def process_request(self, request):
         request.urlconf = urlconf_inner.__name__
 
+
 class NullChangeURLconfMiddleware(object):
     def process_request(self, request):
         request.urlconf = None
 
+
 class ReverseInnerInResponseMiddleware(object):
     def process_response(self, *args, **kwargs):
         return HttpResponse(reverse('inner'))
 
+
 class ReverseOuterInResponseMiddleware(object):
     def process_response(self, *args, **kwargs):
         return HttpResponse(reverse('outer'))
 
+
 class ReverseInnerInStreaming(object):
     def process_view(self, *args, **kwargs):
         def stream():
             yield reverse('inner')
         return StreamingHttpResponse(stream())
 
+
 class ReverseOuterInStreaming(object):
     def process_view(self, *args, **kwargs):
         def stream():
diff --git a/tests/urlpatterns_reverse/tests.py b/tests/urlpatterns_reverse/tests.py
index 4134057b23..b2a6d83443 100644
--- a/tests/urlpatterns_reverse/tests.py
+++ b/tests/urlpatterns_reverse/tests.py
@@ -148,6 +148,7 @@ test_data = (
     ('defaults', NoReverseMatch, [], {'arg2': 1}),
 )
 
+
 class NoURLPatternsTests(TestCase):
     urls = 'urlpatterns_reverse.no_urls'
 
@@ -161,6 +162,7 @@ class NoURLPatternsTests(TestCase):
             "The included urlconf urlpatterns_reverse.no_urls "
             "doesn't have any patterns in it", getattr, resolver, 'url_patterns')
 
+
 class URLPatternReverse(TestCase):
     urls = 'urlpatterns_reverse.urls'
 
@@ -282,6 +284,7 @@ class ResolverTests(unittest.TestCase):
                         else:
                             self.assertEqual(t.name, e['name'], 'Wrong URL name.  Expected "%s", got "%s".' % (e['name'], t.name))
 
+
 class ReverseLazyTest(TestCase):
     urls = 'urlpatterns_reverse.reverse_lazy_urls'
 
@@ -297,6 +300,7 @@ class ReverseLazyTest(TestCase):
         response = self.client.get('/login_required_view/')
         self.assertEqual(response.status_code, 200)
 
+
 class ReverseShortcutTests(TestCase):
     urls = 'urlpatterns_reverse.urls'
 
@@ -454,7 +458,7 @@ class NamespaceTests(TestCase):
         self.assertEqual('/inc78/extra/foobar/', reverse('inc-ns5:inner-extra', args=['78', 'foobar']))
 
 
-@override_settings(ROOT_URLCONF = urlconf_outer.__name__)
+@override_settings(ROOT_URLCONF=urlconf_outer.__name__)
 class RequestURLconfTests(TestCase):
     def test_urlconf(self):
         response = self.client.get('/test/me/')
@@ -549,6 +553,7 @@ class RequestURLconfTests(TestCase):
             self.client.get('/second_test/')
             b''.join(self.client.get('/second_test/'))
 
+
 class ErrorHandlerResolutionTests(TestCase):
     """Tests for handler400, handler404 and handler500"""
 
@@ -573,6 +578,7 @@ class ErrorHandlerResolutionTests(TestCase):
         self.assertEqual(self.callable_resolver.resolve404(), handler)
         self.assertEqual(self.callable_resolver.resolve500(), handler)
 
+
 class DefaultErrorHandlerTests(TestCase):
     urls = 'urlpatterns_reverse.urls_without_full_import'
 
@@ -589,6 +595,7 @@ class DefaultErrorHandlerTests(TestCase):
         except AttributeError:
             self.fail("Shouldn't get an AttributeError due to undefined 500 handler")
 
+
 class NoRootUrlConfTests(TestCase):
     """Tests for handler404 and handler500 if urlconf is None"""
     urls = None
@@ -596,6 +603,7 @@ class NoRootUrlConfTests(TestCase):
     def test_no_handler_exception(self):
         self.assertRaises(ImproperlyConfigured, self.client.get, '/test/me/')
 
+
 class ResolverMatchTests(TestCase):
     urls = 'urlpatterns_reverse.namespace_urls'
 
@@ -631,6 +639,7 @@ class ResolverMatchTests(TestCase):
         request = HttpRequest()
         self.assertIsNone(request.resolver_match)
 
+
 class ErroneousViewTests(TestCase):
     urls = 'urlpatterns_reverse.erroneous_urls'
 
@@ -650,6 +659,7 @@ class ErroneousViewTests(TestCase):
         # The regex error will be hit before NoReverseMatch can be raised
         self.assertRaises(ImproperlyConfigured, reverse, 'whatever blah blah')
 
+
 class ViewLoadingTests(TestCase):
     def test_view_loading(self):
         # A missing view (identified by an AttributeError) should raise
diff --git a/tests/urlpatterns_reverse/urlconf_inner.py b/tests/urlpatterns_reverse/urlconf_inner.py
index 6d9d2346f7..6d5cd27b35 100644
--- a/tests/urlpatterns_reverse/urlconf_inner.py
+++ b/tests/urlpatterns_reverse/urlconf_inner.py
@@ -2,6 +2,7 @@ from django.conf.urls import patterns, url
 from django.template import Template, Context
 from django.http import HttpResponse
 
+
 def inner_view(request):
     content = Template('{% url "outer" as outer_url %}outer:{{ outer_url }},'
                        '{% url "inner" as inner_url %}inner:{{ inner_url }}').render(Context())
diff --git a/tests/urlpatterns_reverse/views.py b/tests/urlpatterns_reverse/views.py
index 6bb8849472..f23b4bf257 100644
--- a/tests/urlpatterns_reverse/views.py
+++ b/tests/urlpatterns_reverse/views.py
@@ -4,21 +4,27 @@ from django.core.urlresolvers import reverse_lazy
 
 from django.contrib.auth.decorators import user_passes_test
 
+
 def empty_view(request, *args, **kwargs):
     return HttpResponse('')
 
+
 def kwargs_view(request, arg1=1, arg2=2):
     return HttpResponse('')
 
+
 def absolute_kwargs_view(request, arg1=1, arg2=2):
     return HttpResponse('')
 
+
 def defaults_view(request, arg1, arg2):
     pass
 
+
 def erroneous_view(request):
     import non_existent  # NOQA
 
+
 def pass_resolver_match_view(request, *args, **kwargs):
     response = HttpResponse('')
     response.resolver_match = request.resolver_match
@@ -26,18 +32,22 @@ def pass_resolver_match_view(request, *args, **kwargs):
 
 uncallable = "Can I be a view? Pleeeease?"
 
+
 class ViewClass(object):
     def __call__(self, request, *args, **kwargs):
         return HttpResponse('')
 
 view_class_instance = ViewClass()
 
+
 class LazyRedirectView(RedirectView):
     url = reverse_lazy('named-lazy-url-redirected-to')
 
+
 @user_passes_test(lambda u: u.is_authenticated(), login_url=reverse_lazy('some-login-page'))
 def login_required_view(request):
     return HttpResponse('Hello you')
 
+
 def bad_view(request, *args, **kwargs):
     raise ValueError("I don't think I'm getting good value for this view")
diff --git a/tests/user_commands/management/commands/leave_locale_alone_false.py b/tests/user_commands/management/commands/leave_locale_alone_false.py
index 8ebb607d5a..e03ad1cab0 100644
--- a/tests/user_commands/management/commands/leave_locale_alone_false.py
+++ b/tests/user_commands/management/commands/leave_locale_alone_false.py
@@ -1,6 +1,7 @@
 from django.core.management.base import BaseCommand
 from django.utils import translation
 
+
 class Command(BaseCommand):
 
     can_import_settings = True
diff --git a/tests/user_commands/management/commands/leave_locale_alone_true.py b/tests/user_commands/management/commands/leave_locale_alone_true.py
index e0f923591e..9861221e39 100644
--- a/tests/user_commands/management/commands/leave_locale_alone_true.py
+++ b/tests/user_commands/management/commands/leave_locale_alone_true.py
@@ -1,6 +1,7 @@
 from django.core.management.base import BaseCommand
 from django.utils import translation
 
+
 class Command(BaseCommand):
 
     can_import_settings = True
diff --git a/tests/utils_tests/test_baseconv.py b/tests/utils_tests/test_baseconv.py
index d49dde1092..0af1c4e3f0 100644
--- a/tests/utils_tests/test_baseconv.py
+++ b/tests/utils_tests/test_baseconv.py
@@ -3,6 +3,7 @@ from unittest import TestCase
 from django.utils.baseconv import base2, base16, base36, base56, base62, base64, BaseConverter
 from django.utils.six.moves import xrange
 
+
 class TestBaseConv(TestCase):
 
     def test_baseconv(self):
diff --git a/tests/utils_tests/test_checksums.py b/tests/utils_tests/test_checksums.py
index cee6dca2a8..9c9f244b6c 100644
--- a/tests/utils_tests/test_checksums.py
+++ b/tests/utils_tests/test_checksums.py
@@ -2,6 +2,7 @@ import unittest
 
 from django.utils import checksums
 
+
 class TestUtilsChecksums(unittest.TestCase):
 
     def check_output(self, function, value, output=None):
diff --git a/tests/utils_tests/test_datetime_safe.py b/tests/utils_tests/test_datetime_safe.py
index c9c34dbf40..3a8d31d6d8 100644
--- a/tests/utils_tests/test_datetime_safe.py
+++ b/tests/utils_tests/test_datetime_safe.py
@@ -3,6 +3,7 @@ import unittest
 from datetime import date as original_date, datetime as original_datetime
 from django.utils.datetime_safe import date, datetime
 
+
 class DatetimeTests(unittest.TestCase):
 
     def setUp(self):
diff --git a/tests/utils_tests/test_decorators.py b/tests/utils_tests/test_decorators.py
index 2d8af0a6e9..a05a736c30 100644
--- a/tests/utils_tests/test_decorators.py
+++ b/tests/utils_tests/test_decorators.py
@@ -11,6 +11,7 @@ class ProcessViewMiddleware(object):
 
 process_view_dec = decorator_from_middleware(ProcessViewMiddleware)
 
+
 @process_view_dec
 def process_view(request):
     return HttpResponse()
diff --git a/tests/utils_tests/test_ipv6.py b/tests/utils_tests/test_ipv6.py
index 662e8b4135..6cd0cebc84 100644
--- a/tests/utils_tests/test_ipv6.py
+++ b/tests/utils_tests/test_ipv6.py
@@ -4,6 +4,7 @@ import unittest
 
 from django.utils.ipv6 import is_valid_ipv6_address, clean_ipv6_address
 
+
 class TestUtilsIPv6(unittest.TestCase):
 
     def test_validates_correct_plain_address(self):
diff --git a/tests/utils_tests/test_jslex.py b/tests/utils_tests/test_jslex.py
index 084e2feb5b..97e6dbc109 100644
--- a/tests/utils_tests/test_jslex.py
+++ b/tests/utils_tests/test_jslex.py
@@ -5,6 +5,7 @@
 from django.test import TestCase
 from django.utils.jslex import JsLexer, prepare_js_for_gettext
 
+
 class JsTokensTest(TestCase):
     LEX_CASES = [
         # ids
@@ -105,6 +106,7 @@ class JsTokensTest(TestCase):
           r'string "\")"', "punct ;"]),
     ]
 
+
 def make_function(input, toks):
     def test_func(self):
         lexer = JsLexer()
@@ -207,6 +209,7 @@ GETTEXT_CASES = (
 class JsToCForGettextTest(TestCase):
     pass
 
+
 def make_function(js, c):
     def test_func(self):
         self.assertMultiLineEqual(prepare_js_for_gettext(js), c)
diff --git a/tests/utils_tests/test_module_loading.py b/tests/utils_tests/test_module_loading.py
index 1886631006..5a7eadcedf 100644
--- a/tests/utils_tests/test_module_loading.py
+++ b/tests/utils_tests/test_module_loading.py
@@ -52,6 +52,7 @@ class DefaultLoader(unittest.TestCase):
         self.assertRaises(ImportError, import_module,
             'utils_tests.test_no_submodule.anything')
 
+
 class EggLoader(unittest.TestCase):
     def setUp(self):
         self.old_path = sys.path[:]
@@ -133,6 +134,7 @@ class ModuleImportTestCase(unittest.TestCase):
         self.assertIsNotNone(traceback.tb_next.tb_next,
             'Should have more than the calling frame in the traceback.')
 
+
 @override_settings(INSTALLED_APPS=('utils_tests.test_module',))
 class AutodiscoverModulesTestCase(SimpleTestCase):
 
@@ -188,6 +190,7 @@ class ProxyFinder(object):
             if fd:
                 fd.close()
 
+
 class TestFinder(object):
     def __init__(self, *args, **kwargs):
         self.importer = zipimporter(*args, **kwargs)
@@ -198,6 +201,7 @@ class TestFinder(object):
             return
         return TestLoader(importer)
 
+
 class TestLoader(object):
     def __init__(self, importer):
         self.importer = importer
@@ -207,6 +211,7 @@ class TestLoader(object):
         mod.__loader__ = self
         return mod
 
+
 class CustomLoader(EggLoader):
     """The Custom Loader test is exactly the same as the EggLoader, but
     it uses a custom defined Loader and Finder that is intentionally
diff --git a/tests/utils_tests/test_simplelazyobject.py b/tests/utils_tests/test_simplelazyobject.py
index 072db52e9e..14ad393bfa 100644
--- a/tests/utils_tests/test_simplelazyobject.py
+++ b/tests/utils_tests/test_simplelazyobject.py
@@ -177,6 +177,7 @@ class TestUtilsSimpleLazyObject(TestCase):
         self.assertEqual(len(lazy_list), 5)
         self.assertEqual(len(lazy_set), 4)
 
+
 class TestUtilsSimpleLazyObjectDjangoTestCase(DjangoTestCase):
 
     def test_pickle_py2_regression(self):
diff --git a/tests/utils_tests/test_text.py b/tests/utils_tests/test_text.py
index 441898c0b4..62e792fab6 100644
--- a/tests/utils_tests/test_text.py
+++ b/tests/utils_tests/test_text.py
@@ -4,6 +4,7 @@ from __future__ import unicode_literals
 from django.test import SimpleTestCase
 from django.utils import text
 
+
 class TestUtilsText(SimpleTestCase):
 
     def test_truncate_chars(self):
diff --git a/tests/utils_tests/test_tzinfo.py b/tests/utils_tests/test_tzinfo.py
index 43522bb1d0..85d6b673bb 100644
--- a/tests/utils_tests/test_tzinfo.py
+++ b/tests/utils_tests/test_tzinfo.py
@@ -13,6 +13,7 @@ with warnings.catch_warnings():
     warnings.filterwarnings("ignore", category=PendingDeprecationWarning)
     from django.utils.tzinfo import FixedOffset, LocalTimezone
 
+
 class TzinfoTests(IgnorePendingDeprecationWarningsMixin, unittest.TestCase):
 
     @classmethod
@@ -47,10 +48,10 @@ class TzinfoTests(IgnorePendingDeprecationWarningsMixin, unittest.TestCase):
         self.assertEqual(repr(FixedOffset(-280)), '-0440')
         self.assertEqual(repr(FixedOffset(-78.4)), '-0118')
         self.assertEqual(repr(FixedOffset(78.4)), '+0118')
-        self.assertEqual(repr(FixedOffset(-5.5*60)), '-0530')
-        self.assertEqual(repr(FixedOffset(5.5*60)), '+0530')
-        self.assertEqual(repr(FixedOffset(-.5*60)), '-0030')
-        self.assertEqual(repr(FixedOffset(.5*60)), '+0030')
+        self.assertEqual(repr(FixedOffset(-5.5 * 60)), '-0530')
+        self.assertEqual(repr(FixedOffset(5.5 * 60)), '+0530')
+        self.assertEqual(repr(FixedOffset(-.5 * 60)), '-0030')
+        self.assertEqual(repr(FixedOffset(.5 * 60)), '+0030')
 
     def test_16899(self):
         if not self.tz_tests:
diff --git a/tests/validation/models.py b/tests/validation/models.py
index ee5bcfc9aa..157b8cb158 100644
--- a/tests/validation/models.py
+++ b/tests/validation/models.py
@@ -11,6 +11,7 @@ def validate_answer_to_universe(value):
     if value != 42:
         raise ValidationError('This is not the answer to life, universe and everything!', code='not42')
 
+
 class ModelToValidate(models.Model):
     name = models.CharField(max_length=100)
     created = models.DateTimeField(default=datetime.now)
@@ -26,14 +27,17 @@ class ModelToValidate(models.Model):
         if self.number == 11:
             raise ValidationError('Invalid number supplied!')
 
+
 class UniqueFieldsModel(models.Model):
     unique_charfield = models.CharField(max_length=100, unique=True)
     unique_integerfield = models.IntegerField(unique=True)
     non_unique_field = models.IntegerField()
 
+
 class CustomPKModel(models.Model):
     my_pk_field = models.CharField(max_length=100, primary_key=True)
 
+
 class UniqueTogetherModel(models.Model):
     cfield = models.CharField(max_length=100)
     ifield = models.IntegerField()
@@ -42,6 +46,7 @@ class UniqueTogetherModel(models.Model):
     class Meta:
         unique_together = (('ifield', 'cfield',), ['ifield', 'efield'])
 
+
 class UniqueForDateModel(models.Model):
     start_date = models.DateField()
     end_date = models.DateTimeField()
@@ -49,6 +54,7 @@ class UniqueForDateModel(models.Model):
     order = models.IntegerField(unique_for_month="end_date")
     name = models.CharField(max_length=100)
 
+
 class CustomMessagesModel(models.Model):
     other = models.IntegerField(blank=True, null=True)
     number = models.IntegerField(db_column='number_val',
@@ -56,9 +62,11 @@ class CustomMessagesModel(models.Model):
         validators=[validate_answer_to_universe]
     )
 
+
 class Author(models.Model):
     name = models.CharField(max_length=100)
 
+
 class Article(models.Model):
     title = models.CharField(max_length=100)
     author = models.ForeignKey(Author)
@@ -68,6 +76,7 @@ class Article(models.Model):
         if self.pub_date is None:
             self.pub_date = datetime.now()
 
+
 @python_2_unicode_compatible
 class Post(models.Model):
     title = models.CharField(max_length=50, unique_for_date='posted', blank=True)
@@ -78,16 +87,19 @@ class Post(models.Model):
     def __str__(self):
         return self.name
 
+
 class FlexibleDatePost(models.Model):
     title = models.CharField(max_length=50, unique_for_date='posted', blank=True)
     slug = models.CharField(max_length=50, unique_for_year='posted', blank=True)
     subtitle = models.CharField(max_length=50, unique_for_month='posted', blank=True)
     posted = models.DateField(blank=True, null=True)
 
+
 class UniqueErrorsModel(models.Model):
     name = models.CharField(max_length=100, unique=True, error_messages={'unique': 'Custom unique name message.'})
     no = models.IntegerField(unique=True, error_messages={'unique': 'Custom unique number message.'})
 
+
 class GenericIPAddressTestModel(models.Model):
     generic_ip = models.GenericIPAddressField(blank=True, null=True, unique=True)
     v4_ip = models.GenericIPAddressField(blank=True, null=True, protocol="ipv4")
@@ -95,6 +107,7 @@ class GenericIPAddressTestModel(models.Model):
     ip_verbose_name = models.GenericIPAddressField("IP Address Verbose",
             blank=True, null=True)
 
+
 class GenericIPAddrUnpackUniqueTest(models.Model):
     generic_v4unpack_ip = models.GenericIPAddressField(null=True, blank=True, unique=True, unpack_ipv4=True)
 
diff --git a/tests/validation/test_unique.py b/tests/validation/test_unique.py
index 7d4ba26ff0..14ac5a2471 100644
--- a/tests/validation/test_unique.py
+++ b/tests/validation/test_unique.py
@@ -55,6 +55,7 @@ class GetUniqueCheckTests(unittest.TestCase):
         ), m._get_unique_checks(exclude='start_date')
         )
 
+
 class PerformUniqueChecksTest(TestCase):
     def test_primary_key_unique_check_not_performed_when_adding_and_pk_not_specified(self):
         # Regression test for #12560
diff --git a/tests/validation/tests.py b/tests/validation/tests.py
index 02839eaf26..7f81cafccf 100644
--- a/tests/validation/tests.py
+++ b/tests/validation/tests.py
@@ -52,7 +52,7 @@ class BaseModelValidationTests(ValidationTestCase):
         self.assertFieldFailsValidationWithMessage(mtv.full_clean, 'url', ['Enter a valid URL.'])
 
     def test_text_greater_that_charfields_max_length_raises_erros(self):
-        mtv = ModelToValidate(number=10, name='Some Name'*100)
+        mtv = ModelToValidate(number=10, name='Some Name' * 100)
         self.assertFailsValidation(mtv.full_clean, ['name'])
 
     def test_malformed_slug_raises_error(self):
@@ -65,6 +65,7 @@ class ArticleForm(forms.ModelForm):
         model = Article
         exclude = ['author']
 
+
 class ModelFormsTests(TestCase):
     def setUp(self):
         self.author = Author.objects.create(name='Joseph Kocherhans')
diff --git a/tests/validators/tests.py b/tests/validators/tests.py
index e3f418ee73..b0d1376aee 100644
--- a/tests/validators/tests.py
+++ b/tests/validators/tests.py
@@ -131,12 +131,12 @@ TEST_DATA = (
     (MinValueValidator(NOW), NOW - timedelta(days=1), ValidationError),
 
     (MaxLengthValidator(10), '', None),
-    (MaxLengthValidator(10), 10*'x', None),
+    (MaxLengthValidator(10), 10 * 'x', None),
 
-    (MaxLengthValidator(10), 15*'x', ValidationError),
+    (MaxLengthValidator(10), 15 * 'x', ValidationError),
 
-    (MinLengthValidator(10), 15*'x', None),
-    (MinLengthValidator(10), 10*'x', None),
+    (MinLengthValidator(10), 15 * 'x', None),
+    (MinLengthValidator(10), 10 * 'x', None),
 
     (MinLengthValidator(10), '', ValidationError),
 
@@ -182,6 +182,7 @@ TEST_DATA = (
     (RegexValidator(re.compile('x')), 'y', ValidationError),
 )
 
+
 def create_simple_test_method(validator, expected, value, num):
     if expected is not None and issubclass(expected, Exception):
         test_mask = 'test_%s_raises_error_%d'
@@ -214,6 +215,7 @@ def create_simple_test_method(validator, expected, value, num):
 
 # Dynamically assemble a test class with the contents of TEST_DATA
 
+
 class TestSimpleValidators(TestCase):
     def test_single_message(self):
         v = ValidationError('Not Valid')
diff --git a/tests/version/tests.py b/tests/version/tests.py
index 8663d52cc5..b4c4283c04 100644
--- a/tests/version/tests.py
+++ b/tests/version/tests.py
@@ -3,6 +3,7 @@ from unittest import TestCase
 from django import get_version
 from django.utils import six
 
+
 class VersionTests(TestCase):
 
     def test_development(self):
diff --git a/tests/view_tests/__init__.py b/tests/view_tests/__init__.py
index 3f16dadae2..b031e205e0 100644
--- a/tests/view_tests/__init__.py
+++ b/tests/view_tests/__init__.py
@@ -1,6 +1,7 @@
 # -*- coding: utf-8 -*-
 from __future__ import unicode_literals
 
+
 class BrokenException(Exception):
     pass
 
diff --git a/tests/view_tests/models.py b/tests/view_tests/models.py
index 461f98c028..f2707b1796 100644
--- a/tests/view_tests/models.py
+++ b/tests/view_tests/models.py
@@ -5,6 +5,7 @@ Regression tests for Django built-in views.
 from django.db import models
 from django.utils.encoding import python_2_unicode_compatible
 
+
 @python_2_unicode_compatible
 class Author(models.Model):
     name = models.CharField(max_length=100)
@@ -15,6 +16,7 @@ class Author(models.Model):
     def get_absolute_url(self):
         return '/views/authors/%s/' % self.id
 
+
 @python_2_unicode_compatible
 class BaseArticle(models.Model):
     """
@@ -31,9 +33,11 @@ class BaseArticle(models.Model):
     def __str__(self):
         return self.title
 
+
 class Article(BaseArticle):
     date_created = models.DateTimeField()
 
+
 class UrlArticle(BaseArticle):
     """
     An Article class with a get_absolute_url defined.
@@ -44,6 +48,7 @@ class UrlArticle(BaseArticle):
         return '/urlarticles/%s/' % self.slug
     get_absolute_url.purge = True
 
+
 class DateArticle(BaseArticle):
     """
     An article Model with a DateField instead of DateTimeField,
diff --git a/tests/view_tests/templatetags/debugtags.py b/tests/view_tests/templatetags/debugtags.py
index 5aafc3a9e0..1b9f3f9828 100644
--- a/tests/view_tests/templatetags/debugtags.py
+++ b/tests/view_tests/templatetags/debugtags.py
@@ -5,6 +5,7 @@ from ..views import BrokenException
 
 register = template.Library()
 
+
 @register.simple_tag
 def go_boom(arg):
     raise BrokenException(arg)
diff --git a/tests/view_tests/tests/test_debug.py b/tests/view_tests/tests/test_debug.py
index b22c7aad43..fbbcdc9a40 100644
--- a/tests/view_tests/tests/test_debug.py
+++ b/tests/view_tests/tests/test_debug.py
@@ -185,7 +185,7 @@ class ExceptionReporterTests(TestCase):
 
         for newline in ['\n', '\r\n', '\r']:
             fd, filename = mkstemp(text=False)
-            os.write(fd, force_bytes(newline.join(LINES)+newline))
+            os.write(fd, force_bytes(newline.join(LINES) + newline))
             os.close(fd)
 
             try:
@@ -375,7 +375,7 @@ class ExceptionReportTestMixin(object):
         Asserts that potentially sensitive info are displayed in the email report.
         """
         with self.settings(ADMINS=(('Admin', 'admin@fattie-breakie.com'),)):
-            mail.outbox = [] # Empty outbox
+            mail.outbox = []  # Empty outbox
             request = self.rf.post('/some_url/', self.breakfast_data)
             view(request)
             self.assertEqual(len(mail.outbox), 1)
@@ -408,7 +408,7 @@ class ExceptionReportTestMixin(object):
         Asserts that certain sensitive info are not displayed in the email report.
         """
         with self.settings(ADMINS=(('Admin', 'admin@fattie-breakie.com'),)):
-            mail.outbox = [] # Empty outbox
+            mail.outbox = []  # Empty outbox
             request = self.rf.post('/some_url/', self.breakfast_data)
             view(request)
             self.assertEqual(len(mail.outbox), 1)
@@ -448,7 +448,7 @@ class ExceptionReportTestMixin(object):
         Asserts that no variables or POST parameters are displayed in the email report.
         """
         with self.settings(ADMINS=(('Admin', 'admin@fattie-breakie.com'),)):
-            mail.outbox = [] # Empty outbox
+            mail.outbox = []  # Empty outbox
             request = self.rf.post('/some_url/', self.breakfast_data)
             view(request)
             self.assertEqual(len(mail.outbox), 1)
@@ -641,6 +641,7 @@ class ExceptionReporterFilterTests(TestCase, ExceptionReportTestMixin):
                 response = self.client.get('/views/raises500/')
                 self.assertNotContains(response, 'should not be displayed', status_code=500)
 
+
 class AjaxResponseExceptionReporterFilter(TestCase, ExceptionReportTestMixin):
     """
     Ensure that sensitive information can be filtered out of error reports.
diff --git a/tests/view_tests/tests/test_shortcuts.py b/tests/view_tests/tests/test_shortcuts.py
index 707df5ee7e..eb08433a44 100644
--- a/tests/view_tests/tests/test_shortcuts.py
+++ b/tests/view_tests/tests/test_shortcuts.py
@@ -1,6 +1,7 @@
 from django.test import TestCase
 from django.test.utils import override_settings
 
+
 @override_settings(
     TEMPLATE_CONTEXT_PROCESSORS=('django.core.context_processors.static',),
     STATIC_URL='/path/to/static/media/',
diff --git a/tests/view_tests/views.py b/tests/view_tests/views.py
index ed4e98a4c7..4373ef12f9 100644
--- a/tests/view_tests/views.py
+++ b/tests/view_tests/views.py
@@ -23,6 +23,7 @@ def index_page(request):
     """Dummy index page"""
     return HttpResponse('<html><body>Dummy page</body></html>')
 
+
 def raises(request):
     # Make sure that a callable that raises an exception in the stack frame's
     # local vars won't hijack the technical 500 response. See:
@@ -34,6 +35,7 @@ def raises(request):
     except Exception:
         return technical_500_response(request, *sys.exc_info())
 
+
 def raises500(request):
     # We need to inspect the HTML generated by the fancy 500 debug view but
     # the test client ignores it, so we send it explicitly.
@@ -42,85 +44,102 @@ def raises500(request):
     except Exception:
         return technical_500_response(request, *sys.exc_info())
 
+
 def raises400(request):
     raise SuspiciousOperation
 
+
 def raises403(request):
     raise PermissionDenied
 
+
 def raises404(request):
     resolver = get_resolver(None)
     resolver.resolve('')
 
+
 def redirect(request):
     """
     Forces an HTTP redirect.
     """
     return HttpResponseRedirect("target/")
 
+
 def view_exception(request, n):
     raise BrokenException(except_args[int(n)])
 
+
 def template_exception(request, n):
     return render_to_response('debug/template_exception.html',
         {'arg': except_args[int(n)]})
 
+
 def jsi18n(request):
     return render_to_response('jsi18n.html')
 
 # Some views to exercise the shortcuts
 
+
 def render_to_response_view(request):
     return render_to_response('debug/render_test.html', {
         'foo': 'FOO',
         'bar': 'BAR',
     })
 
+
 def render_to_response_view_with_request_context(request):
     return render_to_response('debug/render_test.html', {
         'foo': 'FOO',
         'bar': 'BAR',
     }, context_instance=RequestContext(request))
 
+
 def render_to_response_view_with_content_type(request):
     return render_to_response('debug/render_test.html', {
         'foo': 'FOO',
         'bar': 'BAR',
     }, content_type='application/x-rendertest')
 
+
 def render_to_response_view_with_dirs(request):
     return render_to_response('render_dirs_test.html', dirs=dirs)
 
+
 def render_view(request):
     return render(request, 'debug/render_test.html', {
         'foo': 'FOO',
         'bar': 'BAR',
     })
 
+
 def render_view_with_base_context(request):
     return render(request, 'debug/render_test.html', {
         'foo': 'FOO',
         'bar': 'BAR',
     }, context_instance=Context())
 
+
 def render_view_with_content_type(request):
     return render(request, 'debug/render_test.html', {
         'foo': 'FOO',
         'bar': 'BAR',
     }, content_type='application/x-rendertest')
 
+
 def render_view_with_status(request):
     return render(request, 'debug/render_test.html', {
         'foo': 'FOO',
         'bar': 'BAR',
     }, status=403)
 
+
 def render_view_with_current_app(request):
     return render(request, 'debug/render_test.html', {
         'foo': 'FOO',
         'bar': 'BAR',
     }, current_app="foobar_app")
 
+
 def render_view_with_current_app_conflict(request):
     # This should fail because we don't passing both a current_app and
     # context_instance:
@@ -129,9 +148,11 @@ def render_view_with_current_app_conflict(request):
         'bar': 'BAR',
     }, current_app="foobar_app", context_instance=RequestContext(request))
 
+
 def render_with_dirs(request):
     return render(request, 'render_dirs_test.html', dirs=dirs)
 
+
 def raises_template_does_not_exist(request, path='i_dont_exist.html'):
     # We need to inspect the HTML generated by the fancy 500 debug view but
     # the test client ignores it, so we send it explicitly.
@@ -140,11 +161,13 @@ def raises_template_does_not_exist(request, path='i_dont_exist.html'):
     except TemplateDoesNotExist:
         return technical_500_response(request, *sys.exc_info())
 
+
 def render_no_template(request):
     # If we do not specify a template, we need to make sure the debug
     # view doesn't blow up.
     return render(request, [], {})
 
+
 def send_log(request, exc_info):
     logger = getLogger('django.request')
     # The default logging config has a logging filter to ensure admin emails are
@@ -167,6 +190,7 @@ def send_log(request, exc_info):
     )
     admin_email_handler.filters = orig_filters
 
+
 def non_sensitive_view(request):
     # Do not just use plain strings for the variables' values in the code
     # so that the tests don't return false positives when the function's source
@@ -180,6 +204,7 @@ def non_sensitive_view(request):
         send_log(request, exc_info)
         return technical_500_response(request, *exc_info)
 
+
 @sensitive_variables('sauce')
 @sensitive_post_parameters('bacon-key', 'sausage-key')
 def sensitive_view(request):
@@ -195,6 +220,7 @@ def sensitive_view(request):
         send_log(request, exc_info)
         return technical_500_response(request, *exc_info)
 
+
 @sensitive_variables()
 @sensitive_post_parameters()
 def paranoid_view(request):
@@ -210,6 +236,7 @@ def paranoid_view(request):
         send_log(request, exc_info)
         return technical_500_response(request, *exc_info)
 
+
 def sensitive_args_function_caller(request):
     try:
         sensitive_args_function(''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']))
@@ -218,6 +245,7 @@ def sensitive_args_function_caller(request):
         send_log(request, exc_info)
         return technical_500_response(request, *exc_info)
 
+
 @sensitive_variables('sauce')
 def sensitive_args_function(sauce):
     # Do not just use plain strings for the variables' values in the code
@@ -226,6 +254,7 @@ def sensitive_args_function(sauce):
     cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd'])  # NOQA
     raise Exception
 
+
 def sensitive_kwargs_function_caller(request):
     try:
         sensitive_kwargs_function(''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']))
@@ -234,6 +263,7 @@ def sensitive_kwargs_function_caller(request):
         send_log(request, exc_info)
         return technical_500_response(request, *exc_info)
 
+
 @sensitive_variables('sauce')
 def sensitive_kwargs_function(sauce=None):
     # Do not just use plain strings for the variables' values in the code
@@ -242,6 +272,7 @@ def sensitive_kwargs_function(sauce=None):
     cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd'])  # NOQA
     raise Exception
 
+
 class UnsafeExceptionReporterFilter(SafeExceptionReporterFilter):
     """
     Ignores all the filtering done by its parent class.
@@ -287,6 +318,7 @@ class Klass(object):
             send_log(request, exc_info)
             return technical_500_response(request, *exc_info)
 
+
 def sensitive_method_view(request):
     return Klass().method(request)
 
diff --git a/tests/wsgi/urls.py b/tests/wsgi/urls.py
index 7c6701adec..563b7238af 100644
--- a/tests/wsgi/urls.py
+++ b/tests/wsgi/urls.py
@@ -1,6 +1,7 @@
 from django.conf.urls import url, patterns
 from django.http import HttpResponse
 
+
 def helloworld(request):
     return HttpResponse("Hello World!")
 

From 8eec2d93b6e93b8a1107fb3de2acd68d6994d6ec Mon Sep 17 00:00:00 2001
From: coagulant <baryshev@gmail.com>
Date: Sun, 3 Nov 2013 01:02:56 +0400
Subject: [PATCH 2/8] Fixed all E261 warnings

---
 django/conf/__init__.py                       |   2 +-
 django/conf/global_settings.py                |  12 +-
 django/conf/locale/bg/formats.py              |   2 +-
 django/conf/locale/ca/formats.py              |   2 +-
 django/conf/locale/cs/formats.py              |  12 +-
 django/conf/locale/de/formats.py              |   4 +-
 django/conf/locale/de_CH/formats.py           |   6 +-
 django/conf/locale/en/formats.py              |   4 +-
 django/conf/locale/es/formats.py              |   2 +-
 django/conf/locale/es_AR/formats.py           |   6 +-
 django/conf/locale/es_MX/formats.py           |   2 +-
 django/conf/locale/es_NI/formats.py           |   2 +-
 django/conf/locale/es_PR/formats.py           |   2 +-
 django/conf/locale/et/formats.py              |   2 +-
 django/conf/locale/fi/formats.py              |   2 +-
 django/conf/locale/fr/formats.py              |  24 +--
 django/conf/locale/gl/formats.py              |   2 +-
 django/conf/locale/hr/formats.py              |  40 ++---
 django/conf/locale/hu/formats.py              |  10 +-
 django/conf/locale/it/formats.py              |  16 +-
 django/conf/locale/ka/formats.py              |   2 +-
 django/conf/locale/ko/formats.py              |   2 +-
 django/conf/locale/lt/formats.py              |   2 +-
 django/conf/locale/lv/formats.py              |   4 +-
 django/conf/locale/mk/formats.py              |  32 ++--
 django/conf/locale/ml/formats.py              |   4 +-
 django/conf/locale/nb/formats.py              |   6 +-
 django/conf/locale/nn/formats.py              |   6 +-
 django/conf/locale/pl/formats.py              |  10 +-
 django/conf/locale/pt/formats.py              |   2 +-
 django/conf/locale/pt_BR/formats.py           |   2 +-
 django/conf/locale/ru/formats.py              |  18 +--
 django/conf/locale/sk/formats.py              |  12 +-
 django/conf/locale/sr/formats.py              |  32 ++--
 django/conf/locale/sr_Latn/formats.py         |  32 ++--
 django/conf/locale/sv/formats.py              |   2 +-
 django/conf/locale/tr/formats.py              |  10 +-
 django/contrib/admin/helpers.py               |   6 +-
 django/contrib/admin/options.py               |   2 +-
 .../contrib/admin/templatetags/admin_list.py  |   8 +-
 .../admin/templatetags/admin_modify.py        |   2 +-
 django/contrib/admin/utils.py                 |  12 +-
 django/contrib/admin/validation.py            |   8 +-
 django/contrib/admin/views/main.py            |   8 +-
 django/contrib/admin/widgets.py               |   2 +-
 django/contrib/contenttypes/generic.py        |   2 +-
 django/contrib/flatpages/middleware.py        |   2 +-
 django/contrib/formtools/preview.py           |   6 +-
 .../gis/db/backends/mysql/operations.py       |   6 +-
 .../gis/db/backends/oracle/operations.py      |   6 +-
 .../gis/db/backends/postgis/operations.py     |   2 +-
 .../gis/db/backends/spatialite/operations.py  |   6 +-
 django/contrib/gis/db/models/fields.py        |   2 +-
 django/contrib/gis/db/models/query.py         |   4 +-
 django/contrib/gis/gdal/geometries.py         |   6 +-
 django/contrib/gis/gdal/prototypes/ds.py      |   2 +-
 django/contrib/gis/gdal/prototypes/geom.py    |   2 +-
 django/contrib/gis/gdal/tests/test_ds.py      |   8 +-
 .../contrib/gis/gdal/tests/test_envelope.py   |   2 +-
 django/contrib/gis/gdal/tests/test_geom.py    |  38 ++---
 django/contrib/gis/gdal/tests/test_srs.py     |   4 +-
 django/contrib/gis/geoip/tests.py             |   6 +-
 django/contrib/gis/geos/linestring.py         |   8 +-
 .../contrib/gis/geos/prototypes/errcheck.py   |   2 +-
 django/contrib/gis/geos/prototypes/misc.py    |   2 +-
 django/contrib/gis/geos/tests/test_geos.py    |  56 +++----
 .../gis/geos/tests/test_mutable_list.py       |   6 +-
 django/contrib/gis/maps/google/gmap.py        |   6 +-
 django/contrib/gis/maps/google/zoom.py        |  14 +-
 django/contrib/gis/tests/distapp/tests.py     |   8 +-
 django/contrib/gis/tests/geoapp/models.py     |   8 +-
 django/contrib/gis/tests/geoapp/test_feeds.py |   4 +-
 .../contrib/gis/tests/geoapp/test_sitemaps.py |   2 +-
 django/contrib/gis/tests/geoapp/tests.py      |  24 +--
 django/contrib/gis/tests/geogapp/tests.py     |   4 +-
 django/contrib/gis/tests/layermap/models.py   |   6 +-
 django/contrib/gis/tests/layermap/tests.py    |  10 +-
 .../contrib/gis/tests/test_spatialrefsys.py   |   4 +-
 django/contrib/gis/utils/layermapping.py      |   6 +-
 django/contrib/messages/storage/cookie.py     |   2 +-
 django/contrib/messages/tests/test_cookie.py  |   2 +-
 django/contrib/sessions/models.py             |   2 +-
 django/contrib/sessions/tests.py              |   2 +-
 django/core/cache/backends/memcached.py       |   2 +-
 django/core/files/uploadhandler.py            |   2 +-
 django/core/handlers/base.py                  |   4 +-
 django/core/handlers/wsgi.py                  |   2 +-
 django/core/management/__init__.py            |   6 +-
 django/core/management/commands/inspectdb.py  |   6 +-
 django/core/urlresolvers.py                   |   6 +-
 django/core/validators.py                     |   2 +-
 django/db/backends/mysql/base.py              |   6 +-
 django/db/backends/oracle/creation.py         |   2 +-
 django/db/backends/oracle/introspection.py    |   4 +-
 .../postgresql_psycopg2/introspection.py      |   2 +-
 .../postgresql_psycopg2/operations.py         |   4 +-
 django/db/backends/sqlite3/base.py            |   2 +-
 django/db/backends/sqlite3/introspection.py   |   2 +-
 django/db/backends/utils.py                   |  10 +-
 django/db/models/__init__.py                  |   2 +-
 django/db/models/base.py                      |   2 +-
 django/db/models/fields/__init__.py           |   2 +-
 django/db/models/query.py                     |   8 +-
 django/db/models/sql/query.py                 |   2 +-
 django/http/multipartparser.py                |   4 +-
 django/http/request.py                        |  14 +-
 django/middleware/cache.py                    |   6 +-
 django/templatetags/cache.py                  |   2 +-
 django/test/_doctest.py                       |  16 +-
 django/test/simple.py                         |   4 +-
 django/utils/dictconfig.py                    |  66 ++++-----
 django/views/debug.py                         |   2 +-
 docs/conf.py                                  |   2 +-
 setup.cfg                                     |   2 +-
 tests/admin_changelist/admin.py               |   2 +-
 tests/admin_filters/models.py                 |   2 +-
 tests/admin_filters/tests.py                  |   4 +-
 tests/admin_inlines/admin.py                  |   2 +-
 tests/admin_ordering/tests.py                 |   2 +-
 tests/admin_views/admin.py                    |   8 +-
 tests/admin_views/customadmin.py              |   4 +-
 tests/admin_views/models.py                   |   2 +-
 tests/admin_widgets/tests.py                  |   4 +-
 tests/aggregation_regress/tests.py            |   2 +-
 tests/cache/tests.py                          |   6 +-
 .../tests/test_moderation_views.py            |   6 +-
 tests/datatypes/tests.py                      |   2 +-
 tests/file_uploads/uploadhandler.py           |   2 +-
 tests/forms_tests/tests/test_forms.py         |   2 +-
 tests/forms_tests/tests/test_formsets.py      | 140 +++++++++---------
 tests/forms_tests/tests/test_input_formats.py |  10 +-
 tests/generic_inline_admin/tests.py           |   6 +-
 tests/httpwrappers/tests.py                   |  14 +-
 tests/i18n/test_extraction.py                 |   2 +-
 tests/i18n/tests.py                           |   2 +-
 tests/invalid_models/invalid_models/models.py |   2 +-
 tests/m2m_and_m2o/tests.py                    |   4 +-
 tests/max_lengths/tests.py                    |   2 +-
 tests/model_forms/tests.py                    |  12 +-
 tests/model_formsets/tests.py                 | 110 +++++++-------
 tests/modeladmin/models.py                    |   2 +-
 tests/multiple_database/tests.py              |  12 +-
 tests/null_fk/tests.py                        |   2 +-
 tests/queryset_pickle/tests.py                |   2 +-
 tests/requests/tests.py                       |  10 +-
 tests/serializers_regress/tests.py            |   2 +-
 tests/template_tests/filters.py               |   2 +-
 tests/template_tests/tests.py                 |   2 +-
 tests/test_client/tests.py                    |   2 +-
 tests/test_client_regress/tests.py            |   6 +-
 tests/view_tests/__init__.py                  |   2 +-
 tests/view_tests/tests/test_defaults.py       |   4 +-
 152 files changed, 630 insertions(+), 630 deletions(-)

diff --git a/django/conf/__init__.py b/django/conf/__init__.py
index 7a915f1486..5245ff9e25 100644
--- a/django/conf/__init__.py
+++ b/django/conf/__init__.py
@@ -36,7 +36,7 @@ class LazySettings(LazyObject):
         """
         try:
             settings_module = os.environ[ENVIRONMENT_VARIABLE]
-            if not settings_module: # If it's set but is an empty string.
+            if not settings_module:  # If it's set but is an empty string.
                 raise KeyError
         except KeyError:
             desc = ("setting %s" % name) if name else "settings"
diff --git a/django/conf/global_settings.py b/django/conf/global_settings.py
index 377c010b32..19d70eeb3e 100644
--- a/django/conf/global_settings.py
+++ b/django/conf/global_settings.py
@@ -302,7 +302,7 @@ FILE_UPLOAD_HANDLERS = (
 
 # Maximum size, in bytes, of a request before it will be streamed to the
 # file system instead of into memory.
-FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB
+FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440  # i.e. 2.5 MB
 
 # Directory in which upload streamed files will be temporarily saved. A value of
 # `None` will make Django use the operating system's default temporary directory
@@ -360,11 +360,11 @@ SHORT_DATETIME_FORMAT = 'm/d/Y P'
 # http://docs.python.org/library/datetime.html#strftime-behavior
 # * Note that these format strings are different from the ones to display dates
 DATE_INPUT_FORMATS = (
-    '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
-    '%b %d %Y', '%b %d, %Y',            # 'Oct 25 2006', 'Oct 25, 2006'
-    '%d %b %Y', '%d %b, %Y',            # '25 Oct 2006', '25 Oct, 2006'
-    '%B %d %Y', '%B %d, %Y',            # 'October 25 2006', 'October 25, 2006'
-    '%d %B %Y', '%d %B, %Y',            # '25 October 2006', '25 October, 2006'
+    '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y',  # '2006-10-25', '10/25/2006', '10/25/06'
+    '%b %d %Y', '%b %d, %Y',             # 'Oct 25 2006', 'Oct 25, 2006'
+    '%d %b %Y', '%d %b, %Y',             # '25 Oct 2006', '25 Oct, 2006'
+    '%B %d %Y', '%B %d, %Y',             # 'October 25 2006', 'October 25, 2006'
+    '%d %B %Y', '%d %B, %Y',             # '25 October 2006', '25 October, 2006'
 )
 
 # Default formats to be used when parsing times from input boxes, in order
diff --git a/django/conf/locale/bg/formats.py b/django/conf/locale/bg/formats.py
index 4472600398..e1a8a820e3 100644
--- a/django/conf/locale/bg/formats.py
+++ b/django/conf/locale/bg/formats.py
@@ -20,5 +20,5 @@ SHORT_DATE_FORMAT = 'd.m.Y'
 # TIME_INPUT_FORMATS =
 # DATETIME_INPUT_FORMATS =
 DECIMAL_SEPARATOR = ','
-THOUSAND_SEPARATOR = ' ' # Non-breaking space
+THOUSAND_SEPARATOR = ' '  # Non-breaking space
 # NUMBER_GROUPING =
diff --git a/django/conf/locale/ca/formats.py b/django/conf/locale/ca/formats.py
index 9ccddbb24d..392eb48c1c 100644
--- a/django/conf/locale/ca/formats.py
+++ b/django/conf/locale/ca/formats.py
@@ -12,7 +12,7 @@ YEAR_MONTH_FORMAT = r'F \d\e\l Y'
 MONTH_DAY_FORMAT = r'j \d\e F'
 SHORT_DATE_FORMAT = 'd/m/Y'
 SHORT_DATETIME_FORMAT = 'd/m/Y G:i'
-FIRST_DAY_OF_WEEK = 1 # Monday
+FIRST_DAY_OF_WEEK = 1  # Monday
 
 # The *_INPUT_FORMATS strings use the Python strftime format syntax,
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
diff --git a/django/conf/locale/cs/formats.py b/django/conf/locale/cs/formats.py
index 42ca212392..fd445fac6a 100644
--- a/django/conf/locale/cs/formats.py
+++ b/django/conf/locale/cs/formats.py
@@ -12,34 +12,34 @@ YEAR_MONTH_FORMAT = 'F Y'
 MONTH_DAY_FORMAT = 'j. F'
 SHORT_DATE_FORMAT = 'd.m.Y'
 SHORT_DATETIME_FORMAT = 'd.m.Y G:i:s'
-FIRST_DAY_OF_WEEK = 1 # Monday
+FIRST_DAY_OF_WEEK = 1  # Monday
 
 # The *_INPUT_FORMATS strings use the Python strftime format syntax,
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
 DATE_INPUT_FORMATS = (
     '%d.%m.%Y', '%d.%m.%y',     # '05.01.2006', '05.01.06'
-    '%d. %m. %Y', '%d. %m. %y', # '5. 1. 2006', '5. 1. 06'
+    '%d. %m. %Y', '%d. %m. %y',  # '5. 1. 2006', '5. 1. 06'
     # '%d. %B %Y', '%d. %b. %Y',  # '25. October 2006', '25. Oct. 2006'
 )
 # Kept ISO formats as one is in first position
 TIME_INPUT_FORMATS = (
-    '%H:%M:%S', # '04:30:59'
+    '%H:%M:%S',  # '04:30:59'
     '%H.%M',    # '04.30'
     '%H:%M',    # '04:30'
 )
 DATETIME_INPUT_FORMATS = (
     '%d.%m.%Y %H:%M:%S',    # '05.01.2006 04:30:59'
-    '%d.%m.%Y %H:%M:%S.%f', # '05.01.2006 04:30:59.000200'
+    '%d.%m.%Y %H:%M:%S.%f',  # '05.01.2006 04:30:59.000200'
     '%d.%m.%Y %H.%M',       # '05.01.2006 04.30'
     '%d.%m.%Y %H:%M',       # '05.01.2006 04:30'
     '%d.%m.%Y',             # '05.01.2006'
     '%d. %m. %Y %H:%M:%S',  # '05. 01. 2006 04:30:59'
-    '%d. %m. %Y %H:%M:%S.%f', # '05. 01. 2006 04:30:59.000200'
+    '%d. %m. %Y %H:%M:%S.%f',  # '05. 01. 2006 04:30:59.000200'
     '%d. %m. %Y %H.%M',     # '05. 01. 2006 04.30'
     '%d. %m. %Y %H:%M',     # '05. 01. 2006 04:30'
     '%d. %m. %Y',           # '05. 01. 2006'
     '%Y-%m-%d %H.%M',       # '2006-01-05 04.30'
 )
 DECIMAL_SEPARATOR = ','
-THOUSAND_SEPARATOR = '\xa0' # non-breaking space
+THOUSAND_SEPARATOR = '\xa0'  # non-breaking space
 NUMBER_GROUPING = 3
diff --git a/django/conf/locale/de/formats.py b/django/conf/locale/de/formats.py
index b3731a3617..b57f6213a5 100644
--- a/django/conf/locale/de/formats.py
+++ b/django/conf/locale/de/formats.py
@@ -12,7 +12,7 @@ YEAR_MONTH_FORMAT = 'F Y'
 MONTH_DAY_FORMAT = 'j. F'
 SHORT_DATE_FORMAT = 'd.m.Y'
 SHORT_DATETIME_FORMAT = 'd.m.Y H:i:s'
-FIRST_DAY_OF_WEEK = 1 # Monday
+FIRST_DAY_OF_WEEK = 1  # Monday
 
 # The *_INPUT_FORMATS strings use the Python strftime format syntax,
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
@@ -22,7 +22,7 @@ DATE_INPUT_FORMATS = (
 )
 DATETIME_INPUT_FORMATS = (
     '%d.%m.%Y %H:%M:%S',    # '25.10.2006 14:30:59'
-    '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200'
+    '%d.%m.%Y %H:%M:%S.%f',  # '25.10.2006 14:30:59.000200'
     '%d.%m.%Y %H:%M',       # '25.10.2006 14:30'
     '%d.%m.%Y',             # '25.10.2006'
 )
diff --git a/django/conf/locale/de_CH/formats.py b/django/conf/locale/de_CH/formats.py
index bf8a5ce372..4b1678cffd 100644
--- a/django/conf/locale/de_CH/formats.py
+++ b/django/conf/locale/de_CH/formats.py
@@ -13,7 +13,7 @@ YEAR_MONTH_FORMAT = 'F Y'
 MONTH_DAY_FORMAT = 'j. F'
 SHORT_DATE_FORMAT = 'd.m.Y'
 SHORT_DATETIME_FORMAT = 'd.m.Y H:i:s'
-FIRST_DAY_OF_WEEK = 1 # Monday
+FIRST_DAY_OF_WEEK = 1  # Monday
 
 # The *_INPUT_FORMATS strings use the Python strftime format syntax,
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
@@ -23,7 +23,7 @@ DATE_INPUT_FORMATS = (
 )
 DATETIME_INPUT_FORMATS = (
     '%d.%m.%Y %H:%M:%S',    # '25.10.2006 14:30:59'
-    '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200'
+    '%d.%m.%Y %H:%M:%S.%f',  # '25.10.2006 14:30:59.000200'
     '%d.%m.%Y %H:%M',       # '25.10.2006 14:30'
     '%d.%m.%Y',             # '25.10.2006'
 )
@@ -34,5 +34,5 @@ DATETIME_INPUT_FORMATS = (
 # For details, please refer to http://www.bk.admin.ch/dokumentation/sprachen/04915/05016/index.html?lang=de
 # (in German) and the documentation
 DECIMAL_SEPARATOR = ','
-THOUSAND_SEPARATOR = '\xa0' # non-breaking space
+THOUSAND_SEPARATOR = '\xa0'  # non-breaking space
 NUMBER_GROUPING = 3
diff --git a/django/conf/locale/en/formats.py b/django/conf/locale/en/formats.py
index 5accf9e3d2..279cd3c518 100644
--- a/django/conf/locale/en/formats.py
+++ b/django/conf/locale/en/formats.py
@@ -12,13 +12,13 @@ YEAR_MONTH_FORMAT = 'F Y'
 MONTH_DAY_FORMAT = 'F j'
 SHORT_DATE_FORMAT = 'm/d/Y'
 SHORT_DATETIME_FORMAT = 'm/d/Y P'
-FIRST_DAY_OF_WEEK = 0 # Sunday
+FIRST_DAY_OF_WEEK = 0  # Sunday
 
 # The *_INPUT_FORMATS strings use the Python strftime format syntax,
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
 # Kept ISO formats as they are in first position
 DATE_INPUT_FORMATS = (
-    '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
+    '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y',  # '2006-10-25', '10/25/2006', '10/25/06'
     # '%b %d %Y', '%b %d, %Y',            # 'Oct 25 2006', 'Oct 25, 2006'
     # '%d %b %Y', '%d %b, %Y',            # '25 Oct 2006', '25 Oct, 2006'
     # '%B %d %Y', '%B %d, %Y',            # 'October 25 2006', 'October 25, 2006'
diff --git a/django/conf/locale/es/formats.py b/django/conf/locale/es/formats.py
index 08029a876e..dee0a889f6 100644
--- a/django/conf/locale/es/formats.py
+++ b/django/conf/locale/es/formats.py
@@ -12,7 +12,7 @@ YEAR_MONTH_FORMAT = r'F \d\e Y'
 MONTH_DAY_FORMAT = r'j \d\e F'
 SHORT_DATE_FORMAT = 'd/m/Y'
 SHORT_DATETIME_FORMAT = 'd/m/Y H:i'
-FIRST_DAY_OF_WEEK = 1 # Monday
+FIRST_DAY_OF_WEEK = 1  # Monday
 
 # The *_INPUT_FORMATS strings use the Python strftime format syntax,
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
diff --git a/django/conf/locale/es_AR/formats.py b/django/conf/locale/es_AR/formats.py
index 41c732f7b8..37faa80b8a 100644
--- a/django/conf/locale/es_AR/formats.py
+++ b/django/conf/locale/es_AR/formats.py
@@ -12,13 +12,13 @@ YEAR_MONTH_FORMAT = r'F Y'
 MONTH_DAY_FORMAT = r'j \d\e F'
 SHORT_DATE_FORMAT = r'd/m/Y'
 SHORT_DATETIME_FORMAT = r'd/m/Y H:i'
-FIRST_DAY_OF_WEEK = 0 # 0: Sunday, 1: Monday
+FIRST_DAY_OF_WEEK = 0  # 0: Sunday, 1: Monday
 
 # The *_INPUT_FORMATS strings use the Python strftime format syntax,
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
 DATE_INPUT_FORMATS = (
-    '%d/%m/%Y', # '31/12/2009'
-    '%d/%m/%y', # '31/12/09'
+    '%d/%m/%Y',  # '31/12/2009'
+    '%d/%m/%y',  # '31/12/09'
 )
 DATETIME_INPUT_FORMATS = (
     '%d/%m/%Y %H:%M:%S',
diff --git a/django/conf/locale/es_MX/formats.py b/django/conf/locale/es_MX/formats.py
index e3ac674ab0..729eee5370 100644
--- a/django/conf/locale/es_MX/formats.py
+++ b/django/conf/locale/es_MX/formats.py
@@ -24,5 +24,5 @@ DATETIME_INPUT_FORMATS = (
     '%d/%m/%y %H:%M',
 )
 DECIMAL_SEPARATOR = '.'   # ',' is also official (less common): NOM-008-SCFI-2002
-THOUSAND_SEPARATOR = '\xa0' # non-breaking space
+THOUSAND_SEPARATOR = '\xa0'  # non-breaking space
 NUMBER_GROUPING = 3
diff --git a/django/conf/locale/es_NI/formats.py b/django/conf/locale/es_NI/formats.py
index 4bdf24e491..2f8d403d85 100644
--- a/django/conf/locale/es_NI/formats.py
+++ b/django/conf/locale/es_NI/formats.py
@@ -10,7 +10,7 @@ YEAR_MONTH_FORMAT = r'F \d\e Y'
 MONTH_DAY_FORMAT = r'j \d\e F'
 SHORT_DATE_FORMAT = 'd/m/Y'
 SHORT_DATETIME_FORMAT = 'd/m/Y H:i'
-FIRST_DAY_OF_WEEK = 1 # Monday: ISO 8601
+FIRST_DAY_OF_WEEK = 1  # Monday: ISO 8601
 DATE_INPUT_FORMATS = (
     '%d/%m/%Y', '%d/%m/%y',            # '25/10/2006', '25/10/06'
     '%Y%m%d',                          # '20061025'
diff --git a/django/conf/locale/es_PR/formats.py b/django/conf/locale/es_PR/formats.py
index 1d4e76c55b..8f5a25ea53 100644
--- a/django/conf/locale/es_PR/formats.py
+++ b/django/conf/locale/es_PR/formats.py
@@ -10,7 +10,7 @@ YEAR_MONTH_FORMAT = r'F \d\e Y'
 MONTH_DAY_FORMAT = r'j \d\e F'
 SHORT_DATE_FORMAT = 'd/m/Y'
 SHORT_DATETIME_FORMAT = 'd/m/Y H:i'
-FIRST_DAY_OF_WEEK = 0 # Sunday
+FIRST_DAY_OF_WEEK = 0  # Sunday
 
 DATE_INPUT_FORMATS = (
     # '31/12/2009', '31/12/09'
diff --git a/django/conf/locale/et/formats.py b/django/conf/locale/et/formats.py
index 1de3948a2b..5be8131ed6 100644
--- a/django/conf/locale/et/formats.py
+++ b/django/conf/locale/et/formats.py
@@ -20,5 +20,5 @@ SHORT_DATE_FORMAT = 'd.m.Y'
 # TIME_INPUT_FORMATS =
 # DATETIME_INPUT_FORMATS =
 DECIMAL_SEPARATOR = ','
-THOUSAND_SEPARATOR = ' ' # Non-breaking space
+THOUSAND_SEPARATOR = ' '  # Non-breaking space
 # NUMBER_GROUPING =
diff --git a/django/conf/locale/fi/formats.py b/django/conf/locale/fi/formats.py
index da1f003411..b1900a3b7c 100644
--- a/django/conf/locale/fi/formats.py
+++ b/django/conf/locale/fi/formats.py
@@ -20,5 +20,5 @@ SHORT_DATE_FORMAT = 'j.n.Y'
 # TIME_INPUT_FORMATS =
 # DATETIME_INPUT_FORMATS =
 DECIMAL_SEPARATOR = ','
-THOUSAND_SEPARATOR = ' ' # Non-breaking space
+THOUSAND_SEPARATOR = ' '  # Non-breaking space
 # NUMBER_GROUPING =
diff --git a/django/conf/locale/fr/formats.py b/django/conf/locale/fr/formats.py
index f6c8f40648..7b85807404 100644
--- a/django/conf/locale/fr/formats.py
+++ b/django/conf/locale/fr/formats.py
@@ -12,25 +12,25 @@ YEAR_MONTH_FORMAT = 'F Y'
 MONTH_DAY_FORMAT = 'j F'
 SHORT_DATE_FORMAT = 'j N Y'
 SHORT_DATETIME_FORMAT = 'j N Y H:i:s'
-FIRST_DAY_OF_WEEK = 1 # Monday
+FIRST_DAY_OF_WEEK = 1  # Monday
 
 # The *_INPUT_FORMATS strings use the Python strftime format syntax,
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
 DATE_INPUT_FORMATS = (
-    '%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06'
-    '%d.%m.%Y', '%d.%m.%y', # Swiss (fr_CH), '25.10.2006', '25.10.06'
+    '%d/%m/%Y', '%d/%m/%y',  # '25/10/2006', '25/10/06'
+    '%d.%m.%Y', '%d.%m.%y',  # Swiss (fr_CH), '25.10.2006', '25.10.06'
     # '%d %B %Y', '%d %b %Y', # '25 octobre 2006', '25 oct. 2006'
 )
 DATETIME_INPUT_FORMATS = (
-    '%d/%m/%Y %H:%M:%S',    # '25/10/2006 14:30:59'
-    '%d/%m/%Y %H:%M:%S.%f', # '25/10/2006 14:30:59.000200'
-    '%d/%m/%Y %H:%M',       # '25/10/2006 14:30'
-    '%d/%m/%Y',             # '25/10/2006'
-    '%d.%m.%Y %H:%M:%S',    # Swiss (fr_CH), '25.10.2006 14:30:59'
-    '%d.%m.%Y %H:%M:%S.%f', # Swiss (fr_CH), '25.10.2006 14:30:59.000200'
-    '%d.%m.%Y %H:%M',       # Swiss (fr_CH), '25.10.2006 14:30'
-    '%d.%m.%Y',             # Swiss (fr_CH), '25.10.2006'
+    '%d/%m/%Y %H:%M:%S',     # '25/10/2006 14:30:59'
+    '%d/%m/%Y %H:%M:%S.%f',  # '25/10/2006 14:30:59.000200'
+    '%d/%m/%Y %H:%M',        # '25/10/2006 14:30'
+    '%d/%m/%Y',              # '25/10/2006'
+    '%d.%m.%Y %H:%M:%S',     # Swiss (fr_CH), '25.10.2006 14:30:59'
+    '%d.%m.%Y %H:%M:%S.%f',  # Swiss (fr_CH), '25.10.2006 14:30:59.000200'
+    '%d.%m.%Y %H:%M',        # Swiss (fr_CH), '25.10.2006 14:30'
+    '%d.%m.%Y',              # Swiss (fr_CH), '25.10.2006'
 )
 DECIMAL_SEPARATOR = ','
-THOUSAND_SEPARATOR = '\xa0' # non-breaking space
+THOUSAND_SEPARATOR = '\xa0'  # non-breaking space
 NUMBER_GROUPING = 3
diff --git a/django/conf/locale/gl/formats.py b/django/conf/locale/gl/formats.py
index de592240f0..0facf691a9 100644
--- a/django/conf/locale/gl/formats.py
+++ b/django/conf/locale/gl/formats.py
@@ -12,7 +12,7 @@ YEAR_MONTH_FORMAT = r'F \d\e Y'
 MONTH_DAY_FORMAT = r'j \d\e F'
 SHORT_DATE_FORMAT = 'd-m-Y'
 SHORT_DATETIME_FORMAT = 'd-m-Y, H:i'
-FIRST_DAY_OF_WEEK = 1 # Monday
+FIRST_DAY_OF_WEEK = 1  # Monday
 
 # The *_INPUT_FORMATS strings use the Python strftime format syntax,
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
diff --git a/django/conf/locale/hr/formats.py b/django/conf/locale/hr/formats.py
index 96a724b2b8..a38457a435 100644
--- a/django/conf/locale/hr/formats.py
+++ b/django/conf/locale/hr/formats.py
@@ -23,26 +23,26 @@ DATE_INPUT_FORMATS = (
     '%d. %m. %Y.', '%d. %m. %y.',   # '25. 10. 2006.', '25. 10. 06.'
 )
 DATETIME_INPUT_FORMATS = (
-    '%Y-%m-%d %H:%M:%S',      # '2006-10-25 14:30:59'
-    '%Y-%m-%d %H:%M:%S.%f',   # '2006-10-25 14:30:59.000200'
-    '%Y-%m-%d %H:%M',         # '2006-10-25 14:30'
-    '%Y-%m-%d',               # '2006-10-25'
-    '%d.%m.%Y. %H:%M:%S',     # '25.10.2006. 14:30:59'
-    '%d.%m.%Y. %H:%M:%S.%f',  # '25.10.2006. 14:30:59.000200'
-    '%d.%m.%Y. %H:%M',        # '25.10.2006. 14:30'
-    '%d.%m.%Y.',              # '25.10.2006.'
-    '%d.%m.%y. %H:%M:%S',     # '25.10.06. 14:30:59'
-    '%d.%m.%y. %H:%M:%S.%f',  # '25.10.06. 14:30:59.000200'
-    '%d.%m.%y. %H:%M',        # '25.10.06. 14:30'
-    '%d.%m.%y.',              # '25.10.06.'
-    '%d. %m. %Y. %H:%M:%S',   # '25. 10. 2006. 14:30:59'
-    '%d. %m. %Y. %H:%M:%S.%f',# '25. 10. 2006. 14:30:59.000200'
-    '%d. %m. %Y. %H:%M',      # '25. 10. 2006. 14:30'
-    '%d. %m. %Y.',            # '25. 10. 2006.'
-    '%d. %m. %y. %H:%M:%S',   # '25. 10. 06. 14:30:59'
-    '%d. %m. %y. %H:%M:%S.%f',# '25. 10. 06. 14:30:59.000200'
-    '%d. %m. %y. %H:%M',      # '25. 10. 06. 14:30'
-    '%d. %m. %y.',            # '25. 10. 06.'
+    '%Y-%m-%d %H:%M:%S',        # '2006-10-25 14:30:59'
+    '%Y-%m-%d %H:%M:%S.%f',     # '2006-10-25 14:30:59.000200'
+    '%Y-%m-%d %H:%M',           # '2006-10-25 14:30'
+    '%Y-%m-%d',                 # '2006-10-25'
+    '%d.%m.%Y. %H:%M:%S',       # '25.10.2006. 14:30:59'
+    '%d.%m.%Y. %H:%M:%S.%f',    # '25.10.2006. 14:30:59.000200'
+    '%d.%m.%Y. %H:%M',          # '25.10.2006. 14:30'
+    '%d.%m.%Y.',                # '25.10.2006.'
+    '%d.%m.%y. %H:%M:%S',       # '25.10.06. 14:30:59'
+    '%d.%m.%y. %H:%M:%S.%f',    # '25.10.06. 14:30:59.000200'
+    '%d.%m.%y. %H:%M',          # '25.10.06. 14:30'
+    '%d.%m.%y.',                # '25.10.06.'
+    '%d. %m. %Y. %H:%M:%S',     # '25. 10. 2006. 14:30:59'
+    '%d. %m. %Y. %H:%M:%S.%f',  # '25. 10. 2006. 14:30:59.000200'
+    '%d. %m. %Y. %H:%M',        # '25. 10. 2006. 14:30'
+    '%d. %m. %Y.',              # '25. 10. 2006.'
+    '%d. %m. %y. %H:%M:%S',     # '25. 10. 06. 14:30:59'
+    '%d. %m. %y. %H:%M:%S.%f',  # '25. 10. 06. 14:30:59.000200'
+    '%d. %m. %y. %H:%M',        # '25. 10. 06. 14:30'
+    '%d. %m. %y.',              # '25. 10. 06.'
 )
 
 DECIMAL_SEPARATOR = ','
diff --git a/django/conf/locale/hu/formats.py b/django/conf/locale/hu/formats.py
index 9b6630d775..7e499da4ee 100644
--- a/django/conf/locale/hu/formats.py
+++ b/django/conf/locale/hu/formats.py
@@ -12,23 +12,23 @@ YEAR_MONTH_FORMAT = 'Y. F'
 MONTH_DAY_FORMAT = 'F j.'
 SHORT_DATE_FORMAT = 'Y.m.d.'
 SHORT_DATETIME_FORMAT = 'Y.m.d. G.i.s'
-FIRST_DAY_OF_WEEK = 1 # Monday
+FIRST_DAY_OF_WEEK = 1  # Monday
 
 # The *_INPUT_FORMATS strings use the Python strftime format syntax,
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
 DATE_INPUT_FORMATS = (
-    '%Y.%m.%d.', # '2006.10.25.'
+    '%Y.%m.%d.',  # '2006.10.25.'
 )
 TIME_INPUT_FORMATS = (
-    '%H.%M.%S', # '14.30.59'
+    '%H.%M.%S',  # '14.30.59'
     '%H.%M',    # '14.30'
 )
 DATETIME_INPUT_FORMATS = (
     '%Y.%m.%d. %H.%M.%S',   # '2006.10.25. 14.30.59'
-    '%Y.%m.%d. %H.%M.%S.%f', # '2006.10.25. 14.30.59.000200'
+    '%Y.%m.%d. %H.%M.%S.%f',  # '2006.10.25. 14.30.59.000200'
     '%Y.%m.%d. %H.%M',      # '2006.10.25. 14.30'
     '%Y.%m.%d.',            # '2006.10.25.'
 )
 DECIMAL_SEPARATOR = ','
-THOUSAND_SEPARATOR = ' ' # Non-breaking space
+THOUSAND_SEPARATOR = ' '  # Non-breaking space
 NUMBER_GROUPING = 3
diff --git a/django/conf/locale/it/formats.py b/django/conf/locale/it/formats.py
index b12e478ccb..368535d293 100644
--- a/django/conf/locale/it/formats.py
+++ b/django/conf/locale/it/formats.py
@@ -5,14 +5,14 @@ from __future__ import unicode_literals
 
 # The *_FORMAT strings use the Django date format syntax,
 # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
-DATE_FORMAT = 'd F Y' # 25 Ottobre 2006
-TIME_FORMAT = 'H:i:s' # 14:30:59
-DATETIME_FORMAT = 'l d F Y H:i:s' # MercoledƬ 25 Ottobre 2006 14:30:59
-YEAR_MONTH_FORMAT = 'F Y' # Ottobre 2006
-MONTH_DAY_FORMAT = 'j/F' # 10/2006
-SHORT_DATE_FORMAT = 'd/m/Y' # 25/12/2009
-SHORT_DATETIME_FORMAT = 'd/m/Y H:i:s' # 25/10/2009 14:30:59
-FIRST_DAY_OF_WEEK = 1 # LunedƬ
+DATE_FORMAT = 'd F Y'  # 25 Ottobre 2006
+TIME_FORMAT = 'H:i:s'  # 14:30:59
+DATETIME_FORMAT = 'l d F Y H:i:s'  # MercoledƬ 25 Ottobre 2006 14:30:59
+YEAR_MONTH_FORMAT = 'F Y'  # Ottobre 2006
+MONTH_DAY_FORMAT = 'j/F'  # 10/2006
+SHORT_DATE_FORMAT = 'd/m/Y'  # 25/12/2009
+SHORT_DATETIME_FORMAT = 'd/m/Y H:i:s'  # 25/10/2009 14:30:59
+FIRST_DAY_OF_WEEK = 1  # LunedƬ
 
 # The *_INPUT_FORMATS strings use the Python strftime format syntax,
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
diff --git a/django/conf/locale/ka/formats.py b/django/conf/locale/ka/formats.py
index bb26bec6be..1d2eb5f9cb 100644
--- a/django/conf/locale/ka/formats.py
+++ b/django/conf/locale/ka/formats.py
@@ -12,7 +12,7 @@ YEAR_MONTH_FORMAT = 'F, Y'
 MONTH_DAY_FORMAT = 'j F'
 SHORT_DATE_FORMAT = 'j.M.Y'
 SHORT_DATETIME_FORMAT = 'j.M.Y H:i:s'
-FIRST_DAY_OF_WEEK = 1 # (Monday)
+FIRST_DAY_OF_WEEK = 1  # (Monday)
 
 # The *_INPUT_FORMATS strings use the Python strftime format syntax,
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
diff --git a/django/conf/locale/ko/formats.py b/django/conf/locale/ko/formats.py
index 28b4d06ca2..29e57f136c 100644
--- a/django/conf/locale/ko/formats.py
+++ b/django/conf/locale/ko/formats.py
@@ -18,7 +18,7 @@ SHORT_DATETIME_FORMAT = 'Y-n-j H:i'
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
 # Kept ISO formats as they are in first position
 DATE_INPUT_FORMATS = (
-    '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
+    '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y',  # '2006-10-25', '10/25/2006', '10/25/06'
     # '%b %d %Y', '%b %d, %Y',            # 'Oct 25 2006', 'Oct 25, 2006'
     # '%d %b %Y', '%d %b, %Y',            # '25 Oct 2006', '25 Oct, 2006'
     # '%B %d %Y', '%B %d, %Y',            # 'October 25 2006', 'October 25, 2006'
diff --git a/django/conf/locale/lt/formats.py b/django/conf/locale/lt/formats.py
index 1bff4d9861..41dab5f53b 100644
--- a/django/conf/locale/lt/formats.py
+++ b/django/conf/locale/lt/formats.py
@@ -17,7 +17,7 @@ FIRST_DAY_OF_WEEK = 1  # Monday
 # The *_INPUT_FORMATS strings use the Python strftime format syntax,
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
 DATE_INPUT_FORMATS = (
-    '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06'
+    '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y',  # '2006-10-25', '25.10.2006', '25.10.06'
 )
 TIME_INPUT_FORMATS = (
     '%H:%M:%S',     # '14:30:59'
diff --git a/django/conf/locale/lv/formats.py b/django/conf/locale/lv/formats.py
index c2c9f9da37..2b281d810f 100644
--- a/django/conf/locale/lv/formats.py
+++ b/django/conf/locale/lv/formats.py
@@ -18,7 +18,7 @@ FIRST_DAY_OF_WEEK = 1  # Monday
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
 # Kept ISO formats as they are in first position
 DATE_INPUT_FORMATS = (
-    '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06'
+    '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y',  # '2006-10-25', '25.10.2006', '25.10.06'
 )
 TIME_INPUT_FORMATS = (
     '%H:%M:%S',     # '14:30:59'
@@ -45,5 +45,5 @@ DATETIME_INPUT_FORMATS = (
     '%d.%m.%y',              # '25.10.06'
 )
 DECIMAL_SEPARATOR = ','
-THOUSAND_SEPARATOR = ' ' # Non-breaking space
+THOUSAND_SEPARATOR = ' '  # Non-breaking space
 NUMBER_GROUPING = 3
diff --git a/django/conf/locale/mk/formats.py b/django/conf/locale/mk/formats.py
index 2a0df6c43f..fe33070786 100644
--- a/django/conf/locale/mk/formats.py
+++ b/django/conf/locale/mk/formats.py
@@ -22,22 +22,22 @@ DATE_INPUT_FORMATS = (
 )
 
 DATETIME_INPUT_FORMATS = (
-    '%d.%m.%Y. %H:%M:%S',     # '25.10.2006. 14:30:59'
-    '%d.%m.%Y. %H:%M:%S.%f',  # '25.10.2006. 14:30:59.000200'
-    '%d.%m.%Y. %H:%M',        # '25.10.2006. 14:30'
-    '%d.%m.%Y.',              # '25.10.2006.'
-    '%d.%m.%y. %H:%M:%S',     # '25.10.06. 14:30:59'
-    '%d.%m.%y. %H:%M:%S.%f',  # '25.10.06. 14:30:59.000200'
-    '%d.%m.%y. %H:%M',        # '25.10.06. 14:30'
-    '%d.%m.%y.',              # '25.10.06.'
-    '%d. %m. %Y. %H:%M:%S',   # '25. 10. 2006. 14:30:59'
-    '%d. %m. %Y. %H:%M:%S.%f', # '25. 10. 2006. 14:30:59.000200'
-    '%d. %m. %Y. %H:%M',      # '25. 10. 2006. 14:30'
-    '%d. %m. %Y.',            # '25. 10. 2006.'
-    '%d. %m. %y. %H:%M:%S',   # '25. 10. 06. 14:30:59'
-    '%d. %m. %y. %H:%M:%S.%f', # '25. 10. 06. 14:30:59.000200'
-    '%d. %m. %y. %H:%M',      # '25. 10. 06. 14:30'
-    '%d. %m. %y.',            # '25. 10. 06.'
+    '%d.%m.%Y. %H:%M:%S',       # '25.10.2006. 14:30:59'
+    '%d.%m.%Y. %H:%M:%S.%f',    # '25.10.2006. 14:30:59.000200'
+    '%d.%m.%Y. %H:%M',          # '25.10.2006. 14:30'
+    '%d.%m.%Y.',                # '25.10.2006.'
+    '%d.%m.%y. %H:%M:%S',       # '25.10.06. 14:30:59'
+    '%d.%m.%y. %H:%M:%S.%f',    # '25.10.06. 14:30:59.000200'
+    '%d.%m.%y. %H:%M',          # '25.10.06. 14:30'
+    '%d.%m.%y.',                # '25.10.06.'
+    '%d. %m. %Y. %H:%M:%S',     # '25. 10. 2006. 14:30:59'
+    '%d. %m. %Y. %H:%M:%S.%f',  # '25. 10. 2006. 14:30:59.000200'
+    '%d. %m. %Y. %H:%M',        # '25. 10. 2006. 14:30'
+    '%d. %m. %Y.',              # '25. 10. 2006.'
+    '%d. %m. %y. %H:%M:%S',     # '25. 10. 06. 14:30:59'
+    '%d. %m. %y. %H:%M:%S.%f',  # '25. 10. 06. 14:30:59.000200'
+    '%d. %m. %y. %H:%M',        # '25. 10. 06. 14:30'
+    '%d. %m. %y.',              # '25. 10. 06.'
 )
 
 DECIMAL_SEPARATOR = ','
diff --git a/django/conf/locale/ml/formats.py b/django/conf/locale/ml/formats.py
index 5accf9e3d2..279cd3c518 100644
--- a/django/conf/locale/ml/formats.py
+++ b/django/conf/locale/ml/formats.py
@@ -12,13 +12,13 @@ YEAR_MONTH_FORMAT = 'F Y'
 MONTH_DAY_FORMAT = 'F j'
 SHORT_DATE_FORMAT = 'm/d/Y'
 SHORT_DATETIME_FORMAT = 'm/d/Y P'
-FIRST_DAY_OF_WEEK = 0 # Sunday
+FIRST_DAY_OF_WEEK = 0  # Sunday
 
 # The *_INPUT_FORMATS strings use the Python strftime format syntax,
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
 # Kept ISO formats as they are in first position
 DATE_INPUT_FORMATS = (
-    '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
+    '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y',  # '2006-10-25', '10/25/2006', '10/25/06'
     # '%b %d %Y', '%b %d, %Y',            # 'Oct 25 2006', 'Oct 25, 2006'
     # '%d %b %Y', '%d %b, %Y',            # '25 Oct 2006', '25 Oct, 2006'
     # '%B %d %Y', '%B %d, %Y',            # 'October 25 2006', 'October 25, 2006'
diff --git a/django/conf/locale/nb/formats.py b/django/conf/locale/nb/formats.py
index 8f976d7045..5bf43af0d4 100644
--- a/django/conf/locale/nb/formats.py
+++ b/django/conf/locale/nb/formats.py
@@ -12,13 +12,13 @@ YEAR_MONTH_FORMAT = 'F Y'
 MONTH_DAY_FORMAT = 'j. F'
 SHORT_DATE_FORMAT = 'd.m.Y'
 SHORT_DATETIME_FORMAT = 'd.m.Y H:i'
-FIRST_DAY_OF_WEEK = 1 # Monday
+FIRST_DAY_OF_WEEK = 1  # Monday
 
 # The *_INPUT_FORMATS strings use the Python strftime format syntax,
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
 # Kept ISO formats as they are in first position
 DATE_INPUT_FORMATS = (
-    '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06'
+    '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y',  # '2006-10-25', '25.10.2006', '25.10.06'
     # '%d. %b %Y', '%d %b %Y',            # '25. okt 2006', '25 okt 2006'
     # '%d. %b. %Y', '%d %b. %Y',          # '25. okt. 2006', '25 okt. 2006'
     # '%d. %B %Y', '%d %B %Y',            # '25. oktober 2006', '25 oktober 2006'
@@ -38,5 +38,5 @@ DATETIME_INPUT_FORMATS = (
     '%d.%m.%y',              # '25.10.06'
 )
 DECIMAL_SEPARATOR = ','
-THOUSAND_SEPARATOR = '\xa0' # non-breaking space
+THOUSAND_SEPARATOR = '\xa0'  # non-breaking space
 NUMBER_GROUPING = 3
diff --git a/django/conf/locale/nn/formats.py b/django/conf/locale/nn/formats.py
index 528ae30107..ca7d2e294c 100644
--- a/django/conf/locale/nn/formats.py
+++ b/django/conf/locale/nn/formats.py
@@ -12,13 +12,13 @@ YEAR_MONTH_FORMAT = 'F Y'
 MONTH_DAY_FORMAT = 'j. F'
 SHORT_DATE_FORMAT = 'd.m.Y'
 SHORT_DATETIME_FORMAT = 'd.m.Y H:i'
-FIRST_DAY_OF_WEEK = 1 # Monday
+FIRST_DAY_OF_WEEK = 1  # Monday
 
 # The *_INPUT_FORMATS strings use the Python strftime format syntax,
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
 # Kept ISO formats as they are in first position
 DATE_INPUT_FORMATS = (
-    '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06'
+    '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y',  # '2006-10-25', '25.10.2006', '25.10.06'
     # '%d. %b %Y', '%d %b %Y',            # '25. okt 2006', '25 okt 2006'
     # '%d. %b. %Y', '%d %b. %Y',          # '25. okt. 2006', '25 okt. 2006'
     # '%d. %B %Y', '%d %B %Y',            # '25. oktober 2006', '25 oktober 2006'
@@ -39,5 +39,5 @@ DATETIME_INPUT_FORMATS = (
     '%d.%m.%y',              # '25.10.06'
 )
 DECIMAL_SEPARATOR = ','
-THOUSAND_SEPARATOR = '\xa0' # non-breaking space
+THOUSAND_SEPARATOR = '\xa0'  # non-breaking space
 NUMBER_GROUPING = 3
diff --git a/django/conf/locale/pl/formats.py b/django/conf/locale/pl/formats.py
index 25cfc793cf..5997839477 100644
--- a/django/conf/locale/pl/formats.py
+++ b/django/conf/locale/pl/formats.py
@@ -12,7 +12,7 @@ YEAR_MONTH_FORMAT = 'F Y'
 MONTH_DAY_FORMAT = 'j F'
 SHORT_DATE_FORMAT = 'd-m-Y'
 SHORT_DATETIME_FORMAT = 'd-m-Y  H:i:s'
-FIRST_DAY_OF_WEEK = 1 # Monday
+FIRST_DAY_OF_WEEK = 1  # Monday
 
 # The *_INPUT_FORMATS strings use the Python strftime format syntax,
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
@@ -22,10 +22,10 @@ DATE_INPUT_FORMATS = (
     # '%d. %B %Y', '%d. %b. %Y',  # '25. October 2006', '25. Oct. 2006'
 )
 DATETIME_INPUT_FORMATS = (
-    '%d.%m.%Y %H:%M:%S',    # '25.10.2006 14:30:59'
-    '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200'
-    '%d.%m.%Y %H:%M',       # '25.10.2006 14:30'
-    '%d.%m.%Y',             # '25.10.2006'
+    '%d.%m.%Y %H:%M:%S',     # '25.10.2006 14:30:59'
+    '%d.%m.%Y %H:%M:%S.%f',  # '25.10.2006 14:30:59.000200'
+    '%d.%m.%Y %H:%M',        # '25.10.2006 14:30'
+    '%d.%m.%Y',              # '25.10.2006'
 )
 DECIMAL_SEPARATOR = ','
 THOUSAND_SEPARATOR = ' '
diff --git a/django/conf/locale/pt/formats.py b/django/conf/locale/pt/formats.py
index 9452428dd9..6141176760 100644
--- a/django/conf/locale/pt/formats.py
+++ b/django/conf/locale/pt/formats.py
@@ -18,7 +18,7 @@ FIRST_DAY_OF_WEEK = 0  # Sunday
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
 # Kept ISO formats as they are in first position
 DATE_INPUT_FORMATS = (
-    '%Y-%m-%d', '%d/%m/%Y', '%d/%m/%y', # '2006-10-25', '25/10/2006', '25/10/06'
+    '%Y-%m-%d', '%d/%m/%Y', '%d/%m/%y',   # '2006-10-25', '25/10/2006', '25/10/06'
     # '%d de %b de %Y', '%d de %b, %Y',   # '25 de Out de 2006', '25 Out, 2006'
     # '%d de %B de %Y', '%d de %B, %Y',   # '25 de Outubro de 2006', '25 de Outubro, 2006'
 )
diff --git a/django/conf/locale/pt_BR/formats.py b/django/conf/locale/pt_BR/formats.py
index a5ec333d50..6057a21056 100644
--- a/django/conf/locale/pt_BR/formats.py
+++ b/django/conf/locale/pt_BR/formats.py
@@ -17,7 +17,7 @@ FIRST_DAY_OF_WEEK = 0  # Sunday
 # The *_INPUT_FORMATS strings use the Python strftime format syntax,
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
 DATE_INPUT_FORMATS = (
-    '%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06'
+    '%d/%m/%Y', '%d/%m/%y',  # '25/10/2006', '25/10/06'
     # '%d de %b de %Y', '%d de %b, %Y',   # '25 de Out de 2006', '25 Out, 2006'
     # '%d de %B de %Y', '%d de %B, %Y',   # '25 de Outubro de 2006', '25 de Outubro, 2006'
 )
diff --git a/django/conf/locale/ru/formats.py b/django/conf/locale/ru/formats.py
index 413ce2788b..2cc5001c6a 100644
--- a/django/conf/locale/ru/formats.py
+++ b/django/conf/locale/ru/formats.py
@@ -21,15 +21,15 @@ DATE_INPUT_FORMATS = (
     '%d.%m.%y',  # '25.10.06'
 )
 DATETIME_INPUT_FORMATS = (
-    '%d.%m.%Y %H:%M:%S',  # '25.10.2006 14:30:59'
-    '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200'
-    '%d.%m.%Y %H:%M',     # '25.10.2006 14:30'
-    '%d.%m.%Y',           # '25.10.2006'
-    '%d.%m.%y %H:%M:%S',  # '25.10.06 14:30:59'
-    '%d.%m.%y %H:%M:%S.%f', # '25.10.06 14:30:59.000200'
-    '%d.%m.%y %H:%M',     # '25.10.06 14:30'
-    '%d.%m.%y',           # '25.10.06'
+    '%d.%m.%Y %H:%M:%S',     # '25.10.2006 14:30:59'
+    '%d.%m.%Y %H:%M:%S.%f',  # '25.10.2006 14:30:59.000200'
+    '%d.%m.%Y %H:%M',        # '25.10.2006 14:30'
+    '%d.%m.%Y',              # '25.10.2006'
+    '%d.%m.%y %H:%M:%S',     # '25.10.06 14:30:59'
+    '%d.%m.%y %H:%M:%S.%f',  # '25.10.06 14:30:59.000200'
+    '%d.%m.%y %H:%M',        # '25.10.06 14:30'
+    '%d.%m.%y',              # '25.10.06'
 )
 DECIMAL_SEPARATOR = ','
-THOUSAND_SEPARATOR = '\xa0' # non-breaking space
+THOUSAND_SEPARATOR = '\xa0'  # non-breaking space
 NUMBER_GROUPING = 3
diff --git a/django/conf/locale/sk/formats.py b/django/conf/locale/sk/formats.py
index 6ff8ca791b..dfbd1a681f 100644
--- a/django/conf/locale/sk/formats.py
+++ b/django/conf/locale/sk/formats.py
@@ -12,7 +12,7 @@ YEAR_MONTH_FORMAT = 'F Y'
 MONTH_DAY_FORMAT = 'j. F'
 SHORT_DATE_FORMAT = 'd.m.Y'
 SHORT_DATETIME_FORMAT = 'd.m.Y G:i:s'
-FIRST_DAY_OF_WEEK = 1 # Monday
+FIRST_DAY_OF_WEEK = 1  # Monday
 
 # The *_INPUT_FORMATS strings use the Python strftime format syntax,
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
@@ -22,11 +22,11 @@ DATE_INPUT_FORMATS = (
     # '%d. %B %Y', '%d. %b. %Y',  # '25. October 2006', '25. Oct. 2006'
 )
 DATETIME_INPUT_FORMATS = (
-    '%d.%m.%Y %H:%M:%S',    # '25.10.2006 14:30:59'
-    '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200'
-    '%d.%m.%Y %H:%M',       # '25.10.2006 14:30'
-    '%d.%m.%Y',             # '25.10.2006'
+    '%d.%m.%Y %H:%M:%S',     # '25.10.2006 14:30:59'
+    '%d.%m.%Y %H:%M:%S.%f',  # '25.10.2006 14:30:59.000200'
+    '%d.%m.%Y %H:%M',        # '25.10.2006 14:30'
+    '%d.%m.%Y',              # '25.10.2006'
 )
 DECIMAL_SEPARATOR = ','
-THOUSAND_SEPARATOR = '\xa0' # non-breaking space
+THOUSAND_SEPARATOR = '\xa0'  # non-breaking space
 NUMBER_GROUPING = 3
diff --git a/django/conf/locale/sr/formats.py b/django/conf/locale/sr/formats.py
index 8e9e9a487e..86d63e42f1 100644
--- a/django/conf/locale/sr/formats.py
+++ b/django/conf/locale/sr/formats.py
@@ -24,22 +24,22 @@ DATE_INPUT_FORMATS = (
     # '%d. %b %Y.', '%d. %B %Y.',     # '25. Oct 2006.', '25. October 2006.'
 )
 DATETIME_INPUT_FORMATS = (
-    '%d.%m.%Y. %H:%M:%S',     # '25.10.2006. 14:30:59'
-    '%d.%m.%Y. %H:%M:%S.%f',  # '25.10.2006. 14:30:59.000200'
-    '%d.%m.%Y. %H:%M',        # '25.10.2006. 14:30'
-    '%d.%m.%Y.',              # '25.10.2006.'
-    '%d.%m.%y. %H:%M:%S',     # '25.10.06. 14:30:59'
-    '%d.%m.%y. %H:%M:%S.%f',  # '25.10.06. 14:30:59.000200'
-    '%d.%m.%y. %H:%M',        # '25.10.06. 14:30'
-    '%d.%m.%y.',              # '25.10.06.'
-    '%d. %m. %Y. %H:%M:%S',   # '25. 10. 2006. 14:30:59'
-    '%d. %m. %Y. %H:%M:%S.%f', # '25. 10. 2006. 14:30:59.000200'
-    '%d. %m. %Y. %H:%M',      # '25. 10. 2006. 14:30'
-    '%d. %m. %Y.',            # '25. 10. 2006.'
-    '%d. %m. %y. %H:%M:%S',   # '25. 10. 06. 14:30:59'
-    '%d. %m. %y. %H:%M:%S.%f', # '25. 10. 06. 14:30:59.000200'
-    '%d. %m. %y. %H:%M',      # '25. 10. 06. 14:30'
-    '%d. %m. %y.',            # '25. 10. 06.'
+    '%d.%m.%Y. %H:%M:%S',       # '25.10.2006. 14:30:59'
+    '%d.%m.%Y. %H:%M:%S.%f',    # '25.10.2006. 14:30:59.000200'
+    '%d.%m.%Y. %H:%M',          # '25.10.2006. 14:30'
+    '%d.%m.%Y.',                # '25.10.2006.'
+    '%d.%m.%y. %H:%M:%S',       # '25.10.06. 14:30:59'
+    '%d.%m.%y. %H:%M:%S.%f',    # '25.10.06. 14:30:59.000200'
+    '%d.%m.%y. %H:%M',          # '25.10.06. 14:30'
+    '%d.%m.%y.',                # '25.10.06.'
+    '%d. %m. %Y. %H:%M:%S',     # '25. 10. 2006. 14:30:59'
+    '%d. %m. %Y. %H:%M:%S.%f',  # '25. 10. 2006. 14:30:59.000200'
+    '%d. %m. %Y. %H:%M',        # '25. 10. 2006. 14:30'
+    '%d. %m. %Y.',              # '25. 10. 2006.'
+    '%d. %m. %y. %H:%M:%S',     # '25. 10. 06. 14:30:59'
+    '%d. %m. %y. %H:%M:%S.%f',  # '25. 10. 06. 14:30:59.000200'
+    '%d. %m. %y. %H:%M',        # '25. 10. 06. 14:30'
+    '%d. %m. %y.',              # '25. 10. 06.'
 )
 DECIMAL_SEPARATOR = ','
 THOUSAND_SEPARATOR = '.'
diff --git a/django/conf/locale/sr_Latn/formats.py b/django/conf/locale/sr_Latn/formats.py
index 8e9e9a487e..86d63e42f1 100644
--- a/django/conf/locale/sr_Latn/formats.py
+++ b/django/conf/locale/sr_Latn/formats.py
@@ -24,22 +24,22 @@ DATE_INPUT_FORMATS = (
     # '%d. %b %Y.', '%d. %B %Y.',     # '25. Oct 2006.', '25. October 2006.'
 )
 DATETIME_INPUT_FORMATS = (
-    '%d.%m.%Y. %H:%M:%S',     # '25.10.2006. 14:30:59'
-    '%d.%m.%Y. %H:%M:%S.%f',  # '25.10.2006. 14:30:59.000200'
-    '%d.%m.%Y. %H:%M',        # '25.10.2006. 14:30'
-    '%d.%m.%Y.',              # '25.10.2006.'
-    '%d.%m.%y. %H:%M:%S',     # '25.10.06. 14:30:59'
-    '%d.%m.%y. %H:%M:%S.%f',  # '25.10.06. 14:30:59.000200'
-    '%d.%m.%y. %H:%M',        # '25.10.06. 14:30'
-    '%d.%m.%y.',              # '25.10.06.'
-    '%d. %m. %Y. %H:%M:%S',   # '25. 10. 2006. 14:30:59'
-    '%d. %m. %Y. %H:%M:%S.%f', # '25. 10. 2006. 14:30:59.000200'
-    '%d. %m. %Y. %H:%M',      # '25. 10. 2006. 14:30'
-    '%d. %m. %Y.',            # '25. 10. 2006.'
-    '%d. %m. %y. %H:%M:%S',   # '25. 10. 06. 14:30:59'
-    '%d. %m. %y. %H:%M:%S.%f', # '25. 10. 06. 14:30:59.000200'
-    '%d. %m. %y. %H:%M',      # '25. 10. 06. 14:30'
-    '%d. %m. %y.',            # '25. 10. 06.'
+    '%d.%m.%Y. %H:%M:%S',       # '25.10.2006. 14:30:59'
+    '%d.%m.%Y. %H:%M:%S.%f',    # '25.10.2006. 14:30:59.000200'
+    '%d.%m.%Y. %H:%M',          # '25.10.2006. 14:30'
+    '%d.%m.%Y.',                # '25.10.2006.'
+    '%d.%m.%y. %H:%M:%S',       # '25.10.06. 14:30:59'
+    '%d.%m.%y. %H:%M:%S.%f',    # '25.10.06. 14:30:59.000200'
+    '%d.%m.%y. %H:%M',          # '25.10.06. 14:30'
+    '%d.%m.%y.',                # '25.10.06.'
+    '%d. %m. %Y. %H:%M:%S',     # '25. 10. 2006. 14:30:59'
+    '%d. %m. %Y. %H:%M:%S.%f',  # '25. 10. 2006. 14:30:59.000200'
+    '%d. %m. %Y. %H:%M',        # '25. 10. 2006. 14:30'
+    '%d. %m. %Y.',              # '25. 10. 2006.'
+    '%d. %m. %y. %H:%M:%S',     # '25. 10. 06. 14:30:59'
+    '%d. %m. %y. %H:%M:%S.%f',  # '25. 10. 06. 14:30:59.000200'
+    '%d. %m. %y. %H:%M',        # '25. 10. 06. 14:30'
+    '%d. %m. %y.',              # '25. 10. 06.'
 )
 DECIMAL_SEPARATOR = ','
 THOUSAND_SEPARATOR = '.'
diff --git a/django/conf/locale/sv/formats.py b/django/conf/locale/sv/formats.py
index 8874da7519..7673d472a1 100644
--- a/django/conf/locale/sv/formats.py
+++ b/django/conf/locale/sv/formats.py
@@ -37,5 +37,5 @@ DATETIME_INPUT_FORMATS = (
     '%m/%d/%y',              # '10/25/06'
 )
 DECIMAL_SEPARATOR = ','
-THOUSAND_SEPARATOR = '\xa0' # non-breaking space
+THOUSAND_SEPARATOR = '\xa0'  # non-breaking space
 NUMBER_GROUPING = 3
diff --git a/django/conf/locale/tr/formats.py b/django/conf/locale/tr/formats.py
index 395fca9114..175def1956 100644
--- a/django/conf/locale/tr/formats.py
+++ b/django/conf/locale/tr/formats.py
@@ -12,7 +12,7 @@ YEAR_MONTH_FORMAT = 'F Y'
 MONTH_DAY_FORMAT = 'd F'
 SHORT_DATE_FORMAT = 'd M Y'
 SHORT_DATETIME_FORMAT = 'd M Y H:i:s'
-FIRST_DAY_OF_WEEK = 1 # Pazartesi
+FIRST_DAY_OF_WEEK = 1  # Pazartesi
 
 # The *_INPUT_FORMATS strings use the Python strftime format syntax,
 # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
@@ -22,10 +22,10 @@ DATE_INPUT_FORMATS = (
     # '%d %B %Y', '%d %b. %Y',  # '25 Ekim 2006', '25 Eki. 2006'
 )
 DATETIME_INPUT_FORMATS = (
-    '%d/%m/%Y %H:%M:%S',    # '25/10/2006 14:30:59'
-    '%d/%m/%Y %H:%M:%S.%f', # '25/10/2006 14:30:59.000200'
-    '%d/%m/%Y %H:%M',       # '25/10/2006 14:30'
-    '%d/%m/%Y',             # '25/10/2006'
+    '%d/%m/%Y %H:%M:%S',     # '25/10/2006 14:30:59'
+    '%d/%m/%Y %H:%M:%S.%f',  # '25/10/2006 14:30:59.000200'
+    '%d/%m/%Y %H:%M',        # '25/10/2006 14:30'
+    '%d/%m/%Y',              # '25/10/2006'
 )
 DECIMAL_SEPARATOR = ','
 THOUSAND_SEPARATOR = '.'
diff --git a/django/contrib/admin/helpers.py b/django/contrib/admin/helpers.py
index ee38fdf1d5..012a14ef64 100644
--- a/django/contrib/admin/helpers.py
+++ b/django/contrib/admin/helpers.py
@@ -83,7 +83,7 @@ class Fieldset(object):
 
 class Fieldline(object):
     def __init__(self, form, field, readonly_fields=None, model_admin=None):
-        self.form = form # A django.forms.Form instance
+        self.form = form  # A django.forms.Form instance
         if not hasattr(field, "__iter__") or isinstance(field, six.text_type):
             self.fields = [field]
         else:
@@ -110,8 +110,8 @@ class Fieldline(object):
 
 class AdminField(object):
     def __init__(self, form, field, is_first):
-        self.field = form[field] # A django.forms.BoundField instance
-        self.is_first = is_first # Whether this field is first on the line
+        self.field = form[field]  # A django.forms.BoundField instance
+        self.is_first = is_first  # Whether this field is first on the line
         self.is_checkbox = isinstance(self.field.field.widget, forms.CheckboxInput)
 
     def label_tag(self):
diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py
index e3514dd82a..6ab842dd61 100644
--- a/django/contrib/admin/options.py
+++ b/django/contrib/admin/options.py
@@ -1033,7 +1033,7 @@ class ModelAdmin(BaseModelAdmin):
                 attr = obj._meta.pk.attname
             value = obj.serializable_value(attr)
             return SimpleTemplateResponse('admin/popup_response.html', {
-                'pk_value': escape(pk_value), # for possible backwards-compatibility
+                'pk_value': escape(pk_value),  # for possible backwards-compatibility
                 'value': escape(value),
                 'obj': escapejs(obj)
             })
diff --git a/django/contrib/admin/templatetags/admin_list.py b/django/contrib/admin/templatetags/admin_list.py
index 0b48cb0851..e75f1a2a60 100644
--- a/django/contrib/admin/templatetags/admin_list.py
+++ b/django/contrib/admin/templatetags/admin_list.py
@@ -136,13 +136,13 @@ def result_headers(cl):
             new_order_type = {'asc': 'desc', 'desc': 'asc'}[order_type]
 
         # build new ordering param
-        o_list_primary = [] # URL for making this field the primary sort
-        o_list_remove = [] # URL for removing this field from sort
-        o_list_toggle = [] # URL for toggling order type for this field
+        o_list_primary = []  # URL for making this field the primary sort
+        o_list_remove = []  # URL for removing this field from sort
+        o_list_toggle = []  # URL for toggling order type for this field
         make_qs_param = lambda t, n: ('-' if t == 'desc' else '') + str(n)
 
         for j, ot in ordering_field_columns.items():
-            if j == i: # Same column
+            if j == i:  # Same column
                 param = make_qs_param(new_order_type, j)
                 # We want clicking on this header to bring the ordering to the
                 # front
diff --git a/django/contrib/admin/templatetags/admin_modify.py b/django/contrib/admin/templatetags/admin_modify.py
index 7665176228..c4ce53fec0 100644
--- a/django/contrib/admin/templatetags/admin_modify.py
+++ b/django/contrib/admin/templatetags/admin_modify.py
@@ -49,7 +49,7 @@ def submit_row(context):
 @register.filter
 def cell_count(inline_admin_form):
     """Returns the number of cells used in a tabular inline"""
-    count = 1 # Hidden cell with hidden 'id' field
+    count = 1  # Hidden cell with hidden 'id' field
     for fieldset in inline_admin_form:
         # Loop through all the fields (one per cell)
         for line in fieldset:
diff --git a/django/contrib/admin/utils.py b/django/contrib/admin/utils.py
index 2242f7de58..ed3668907a 100644
--- a/django/contrib/admin/utils.py
+++ b/django/contrib/admin/utils.py
@@ -154,7 +154,7 @@ def get_deleted_objects(objs, opts, user, admin_site, using):
 class NestedObjects(Collector):
     def __init__(self, *args, **kwargs):
         super(NestedObjects, self).__init__(*args, **kwargs)
-        self.edges = {} # {from_instance: [to_instances]}
+        self.edges = {}  # {from_instance: [to_instances]}
         self.protected = set()
 
     def add_edge(self, source, target):
@@ -391,7 +391,7 @@ class NotRelationField(Exception):
 def get_model_from_relation(field):
     if isinstance(field, models.related.RelatedObject):
         return field.model
-    elif getattr(field, 'rel'): # or isinstance?
+    elif getattr(field, 'rel'):  # or isinstance?
         return field.rel.to
     else:
         raise NotRelationField
@@ -412,7 +412,7 @@ def reverse_field_path(model, path):
     for piece in pieces:
         field, model, direct, m2m = parent._meta.get_field_by_name(piece)
         # skip trailing data field if extant:
-        if len(reversed_path) == len(pieces)-1: # final iteration
+        if len(reversed_path) == len(pieces)-1:  # final iteration
             try:
                 get_model_from_relation(field)
             except NotRelationField:
@@ -469,8 +469,8 @@ def get_limit_choices_to_from_path(model, path):
         fields and hasattr(fields[-1], 'rel') and
         getattr(fields[-1].rel, 'limit_choices_to', None))
     if not limit_choices_to:
-        return models.Q() # empty Q
+        return models.Q()  # empty Q
     elif isinstance(limit_choices_to, models.Q):
-        return limit_choices_to # already a Q
+        return limit_choices_to  # already a Q
     else:
-        return models.Q(**limit_choices_to) # convert dict to Q
+        return models.Q(**limit_choices_to)  # convert dict to Q
diff --git a/django/contrib/admin/validation.py b/django/contrib/admin/validation.py
index 12b3bdb211..b2cb0b4181 100644
--- a/django/contrib/admin/validation.py
+++ b/django/contrib/admin/validation.py
@@ -70,7 +70,7 @@ class BaseValidator(object):
     def validate_fields(self, cls, model):
         " Validate that fields only refer to existing fields, doesn't contain duplicates. "
         # fields
-        if cls.fields: # default value is None
+        if cls.fields:  # default value is None
             check_isseq(cls, 'fields', cls.fields)
             self.check_field_spec(cls, model, cls.fields, 'fields')
             if cls.fieldsets:
@@ -81,7 +81,7 @@ class BaseValidator(object):
     def validate_fieldsets(self, cls, model):
         " Validate that fieldsets is properly formatted and doesn't contain duplicates. "
         from django.contrib.admin.options import flatten_fieldsets
-        if cls.fieldsets: # default value is None
+        if cls.fieldsets:  # default value is None
             check_isseq(cls, 'fieldsets', cls.fieldsets)
             for idx, fieldset in enumerate(cls.fieldsets):
                 check_isseq(cls, 'fieldsets[%d]' % idx, fieldset)
@@ -100,7 +100,7 @@ class BaseValidator(object):
 
     def validate_exclude(self, cls, model):
         " Validate that exclude is a sequence without duplicates. "
-        if cls.exclude: # default value is None
+        if cls.exclude:  # default value is None
             check_isseq(cls, 'exclude', cls.exclude)
             if len(cls.exclude) > len(set(cls.exclude)):
                 raise ImproperlyConfigured('There are duplicate field(s) in %s.exclude' % cls.__name__)
@@ -384,7 +384,7 @@ class ModelAdminValidator(BaseValidator):
 class InlineValidator(BaseValidator):
     def validate_fk_name(self, cls, model):
         " Validate that fk_name refers to a ForeignKey. "
-        if cls.fk_name: # default value is None
+        if cls.fk_name:  # default value is None
             f = get_field(cls, model, 'fk_name', cls.fk_name)
             if not isinstance(f, models.ForeignKey):
                 raise ImproperlyConfigured("'%s.fk_name is not an instance of "
diff --git a/django/contrib/admin/views/main.py b/django/contrib/admin/views/main.py
index 04977eeef8..a0ffef90f4 100644
--- a/django/contrib/admin/views/main.py
+++ b/django/contrib/admin/views/main.py
@@ -130,7 +130,7 @@ class ChangeList(six.with_metaclass(RenameChangeListMethods)):
         """
         if not params:
             params = self.params
-        lookup_params = params.copy() # a dictionary of the query string
+        lookup_params = params.copy()  # a dictionary of the query string
         # Remove all the parameters that are globally and systematically
         # ignored.
         for ignored in IGNORED_PARAMS:
@@ -299,10 +299,10 @@ class ChangeList(six.with_metaclass(RenameChangeListMethods)):
                     field_name = self.list_display[int(idx)]
                     order_field = self.get_ordering_field(field_name)
                     if not order_field:
-                        continue # No 'admin_order_field', skip it
+                        continue  # No 'admin_order_field', skip it
                     ordering.append(pfx + order_field)
                 except (IndexError, ValueError):
-                    continue # Invalid ordering specified, skip it.
+                    continue  # Invalid ordering specified, skip it.
 
         # Add the given query's ordering fields, if any.
         ordering.extend(queryset.query.order_by)
@@ -347,7 +347,7 @@ class ChangeList(six.with_metaclass(RenameChangeListMethods)):
                 try:
                     idx = int(idx)
                 except ValueError:
-                    continue # skip it
+                    continue  # skip it
                 ordering_fields[idx] = 'desc' if pfx == '-' else 'asc'
         return ordering_fields
 
diff --git a/django/contrib/admin/widgets.py b/django/contrib/admin/widgets.py
index 0066f86b52..a17f875f40 100644
--- a/django/contrib/admin/widgets.py
+++ b/django/contrib/admin/widgets.py
@@ -164,7 +164,7 @@ class ForeignKeyRawIdWidget(forms.TextInput):
             else:
                 url = ''
             if "class" not in attrs:
-                attrs['class'] = 'vForeignKeyRawIdAdminField' # The JavaScript code looks for this hook.
+                attrs['class'] = 'vForeignKeyRawIdAdminField'  # The JavaScript code looks for this hook.
             # TODO: "lookup_id_" is hard-coded here. This should instead use
             # the correct API to determine the ID dynamically.
             extra.append('<a href="%s%s" class="related-lookup" id="lookup_id_%s" onclick="return showRelatedObjectLookupPopup(this);"> '
diff --git a/django/contrib/contenttypes/generic.py b/django/contrib/contenttypes/generic.py
index 10d3f7d4a5..26af7f0d3f 100644
--- a/django/contrib/contenttypes/generic.py
+++ b/django/contrib/contenttypes/generic.py
@@ -461,7 +461,7 @@ def generic_inlineformset_factory(model, form=ModelForm,
     ct_field = opts.get_field(ct_field)
     if not isinstance(ct_field, models.ForeignKey) or ct_field.rel.to != ContentType:
         raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field)
-    fk_field = opts.get_field(fk_field) # let the exception propagate
+    fk_field = opts.get_field(fk_field)  # let the exception propagate
     if exclude is not None:
         exclude = list(exclude)
         exclude.extend([ct_field.name, fk_field.name])
diff --git a/django/contrib/flatpages/middleware.py b/django/contrib/flatpages/middleware.py
index 2f494064f3..9fe595d0cf 100644
--- a/django/contrib/flatpages/middleware.py
+++ b/django/contrib/flatpages/middleware.py
@@ -6,7 +6,7 @@ from django.conf import settings
 class FlatpageFallbackMiddleware(object):
     def process_response(self, request, response):
         if response.status_code != 404:
-            return response # No need to check for a flatpage for non-404 responses.
+            return response  # No need to check for a flatpage for non-404 responses.
         try:
             return flatpage(request, request.path_info)
         # Return the original response if any errors happened. Because this
diff --git a/django/contrib/formtools/preview.py b/django/contrib/formtools/preview.py
index e7de911a8d..02e6f27547 100644
--- a/django/contrib/formtools/preview.py
+++ b/django/contrib/formtools/preview.py
@@ -8,7 +8,7 @@ from django.template.context import RequestContext
 from django.utils.crypto import constant_time_compare
 from django.contrib.formtools.utils import form_hmac
 
-AUTO_ID = 'formtools_%s' # Each form here uses this as its auto_id parameter.
+AUTO_ID = 'formtools_%s'  # Each form here uses this as its auto_id parameter.
 
 
 class FormPreview(object):
@@ -42,7 +42,7 @@ class FormPreview(object):
             try:
                 self.form.base_fields[name]
             except KeyError:
-                break # This field name isn't being used by the form.
+                break  # This field name isn't being used by the form.
             name += '_'
         return name
 
@@ -75,7 +75,7 @@ class FormPreview(object):
         if f.is_valid():
             if not self._check_security_hash(request.POST.get(self.unused_name('hash'), ''),
                                              request, f):
-                return self.failed_hash(request) # Security hash failed.
+                return self.failed_hash(request)  # Security hash failed.
             return self.done(request, f.cleaned_data)
         else:
             return render_to_response(self.form_template,
diff --git a/django/contrib/gis/db/backends/mysql/operations.py b/django/contrib/gis/db/backends/mysql/operations.py
index 26cec743a9..81aa1e2fb6 100644
--- a/django/contrib/gis/db/backends/mysql/operations.py
+++ b/django/contrib/gis/db/backends/mysql/operations.py
@@ -14,11 +14,11 @@ class MySQLOperations(DatabaseOperations, BaseSpatialOperations):
     from_text = 'GeomFromText'
 
     Adapter = WKTAdapter
-    Adaptor = Adapter # Backwards-compatibility alias.
+    Adaptor = Adapter  # Backwards-compatibility alias.
 
     geometry_functions = {
-        'bbcontains': 'MBRContains', # For consistency w/PostGIS API
-        'bboverlaps': 'MBROverlaps', # .. ..
+        'bbcontains': 'MBRContains',  # For consistency w/PostGIS API
+        'bboverlaps': 'MBROverlaps',  # .. ..
         'contained': 'MBRWithin',    # .. ..
         'contains': 'MBRContains',
         'disjoint': 'MBRDisjoint',
diff --git a/django/contrib/gis/db/backends/oracle/operations.py b/django/contrib/gis/db/backends/oracle/operations.py
index 14df0ff1d3..8212938f01 100644
--- a/django/contrib/gis/db/backends/oracle/operations.py
+++ b/django/contrib/gis/db/backends/oracle/operations.py
@@ -86,7 +86,7 @@ class OracleOperations(DatabaseOperations, BaseSpatialOperations):
     valid_aggregates = {'Union', 'Extent'}
 
     Adapter = OracleSpatialAdapter
-    Adaptor = Adapter # Backwards-compatibility alias.
+    Adaptor = Adapter  # Backwards-compatibility alias.
 
     area = 'SDO_GEOM.SDO_AREA'
     gml = 'SDO_UTIL.TO_GMLGEOMETRY'
@@ -126,12 +126,12 @@ class OracleOperations(DatabaseOperations, BaseSpatialOperations):
         'coveredby': SDOOperation('SDO_COVEREDBY'),
         'covers': SDOOperation('SDO_COVERS'),
         'disjoint': SDOGeomRelate('DISJOINT'),
-        'intersects': SDOOperation('SDO_OVERLAPBDYINTERSECT'), # TODO: Is this really the same as ST_Intersects()?
+        'intersects': SDOOperation('SDO_OVERLAPBDYINTERSECT'),  # TODO: Is this really the same as ST_Intersects()?
         'equals': SDOOperation('SDO_EQUAL'),
         'exact': SDOOperation('SDO_EQUAL'),
         'overlaps': SDOOperation('SDO_OVERLAPS'),
         'same_as': SDOOperation('SDO_EQUAL'),
-        'relate': (SDORelate, six.string_types), # Oracle uses a different syntax, e.g., 'mask=inside+touch'
+        'relate': (SDORelate, six.string_types),  # Oracle uses a different syntax, e.g., 'mask=inside+touch'
         'touches': SDOOperation('SDO_TOUCH'),
         'within': SDOOperation('SDO_INSIDE'),
     }
diff --git a/django/contrib/gis/db/backends/postgis/operations.py b/django/contrib/gis/db/backends/postgis/operations.py
index eae08479df..1a71be681c 100644
--- a/django/contrib/gis/db/backends/postgis/operations.py
+++ b/django/contrib/gis/db/backends/postgis/operations.py
@@ -79,7 +79,7 @@ class PostGISOperations(DatabaseOperations, BaseSpatialOperations):
     valid_aggregates = {'Collect', 'Extent', 'Extent3D', 'MakeLine', 'Union'}
 
     Adapter = PostGISAdapter
-    Adaptor = Adapter # Backwards-compatibility alias.
+    Adaptor = Adapter  # Backwards-compatibility alias.
 
     def __init__(self, connection):
         super(PostGISOperations, self).__init__(connection)
diff --git a/django/contrib/gis/db/backends/spatialite/operations.py b/django/contrib/gis/db/backends/spatialite/operations.py
index 827c5217a5..5149b541a2 100644
--- a/django/contrib/gis/db/backends/spatialite/operations.py
+++ b/django/contrib/gis/db/backends/spatialite/operations.py
@@ -68,7 +68,7 @@ class SpatiaLiteOperations(DatabaseOperations, BaseSpatialOperations):
     valid_aggregates = {'Extent', 'Union'}
 
     Adapter = SpatiaLiteAdapter
-    Adaptor = Adapter # Backwards-compatibility alias.
+    Adaptor = Adapter  # Backwards-compatibility alias.
 
     area = 'Area'
     centroid = 'Centroid'
@@ -77,7 +77,7 @@ class SpatiaLiteOperations(DatabaseOperations, BaseSpatialOperations):
     distance = 'Distance'
     envelope = 'Envelope'
     intersection = 'Intersection'
-    length = 'GLength' # OpenGis defines Length, but this conflicts with an SQLite reserved keyword
+    length = 'GLength'  # OpenGis defines Length, but this conflicts with an SQLite reserved keyword
     num_geom = 'NumGeometries'
     num_points = 'NumPoints'
     point_on_surface = 'PointOnSurface'
@@ -86,7 +86,7 @@ class SpatiaLiteOperations(DatabaseOperations, BaseSpatialOperations):
     sym_difference = 'SymDifference'
     transform = 'Transform'
     translate = 'ShiftCoords'
-    union = 'GUnion' # OpenGis defines Union, but this conflicts with an SQLite reserved keyword
+    union = 'GUnion'  # OpenGis defines Union, but this conflicts with an SQLite reserved keyword
     unionagg = 'GUnion'
 
     from_text = 'GeomFromText'
diff --git a/django/contrib/gis/db/models/fields.py b/django/contrib/gis/db/models/fields.py
index 662b20ae79..6dc2ee23b9 100644
--- a/django/contrib/gis/db/models/fields.py
+++ b/django/contrib/gis/db/models/fields.py
@@ -188,7 +188,7 @@ class GeometryField(Field):
         the SRID set for the field.  For example, if the input geometry
         has no SRID, then that of the field will be returned.
         """
-        gsrid = geom.srid # SRID of given geometry.
+        gsrid = geom.srid  # SRID of given geometry.
         if gsrid is None or self.srid == -1 or (gsrid == -1 and self.srid != -1):
             return self.srid
         else:
diff --git a/django/contrib/gis/db/models/query.py b/django/contrib/gis/db/models/query.py
index 5f1d4623ab..cdff5396cc 100644
--- a/django/contrib/gis/db/models/query.py
+++ b/django/contrib/gis/db/models/query.py
@@ -50,7 +50,7 @@ class GeoQuerySet(QuerySet):
         if backend.oracle:
             s['procedure_fmt'] = '%(geo_col)s,%(tolerance)s'
             s['procedure_args']['tolerance'] = tolerance
-            s['select_field'] = AreaField('sq_m') # Oracle returns area in units of meters.
+            s['select_field'] = AreaField('sq_m')  # Oracle returns area in units of meters.
         elif backend.postgis or backend.spatialite:
             if backend.geography:
                 # Geography fields support area calculation, returns square meters.
@@ -420,7 +420,7 @@ class GeoQuerySet(QuerySet):
         custom_sel = '%s(%s, %s)' % (connections[self.db].ops.transform, geo_col, srid)
         # TODO: Should we have this as an alias?
         # custom_sel = '(%s(%s, %s)) AS %s' % (SpatialBackend.transform, geo_col, srid, qn(geo_field.name))
-        self.query.transformed_srid = srid # So other GeoQuerySet methods
+        self.query.transformed_srid = srid  # So other GeoQuerySet methods
         self.query.custom_select[geo_field] = custom_sel
         return self._clone()
 
diff --git a/django/contrib/gis/gdal/geometries.py b/django/contrib/gis/gdal/geometries.py
index a331053eeb..753baff9ac 100644
--- a/django/contrib/gis/gdal/geometries.py
+++ b/django/contrib/gis/gdal/geometries.py
@@ -339,9 +339,9 @@ class OGRGeometry(GDALBase):
     def wkb(self):
         "Returns the WKB representation of the Geometry."
         if sys.byteorder == 'little':
-            byteorder = 1 # wkbNDR (from ogr_core.h)
+            byteorder = 1  # wkbNDR (from ogr_core.h)
         else:
-            byteorder = 0 # wkbXDR
+            byteorder = 0  # wkbXDR
         sz = self.wkb_size
         # Creating the unsigned character buffer, and passing it in by reference.
         buf = (c_ubyte * sz)()
@@ -635,7 +635,7 @@ class Polygon(OGRGeometry):
     @property
     def shell(self):
         "Returns the shell of this Polygon."
-        return self[0] # First ring is the shell
+        return self[0]  # First ring is the shell
     exterior_ring = shell
 
     @property
diff --git a/django/contrib/gis/gdal/prototypes/ds.py b/django/contrib/gis/gdal/prototypes/ds.py
index 11d3b2452f..374a0f424e 100644
--- a/django/contrib/gis/gdal/prototypes/ds.py
+++ b/django/contrib/gis/gdal/prototypes/ds.py
@@ -9,7 +9,7 @@ from django.contrib.gis.gdal.libgdal import lgdal
 from django.contrib.gis.gdal.prototypes.generation import (const_string_output,
     double_output, geom_output, int_output, srs_output, void_output, voidptr_output)
 
-c_int_p = POINTER(c_int) # shortcut type
+c_int_p = POINTER(c_int)  # shortcut type
 
 ### Driver Routines ###
 register_all = void_output(lgdal.OGRRegisterAll, [], errcheck=False)
diff --git a/django/contrib/gis/gdal/prototypes/geom.py b/django/contrib/gis/gdal/prototypes/geom.py
index f5dc7e10e9..4e4fb633c7 100644
--- a/django/contrib/gis/gdal/prototypes/geom.py
+++ b/django/contrib/gis/gdal/prototypes/geom.py
@@ -59,7 +59,7 @@ import_wkt = void_output(lgdal.OGR_G_ImportFromWkt, [c_void_p, POINTER(c_char_p)
 destroy_geom = void_output(lgdal.OGR_G_DestroyGeometry, [c_void_p], errcheck=False)
 
 # Geometry export routines.
-to_wkb = void_output(lgdal.OGR_G_ExportToWkb, None, errcheck=True) # special handling for WKB.
+to_wkb = void_output(lgdal.OGR_G_ExportToWkb, None, errcheck=True)  # special handling for WKB.
 to_wkt = string_output(lgdal.OGR_G_ExportToWkt, [c_void_p, POINTER(c_char_p)], decoding='ascii')
 to_gml = string_output(lgdal.OGR_G_ExportToGML, [c_void_p], str_result=True, decoding='ascii')
 get_wkbsize = int_output(lgdal.OGR_G_WkbSize, [c_void_p])
diff --git a/django/contrib/gis/gdal/tests/test_ds.py b/django/contrib/gis/gdal/tests/test_ds.py
index a2c0e9e133..5cfdb4a8ea 100644
--- a/django/contrib/gis/gdal/tests/test_ds.py
+++ b/django/contrib/gis/gdal/tests/test_ds.py
@@ -13,19 +13,19 @@ if HAS_GDAL:
     ds_list = (
         TestDS('test_point', nfeat=5, nfld=3, geom='POINT', gtype=1, driver='ESRI Shapefile',
             fields={'dbl': OFTReal, 'int': OFTInteger, 'str': OFTString},
-            extent=(-1.35011, 0.166623, -0.524093, 0.824508), # Got extent from QGIS
+            extent=(-1.35011, 0.166623, -0.524093, 0.824508),  # Got extent from QGIS
             srs_wkt='GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]]',
             field_values={'dbl': [float(i) for i in range(1, 6)], 'int': list(range(1, 6)), 'str': [str(i) for i in range(1, 6)]},
             fids=range(5)),
         TestDS('test_vrt', ext='vrt', nfeat=3, nfld=3, geom='POINT', gtype='Point25D', driver='VRT',
-            fields={'POINT_X': OFTString, 'POINT_Y': OFTString, 'NUM': OFTString}, # VRT uses CSV, which all types are OFTString.
-            extent=(1.0, 2.0, 100.0, 523.5), # Min/Max from CSV
+            fields={'POINT_X': OFTString, 'POINT_Y': OFTString, 'NUM': OFTString},  # VRT uses CSV, which all types are OFTString.
+            extent=(1.0, 2.0, 100.0, 523.5),  # Min/Max from CSV
             field_values={'POINT_X': ['1.0', '5.0', '100.0'], 'POINT_Y': ['2.0', '23.0', '523.5'], 'NUM': ['5', '17', '23']},
             fids=range(1, 4)),
         TestDS('test_poly', nfeat=3, nfld=3, geom='POLYGON', gtype=3,
             driver='ESRI Shapefile',
             fields={'float': OFTReal, 'int': OFTInteger, 'str': OFTString},
-            extent=(-1.01513, -0.558245, 0.161876, 0.839637), # Got extent from QGIS
+            extent=(-1.01513, -0.558245, 0.161876, 0.839637),  # Got extent from QGIS
             srs_wkt='GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]]'),
     )
 
diff --git a/django/contrib/gis/gdal/tests/test_envelope.py b/django/contrib/gis/gdal/tests/test_envelope.py
index 4644fbc533..555ca69531 100644
--- a/django/contrib/gis/gdal/tests/test_envelope.py
+++ b/django/contrib/gis/gdal/tests/test_envelope.py
@@ -23,7 +23,7 @@ class EnvelopeTest(unittest.TestCase):
         "Testing Envelope initilization."
         e1 = Envelope((0, 0, 5, 5))
         Envelope(0, 0, 5, 5)
-        Envelope(0, '0', '5', 5) # Thanks to ww for this
+        Envelope(0, '0', '5', 5)  # Thanks to ww for this
         Envelope(e1._envelope)
         self.assertRaises(OGRException, Envelope, (5, 5, 0, 0))
         self.assertRaises(OGRException, Envelope, 5, 5, 0, 0)
diff --git a/django/contrib/gis/gdal/tests/test_geom.py b/django/contrib/gis/gdal/tests/test_geom.py
index 65d78a1735..ed6bb2ad9c 100644
--- a/django/contrib/gis/gdal/tests/test_geom.py
+++ b/django/contrib/gis/gdal/tests/test_geom.py
@@ -130,7 +130,7 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
 
         OGRGeometry('POINT(0 0)')
         for p in self.geometries.points:
-            if not hasattr(p, 'z'): # No 3D
+            if not hasattr(p, 'z'):  # No 3D
                 pnt = OGRGeometry(p.wkt)
                 self.assertEqual(1, pnt.geom_type)
                 self.assertEqual('POINT', pnt.geom_name)
@@ -141,15 +141,15 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
     def test03_multipoints(self):
         "Testing MultiPoint objects."
         for mp in self.geometries.multipoints:
-            mgeom1 = OGRGeometry(mp.wkt) # First one from WKT
+            mgeom1 = OGRGeometry(mp.wkt)  # First one from WKT
             self.assertEqual(4, mgeom1.geom_type)
             self.assertEqual('MULTIPOINT', mgeom1.geom_name)
-            mgeom2 = OGRGeometry('MULTIPOINT') # Creating empty multipoint
+            mgeom2 = OGRGeometry('MULTIPOINT')  # Creating empty multipoint
             mgeom3 = OGRGeometry('MULTIPOINT')
             for g in mgeom1:
-                mgeom2.add(g) # adding each point from the multipoints
-                mgeom3.add(g.wkt) # should take WKT as well
-            self.assertEqual(mgeom1, mgeom2) # they should equal
+                mgeom2.add(g)  # adding each point from the multipoints
+                mgeom3.add(g.wkt)  # should take WKT as well
+            self.assertEqual(mgeom1, mgeom2)  # they should equal
             self.assertEqual(mgeom1, mgeom3)
             self.assertEqual(mp.coords, mgeom2.coords)
             self.assertEqual(mp.n_p, mgeom2.point_count)
@@ -247,7 +247,7 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
             poly.centroid
 
         poly.close_rings()
-        self.assertEqual(10, poly.point_count) # Two closing points should've been added
+        self.assertEqual(10, poly.point_count)  # Two closing points should've been added
         self.assertEqual(OGRGeometry('POINT(2.5 2.5)'), poly.centroid)
 
     def test08_multipolygons(self):
@@ -309,7 +309,7 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
                     # Changing each ring in the polygon
                     self.assertEqual(32140, ring.srs.srid)
                     self.assertEqual('NAD83 / Texas South Central', ring.srs.name)
-                    ring.srs = str(SpatialReference(4326)) # back to WGS84
+                    ring.srs = str(SpatialReference(4326))  # back to WGS84
                     self.assertEqual(4326, ring.srs.srid)
 
                     # Using the `srid` property.
@@ -361,8 +361,8 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
             d1 = OGRGeometry(self.geometries.diff_geoms[i].wkt)
             d2 = a.difference(b)
             self.assertEqual(d1, d2)
-            self.assertEqual(d1, a - b) # __sub__ is difference operator
-            a -= b # testing __isub__
+            self.assertEqual(d1, a - b)  # __sub__ is difference operator
+            a -= b  # testing __isub__
             self.assertEqual(d1, a)
 
     def test11_intersection(self):
@@ -374,8 +374,8 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
             self.assertTrue(a.intersects(b))
             i2 = a.intersection(b)
             self.assertEqual(i1, i2)
-            self.assertEqual(i1, a & b) # __and__ is intersection operator
-            a &= b # testing __iand__
+            self.assertEqual(i1, a & b)  # __and__ is intersection operator
+            a &= b  # testing __iand__
             self.assertEqual(i1, a)
 
     def test12_symdifference(self):
@@ -386,8 +386,8 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
             d1 = OGRGeometry(self.geometries.sdiff_geoms[i].wkt)
             d2 = a.sym_difference(b)
             self.assertEqual(d1, d2)
-            self.assertEqual(d1, a ^ b) # __xor__ is symmetric difference operator
-            a ^= b # testing __ixor__
+            self.assertEqual(d1, a ^ b)  # __xor__ is symmetric difference operator
+            a ^= b  # testing __ixor__
             self.assertEqual(d1, a)
 
     def test13_union(self):
@@ -398,8 +398,8 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
             u1 = OGRGeometry(self.geometries.union_geoms[i].wkt)
             u2 = a.union(b)
             self.assertEqual(u1, u2)
-            self.assertEqual(u1, a | b) # __or__ is union operator
-            a |= b # testing __ior__
+            self.assertEqual(u1, a | b)  # __or__ is union operator
+            a |= b  # testing __ior__
             self.assertEqual(u1, a)
 
     def test14_add(self):
@@ -418,9 +418,9 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
             mp3 = OGRGeometry('MultiPolygon')
 
             for poly in mpoly:
-                mp1.add(poly) # Adding a geometry at a time
-                mp2.add(poly.wkt) # Adding WKT
-            mp3.add(mpoly) # Adding a MultiPolygon's entire contents at once.
+                mp1.add(poly)  # Adding a geometry at a time
+                mp2.add(poly.wkt)  # Adding WKT
+            mp3.add(mpoly)  # Adding a MultiPolygon's entire contents at once.
             for tmp in (mp1, mp2, mp3):
                 self.assertEqual(mpoly, tmp)
 
diff --git a/django/contrib/gis/gdal/tests/test_srs.py b/django/contrib/gis/gdal/tests/test_srs.py
index 39cccf8440..372232755d 100644
--- a/django/contrib/gis/gdal/tests/test_srs.py
+++ b/django/contrib/gis/gdal/tests/test_srs.py
@@ -127,8 +127,8 @@ class SpatialRefTest(unittest.TestCase):
         for s in srlist:
             srs = SpatialReference(s.wkt)
             for tup in s.attr:
-                att = tup[0] # Attribute to test
-                exp = tup[1] # Expected result
+                att = tup[0]  # Attribute to test
+                exp = tup[1]  # Expected result
                 self.assertEqual(exp, srs[att])
 
     def test11_wellknown(self):
diff --git a/django/contrib/gis/geoip/tests.py b/django/contrib/gis/geoip/tests.py
index 4e7a990d50..f771608e1d 100644
--- a/django/contrib/gis/geoip/tests.py
+++ b/django/contrib/gis/geoip/tests.py
@@ -30,10 +30,10 @@ class GeoIPTest(unittest.TestCase):
 
     def test01_init(self):
         "Testing GeoIP initialization."
-        g1 = GeoIP() # Everything inferred from GeoIP path
+        g1 = GeoIP()  # Everything inferred from GeoIP path
         path = settings.GEOIP_PATH
-        g2 = GeoIP(path, 0) # Passing in data path explicitly.
-        g3 = GeoIP.open(path, 0) # MaxMind Python API syntax.
+        g2 = GeoIP(path, 0)  # Passing in data path explicitly.
+        g3 = GeoIP.open(path, 0)  # MaxMind Python API syntax.
 
         for g in (g1, g2, g3):
             self.assertEqual(True, bool(g._country))
diff --git a/django/contrib/gis/geos/linestring.py b/django/contrib/gis/geos/linestring.py
index 7a03712600..72f766310e 100644
--- a/django/contrib/gis/geos/linestring.py
+++ b/django/contrib/gis/geos/linestring.py
@@ -47,7 +47,7 @@ class LineString(GEOSGeometry):
                     raise TypeError('Dimension mismatch.')
             numpy_coords = False
         elif numpy and isinstance(coords, numpy.ndarray):
-            shape = coords.shape # Using numpy's shape.
+            shape = coords.shape  # Using numpy's shape.
             if len(shape) != 2:
                 raise TypeError('Too many dimensions.')
             self._checkdim(shape[1])
@@ -91,8 +91,8 @@ class LineString(GEOSGeometry):
     _get_single_internal = _get_single_external
 
     def _set_list(self, length, items):
-        ndim = self._cs.dims #
-        hasz = self._cs.hasz # I don't understand why these are different
+        ndim = self._cs.dims
+        hasz = self._cs.hasz  # I don't understand why these are different
 
         # create a new coordinate sequence and populate accordingly
         cs = GEOSCoordSeq(capi.create_cs(length, ndim), z=hasz)
@@ -130,7 +130,7 @@ class LineString(GEOSGeometry):
         """
         lst = [func(i) for i in xrange(len(self))]
         if numpy:
-            return numpy.array(lst) # ARRRR!
+            return numpy.array(lst)  # ARRRR!
         else:
             return lst
 
diff --git a/django/contrib/gis/geos/prototypes/errcheck.py b/django/contrib/gis/geos/prototypes/errcheck.py
index bd99047604..a3682ffd91 100644
--- a/django/contrib/gis/geos/prototypes/errcheck.py
+++ b/django/contrib/gis/geos/prototypes/errcheck.py
@@ -58,7 +58,7 @@ def check_minus_one(result, func, cargs):
 
 def check_predicate(result, func, cargs):
     "Error checking for unary/binary predicate functions."
-    val = ord(result) # getting the ordinal from the character
+    val = ord(result)  # getting the ordinal from the character
     if val == 1:
         return True
     elif val == 0:
diff --git a/django/contrib/gis/geos/prototypes/misc.py b/django/contrib/gis/geos/prototypes/misc.py
index 55381bf7fd..6b10396aba 100644
--- a/django/contrib/gis/geos/prototypes/misc.py
+++ b/django/contrib/gis/geos/prototypes/misc.py
@@ -21,7 +21,7 @@ def dbl_from_geom(func, num_geom=1):
     argtypes = [GEOM_PTR for i in xrange(num_geom)]
     argtypes += [POINTER(c_double)]
     func.argtypes = argtypes
-    func.restype = c_int # Status code returned
+    func.restype = c_int  # Status code returned
     func.errcheck = check_dbl
     return func
 
diff --git a/django/contrib/gis/geos/tests/test_geos.py b/django/contrib/gis/geos/tests/test_geos.py
index 9c24f614df..59cd9a32cc 100644
--- a/django/contrib/gis/geos/tests/test_geos.py
+++ b/django/contrib/gis/geos/tests/test_geos.py
@@ -198,7 +198,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
                 poly = fromstr(ewkt)
                 self.assertEqual(srid, poly.srid)
                 self.assertEqual(srid, poly.shell.srid)
-                self.assertEqual(srid, fromstr(poly.ewkt).srid) # Checking export
+                self.assertEqual(srid, fromstr(poly.ewkt).srid)  # Checking export
 
     @skipUnless(HAS_GDAL, "GDAL is required.")
     def test_json(self):
@@ -279,7 +279,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
 
             # Now testing the different constructors
             pnt2 = Point(tup_args)  # e.g., Point((1, 2))
-            pnt3 = Point(*tup_args) # e.g., Point(1, 2)
+            pnt3 = Point(*tup_args)  # e.g., Point(1, 2)
             self.assertEqual(True, pnt == pnt2)
             self.assertEqual(True, pnt == pnt3)
 
@@ -295,7 +295,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
             pnt.coords = set_tup2
             self.assertEqual(set_tup2, pnt.coords)
 
-            prev = pnt # setting the previous geometry
+            prev = pnt  # setting the previous geometry
 
     def test_multipoints(self):
         "Testing MultiPoint objects."
@@ -337,11 +337,11 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
 
             # Creating a LineString from a tuple, list, and numpy array
             self.assertEqual(ls, LineString(ls.tuple))  # tuple
-            self.assertEqual(ls, LineString(*ls.tuple)) # as individual arguments
-            self.assertEqual(ls, LineString([list(tup) for tup in ls.tuple])) # as list
-            self.assertEqual(ls.wkt, LineString(*tuple(Point(tup) for tup in ls.tuple)).wkt) # Point individual arguments
+            self.assertEqual(ls, LineString(*ls.tuple))  # as individual arguments
+            self.assertEqual(ls, LineString([list(tup) for tup in ls.tuple]))  # as list
+            self.assertEqual(ls.wkt, LineString(*tuple(Point(tup) for tup in ls.tuple)).wkt)  # Point individual arguments
             if numpy:
-                self.assertEqual(ls, LineString(numpy.array(ls.tuple))) # as numpy array
+                self.assertEqual(ls, LineString(numpy.array(ls.tuple)))  # as numpy array
 
     def test_multilinestring(self):
         "Testing MultiLineString objects."
@@ -409,7 +409,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
             self.assertEqual(poly.empty, False)
             self.assertEqual(poly.ring, False)
             self.assertEqual(p.n_i, poly.num_interior_rings)
-            self.assertEqual(p.n_i + 1, len(poly)) # Testing __len__
+            self.assertEqual(p.n_i + 1, len(poly))  # Testing __len__
             self.assertEqual(p.n_p, poly.num_points)
 
             # Area & Centroid
@@ -419,7 +419,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
 
             # Testing the geometry equivalence
             self.assertEqual(True, poly == fromstr(p.wkt))
-            self.assertEqual(False, poly == prev) # Should not be equal to previous geometry
+            self.assertEqual(False, poly == prev)  # Should not be equal to previous geometry
             self.assertEqual(True, poly != prev)
 
             # Testing the exterior ring
@@ -428,7 +428,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
             self.assertEqual(ring.geom_typeid, 2)
             if p.ext_ring_cs:
                 self.assertEqual(p.ext_ring_cs, ring.tuple)
-                self.assertEqual(p.ext_ring_cs, poly[0].tuple) # Testing __getitem__
+                self.assertEqual(p.ext_ring_cs, poly[0].tuple)  # Testing __getitem__
 
             # Testing __getitem__ and __setitem__ on invalid indices
             self.assertRaises(GEOSIndexError, poly.__getitem__, len(poly))
@@ -522,13 +522,13 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
                 poly = fromstr(p.wkt)
                 cs = poly.exterior_ring.coord_seq
 
-                self.assertEqual(p.ext_ring_cs, cs.tuple) # done in the Polygon test too.
-                self.assertEqual(len(p.ext_ring_cs), len(cs)) # Making sure __len__ works
+                self.assertEqual(p.ext_ring_cs, cs.tuple)  # done in the Polygon test too.
+                self.assertEqual(len(p.ext_ring_cs), len(cs))  # Making sure __len__ works
 
                 # Checks __getitem__ and __setitem__
                 for i in xrange(len(p.ext_ring_cs)):
-                    c1 = p.ext_ring_cs[i] # Expected value
-                    c2 = cs[i] # Value from coordseq
+                    c1 = p.ext_ring_cs[i]  # Expected value
+                    c2 = cs[i]  # Value from coordseq
                     self.assertEqual(c1, c2)
 
                     # Constructing the test value to set the coordinate sequence with
@@ -562,8 +562,8 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
             self.assertEqual(True, a.intersects(b))
             i2 = a.intersection(b)
             self.assertEqual(i1, i2)
-            self.assertEqual(i1, a & b) # __and__ is intersection operator
-            a &= b # testing __iand__
+            self.assertEqual(i1, a & b)  # __and__ is intersection operator
+            a &= b  # testing __iand__
             self.assertEqual(i1, a)
 
     def test_union(self):
@@ -574,8 +574,8 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
             u1 = fromstr(self.geometries.union_geoms[i].wkt)
             u2 = a.union(b)
             self.assertEqual(u1, u2)
-            self.assertEqual(u1, a | b) # __or__ is union operator
-            a |= b # testing __ior__
+            self.assertEqual(u1, a | b)  # __or__ is union operator
+            a |= b  # testing __ior__
             self.assertEqual(u1, a)
 
     def test_difference(self):
@@ -586,8 +586,8 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
             d1 = fromstr(self.geometries.diff_geoms[i].wkt)
             d2 = a.difference(b)
             self.assertEqual(d1, d2)
-            self.assertEqual(d1, a - b) # __sub__ is difference operator
-            a -= b # testing __isub__
+            self.assertEqual(d1, a - b)  # __sub__ is difference operator
+            a -= b  # testing __isub__
             self.assertEqual(d1, a)
 
     def test_symdifference(self):
@@ -598,8 +598,8 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
             d1 = fromstr(self.geometries.sdiff_geoms[i].wkt)
             d2 = a.sym_difference(b)
             self.assertEqual(d1, d2)
-            self.assertEqual(d1, a ^ b) # __xor__ is symmetric difference operator
-            a ^= b # testing __ixor__
+            self.assertEqual(d1, a ^ b)  # __xor__ is symmetric difference operator
+            a ^= b  # testing __ixor__
             self.assertEqual(d1, a)
 
     def test_buffer(self):
@@ -667,7 +667,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
 
         p2 = fromstr(p1.hex)
         self.assertEqual(exp_srid, p2.srid)
-        p3 = fromstr(p1.hex, srid=-1) # -1 is intended.
+        p3 = fromstr(p1.hex, srid=-1)  # -1 is intended.
         self.assertEqual(-1, p3.srid)
 
     @skipUnless(HAS_GDAL, "GDAL is required.")
@@ -705,7 +705,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
 
             # Assigning polygon's exterior ring w/the new shell
             poly.exterior_ring = new_shell
-            str(new_shell) # new shell is still accessible
+            str(new_shell)  # new shell is still accessible
             self.assertEqual(poly.exterior_ring, new_shell)
             self.assertEqual(poly[0], new_shell)
 
@@ -718,7 +718,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
                 new = Point(random.randint(21, 100), random.randint(21, 100))
                 # Testing the assignment
                 mp[i] = new
-                str(new) # what was used for the assignment is still accessible
+                str(new)  # what was used for the assignment is still accessible
                 self.assertEqual(mp[i], new)
                 self.assertEqual(mp[i].wkt, new.wkt)
                 self.assertNotEqual(pnt, mp[i])
@@ -740,7 +740,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
                 self.assertNotEqual(mpoly[i], poly)
                 # Testing the assignment
                 mpoly[i] = poly
-                str(poly) # Still accessible
+                str(poly)  # Still accessible
                 self.assertEqual(mpoly[i], poly)
                 self.assertNotEqual(mpoly[i], old_poly)
 
@@ -821,7 +821,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
 
             # Testing len() and num_geom.
             if isinstance(g, Polygon):
-                self.assertEqual(1, len(g)) # Has one empty linear ring
+                self.assertEqual(1, len(g))  # Has one empty linear ring
                 self.assertEqual(1, g.num_geom)
                 self.assertEqual(0, len(g[0]))
             elif isinstance(g, (Point, LineString)):
@@ -1039,7 +1039,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
 
         # A set of test points.
         pnts = [Point(5, 5), Point(7.5, 7.5), Point(2.5, 7.5)]
-        covers = [True, True, False] # No `covers` op for regular GEOS geoms.
+        covers = [True, True, False]  # No `covers` op for regular GEOS geoms.
         for pnt, c in zip(pnts, covers):
             # Results should be the same (but faster)
             self.assertEqual(mpoly.contains(pnt), prep.contains(pnt))
diff --git a/django/contrib/gis/geos/tests/test_mutable_list.py b/django/contrib/gis/geos/tests/test_mutable_list.py
index fc3b247f1f..5340dac99d 100644
--- a/django/contrib/gis/geos/tests/test_mutable_list.py
+++ b/django/contrib/gis/geos/tests/test_mutable_list.py
@@ -223,9 +223,9 @@ class ListMixinTest(unittest.TestCase):
             del x[i]
         pl, ul = self.lists_of_len()
         for i in (-1 - self.limit, self.limit):
-            self.assertRaises(IndexError, setfcn, ul, i) # 'set index %d' % i)
-            self.assertRaises(IndexError, getfcn, ul, i) # 'get index %d' % i)
-            self.assertRaises(IndexError, delfcn, ul, i) # 'del index %d' % i)
+            self.assertRaises(IndexError, setfcn, ul, i)  # 'set index %d' % i)
+            self.assertRaises(IndexError, getfcn, ul, i)  # 'get index %d' % i)
+            self.assertRaises(IndexError, delfcn, ul, i)  # 'del index %d' % i)
 
     def test06_list_methods(self):
         'List methods'
diff --git a/django/contrib/gis/maps/google/gmap.py b/django/contrib/gis/maps/google/gmap.py
index ee820fc3c6..b61c95913d 100644
--- a/django/contrib/gis/maps/google/gmap.py
+++ b/django/contrib/gis/maps/google/gmap.py
@@ -20,9 +20,9 @@ class GoogleMap(object):
     "A class for generating Google Maps JavaScript."
 
     # String constants
-    onunload = mark_safe('onunload="GUnload()"') # Cleans up after Google Maps
-    vml_css = mark_safe('v\:* {behavior:url(#default#VML);}') # CSS for IE VML
-    xmlns = mark_safe('xmlns:v="urn:schemas-microsoft-com:vml"') # XML Namespace (for IE VML).
+    onunload = mark_safe('onunload="GUnload()"')  # Cleans up after Google Maps
+    vml_css = mark_safe('v\:* {behavior:url(#default#VML);}')  # CSS for IE VML
+    xmlns = mark_safe('xmlns:v="urn:schemas-microsoft-com:vml"')  # XML Namespace (for IE VML).
 
     def __init__(self, key=None, api_url=None, version=None,
                  center=None, zoom=None, dom_id='map',
diff --git a/django/contrib/gis/maps/google/zoom.py b/django/contrib/gis/maps/google/zoom.py
index 6bbadcdf16..22b3ceac1d 100644
--- a/django/contrib/gis/maps/google/zoom.py
+++ b/django/contrib/gis/maps/google/zoom.py
@@ -33,18 +33,18 @@ class GoogleZoom(object):
 
         # Initializing arrays to hold the parameters for each one of the
         # zoom levels.
-        self._degpp = [] # Degrees per pixel
-        self._radpp = [] # Radians per pixel
-        self._npix = [] # 1/2 the number of pixels for a tile at the given zoom level
+        self._degpp = []  # Degrees per pixel
+        self._radpp = []  # Radians per pixel
+        self._npix = []  # 1/2 the number of pixels for a tile at the given zoom level
 
         # Incrementing through the zoom levels and populating the parameter arrays.
-        z = tilesize # The number of pixels per zoom level.
+        z = tilesize  # The number of pixels per zoom level.
         for i in xrange(num_zoom):
             # Getting the degrees and radians per pixel, and the 1/2 the number of
             # for every zoom level.
-            self._degpp.append(z / 360.) # degrees per pixel
-            self._radpp.append(z / (2 * pi)) # radians per pixel
-            self._npix.append(z / 2) # number of pixels to center of tile
+            self._degpp.append(z / 360.)  # degrees per pixel
+            self._radpp.append(z / (2 * pi))  # radians per pixel
+            self._npix.append(z / 2)  # number of pixels to center of tile
 
             # Multiplying `z` by 2 for the next iteration.
             z *= 2
diff --git a/django/contrib/gis/tests/distapp/tests.py b/django/contrib/gis/tests/distapp/tests.py
index 8db977e025..6b7c734066 100644
--- a/django/contrib/gis/tests/distapp/tests.py
+++ b/django/contrib/gis/tests/distapp/tests.py
@@ -5,7 +5,7 @@ from unittest import skipUnless
 from django.db import connection
 from django.db.models import Q
 from django.contrib.gis.geos import HAS_GEOS
-from django.contrib.gis.measure import D # alias for Distance
+from django.contrib.gis.measure import D  # alias for Distance
 from django.contrib.gis.tests.utils import (
     HAS_SPATIAL_DB, mysql, oracle, postgis, spatialite, no_oracle, no_spatialite
 )
@@ -123,7 +123,7 @@ class DistanceTest(TestCase):
         if spatialite or oracle:
             dist_qs = [dist1, dist2]
         else:
-            dist3 = SouthTexasCityFt.objects.distance(lagrange.ewkt) # Using EWKT string parameter.
+            dist3 = SouthTexasCityFt.objects.distance(lagrange.ewkt)  # Using EWKT string parameter.
             dist4 = SouthTexasCityFt.objects.distance(lagrange)
             dist_qs = [dist1, dist2, dist3, dist4]
 
@@ -199,7 +199,7 @@ class DistanceTest(TestCase):
             for i, c in enumerate(qs):
                 self.assertAlmostEqual(sphere_distances[i], c.distance.m, tol)
 
-    @no_oracle # Oracle already handles geographic distance calculation.
+    @no_oracle  # Oracle already handles geographic distance calculation.
     def test_distance_transform(self):
         """
         Test the `distance` GeoQuerySet method used with `transform` on a geographic field.
@@ -307,7 +307,7 @@ class DistanceTest(TestCase):
         # Cities that are either really close or really far from Wollongong --
         # and using different units of distance.
         wollongong = AustraliaCity.objects.get(name='Wollongong')
-        d1, d2 = D(yd=19500), D(nm=400) # Yards (~17km) & Nautical miles.
+        d1, d2 = D(yd=19500), D(nm=400)  # Yards (~17km) & Nautical miles.
 
         # Normal geodetic distance lookup (uses `distance_sphere` on PostGIS.
         gq1 = Q(point__distance_lte=(wollongong.point, d1))
diff --git a/django/contrib/gis/tests/geoapp/models.py b/django/contrib/gis/tests/geoapp/models.py
index 251173e432..8234bc8d9b 100644
--- a/django/contrib/gis/tests/geoapp/models.py
+++ b/django/contrib/gis/tests/geoapp/models.py
@@ -9,7 +9,7 @@ null_flag = not mysql
 @python_2_unicode_compatible
 class Country(models.Model):
     name = models.CharField(max_length=30)
-    mpoly = models.MultiPolygonField() # SRID, by default, is 4326
+    mpoly = models.MultiPolygonField()  # SRID, by default, is 4326
     objects = models.GeoManager()
 
     def __str__(self):
@@ -30,13 +30,13 @@ class City(models.Model):
 class PennsylvaniaCity(City):
     county = models.CharField(max_length=30)
     founded = models.DateTimeField(null=True)
-    objects = models.GeoManager() # TODO: This should be implicitly inherited.
+    objects = models.GeoManager()  # TODO: This should be implicitly inherited.
 
 
 @python_2_unicode_compatible
 class State(models.Model):
     name = models.CharField(max_length=30)
-    poly = models.PolygonField(null=null_flag) # Allowing NULL geometries here.
+    poly = models.PolygonField(null=null_flag)  # Allowing NULL geometries here.
     objects = models.GeoManager()
 
     def __str__(self):
@@ -68,5 +68,5 @@ if not spatialite:
             return self.name
 
     class MinusOneSRID(models.Model):
-        geom = models.PointField(srid=-1) # Minus one SRID.
+        geom = models.PointField(srid=-1)  # Minus one SRID.
         objects = models.GeoManager()
diff --git a/django/contrib/gis/tests/geoapp/test_feeds.py b/django/contrib/gis/tests/geoapp/test_feeds.py
index 9ae06d76e0..7b8fc159b4 100644
--- a/django/contrib/gis/tests/geoapp/test_feeds.py
+++ b/django/contrib/gis/tests/geoapp/test_feeds.py
@@ -92,5 +92,5 @@ class GeoFeedTest(TestCase):
             self.assertChildNodes(item, ['title', 'link', 'description', 'guid', 'geo:lat', 'geo:lon'])
 
         # Boxes and Polygons aren't allowed in W3C Geo feeds.
-        self.assertRaises(ValueError, self.client.get, '/feeds/w3cgeo2/') # Box in <channel>
-        self.assertRaises(ValueError, self.client.get, '/feeds/w3cgeo3/') # Polygons in <entry>
+        self.assertRaises(ValueError, self.client.get, '/feeds/w3cgeo2/')  # Box in <channel>
+        self.assertRaises(ValueError, self.client.get, '/feeds/w3cgeo3/')  # Polygons in <entry>
diff --git a/django/contrib/gis/tests/geoapp/test_sitemaps.py b/django/contrib/gis/tests/geoapp/test_sitemaps.py
index 92d70e1fd5..d9ede80c57 100644
--- a/django/contrib/gis/tests/geoapp/test_sitemaps.py
+++ b/django/contrib/gis/tests/geoapp/test_sitemaps.py
@@ -59,7 +59,7 @@ class GeoSitemapTest(TestCase):
             self.assertEqual(urlset.getAttribute('xmlns:geo'), 'http://www.google.com/geo/schemas/sitemap/1.0')
 
             urls = urlset.getElementsByTagName('url')
-            self.assertEqual(2, len(urls)) # Should only be 2 sitemaps.
+            self.assertEqual(2, len(urls))  # Should only be 2 sitemaps.
             for url in urls:
                 self.assertChildNodes(url, ['loc', 'geo:geo'])
                 # Making sure the 'geo:format' element was properly set.
diff --git a/django/contrib/gis/tests/geoapp/tests.py b/django/contrib/gis/tests/geoapp/tests.py
index 4b20c4b2c8..f1b2f1adbe 100644
--- a/django/contrib/gis/tests/geoapp/tests.py
+++ b/django/contrib/gis/tests/geoapp/tests.py
@@ -84,7 +84,7 @@ class GeoModelTest(TestCase):
         # Creating a State object using a built Polygon
         ply = Polygon(shell, inner)
         nullstate = State(name='NullState', poly=ply)
-        self.assertEqual(4326, nullstate.poly.srid) # SRID auto-set from None
+        self.assertEqual(4326, nullstate.poly.srid)  # SRID auto-set from None
         nullstate.save()
 
         ns = State.objects.get(name='NullState')
@@ -111,7 +111,7 @@ class GeoModelTest(TestCase):
         "Testing automatic transform for lookups and inserts."
         # San Antonio in 'WGS84' (SRID 4326)
         sa_4326 = 'POINT (-98.493183 29.424170)'
-        wgs_pnt = fromstr(sa_4326, srid=4326) # Our reference point in WGS84
+        wgs_pnt = fromstr(sa_4326, srid=4326)  # Our reference point in WGS84
 
         # Oracle doesn't have SRID 3084, using 41157.
         if oracle:
@@ -122,7 +122,7 @@ class GeoModelTest(TestCase):
             nad_srid = 41157
         else:
             # San Antonio in 'NAD83(HARN) / Texas Centric Lambert Conformal' (SRID 3084)
-            nad_wkt = 'POINT (1645978.362408288754523 6276356.025927528738976)' # Used ogr.py in gdal 1.4.1 for this transform
+            nad_wkt = 'POINT (1645978.362408288754523 6276356.025927528738976)'  # Used ogr.py in gdal 1.4.1 for this transform
             nad_srid = 3084
 
         # Constructing & querying with a point from a different SRID. Oracle
@@ -156,7 +156,7 @@ class GeoModelTest(TestCase):
         c = City()
         self.assertEqual(c.point, None)
 
-    @no_spatialite # SpatiaLite does not support abstract geometry columns
+    @no_spatialite  # SpatiaLite does not support abstract geometry columns
     def test_geometryfield(self):
         "Testing the general GeometryField."
         Feature(name='Point', geom=Point(1, 1)).save()
@@ -242,8 +242,8 @@ class GeoLookupTest(TestCase):
 
         # Now testing contains on the countries using the points for
         #  Houston and Wellington.
-        tx = Country.objects.get(mpoly__contains=houston.point) # Query w/GEOSGeometry
-        nz = Country.objects.get(mpoly__contains=wellington.point.hex) # Query w/EWKBHEX
+        tx = Country.objects.get(mpoly__contains=houston.point)  # Query w/GEOSGeometry
+        nz = Country.objects.get(mpoly__contains=wellington.point.hex)  # Query w/EWKBHEX
         self.assertEqual('Texas', tx.name)
         self.assertEqual('New Zealand', nz.name)
 
@@ -254,9 +254,9 @@ class GeoLookupTest(TestCase):
 
         # Pueblo and Oklahoma City (even though OK City is within the bounding box of Texas)
         # are not contained in Texas or New Zealand.
-        self.assertEqual(0, len(Country.objects.filter(mpoly__contains=pueblo.point))) # Query w/GEOSGeometry object
+        self.assertEqual(0, len(Country.objects.filter(mpoly__contains=pueblo.point)))  # Query w/GEOSGeometry object
         self.assertEqual((mysql and 1) or 0,
-                         len(Country.objects.filter(mpoly__contains=okcity.point.wkt))) # Qeury w/WKT
+                         len(Country.objects.filter(mpoly__contains=okcity.point.wkt)))  # Qeury w/WKT
 
         # OK City is contained w/in bounding box of Texas.
         if not oracle:
@@ -446,7 +446,7 @@ class GeoQuerySetTest(TestCase):
             self.assertIsInstance(country.envelope, Polygon)
 
     @no_mysql
-    @no_spatialite # SpatiaLite does not have an Extent function
+    @no_spatialite  # SpatiaLite does not have an Extent function
     def test_extent(self):
         "Testing the `extent` GeoQuerySet method."
         # Reference query:
@@ -618,7 +618,7 @@ class GeoQuerySetTest(TestCase):
                 self.assertEqual(1, c.num_geom)
 
     @no_mysql
-    @no_spatialite # SpatiaLite can only count vertices in LineStrings
+    @no_spatialite  # SpatiaLite can only count vertices in LineStrings
     def test_num_points(self):
         "Testing the `num_points` GeoQuerySet method."
         for c in Country.objects.num_points():
@@ -671,7 +671,7 @@ class GeoQuerySetTest(TestCase):
     def test_scale(self):
         "Testing the `scale` GeoQuerySet method."
         xfac, yfac = 2, 3
-        tol = 5 # XXX The low precision tolerance is for SpatiaLite
+        tol = 5  # XXX The low precision tolerance is for SpatiaLite
         qs = Country.objects.scale(xfac, yfac, model_att='scaled')
         for c in qs:
             for p1, p2 in zip(c.mpoly, c.scaled):
@@ -740,7 +740,7 @@ class GeoQuerySetTest(TestCase):
         # Pre-transformed points for Houston and Pueblo.
         htown = fromstr('POINT(1947516.83115183 6322297.06040572)', srid=3084)
         ptown = fromstr('POINT(992363.390841912 481455.395105533)', srid=2774)
-        prec = 3 # Precision is low due to version variations in PROJ and GDAL.
+        prec = 3  # Precision is low due to version variations in PROJ and GDAL.
 
         # Asserting the result of the transform operation with the values in
         #  the pre-transformed points.  Oracle does not have the 3084 SRID.
diff --git a/django/contrib/gis/tests/geogapp/tests.py b/django/contrib/gis/tests/geogapp/tests.py
index 83c73dfd4d..615c142324 100644
--- a/django/contrib/gis/tests/geogapp/tests.py
+++ b/django/contrib/gis/tests/geogapp/tests.py
@@ -48,7 +48,7 @@ class GeographyTest(TestCase):
         "Ensuring exceptions are raised for operators & functions invalid on geography fields."
         # Only a subset of the geometry functions & operator are available
         # to PostGIS geography types.  For more information, visit:
-        #  http://postgis.refractions.net/documentation/manual-1.5/ch08.html#PostGIS_GeographyFunctions
+        # http://postgis.refractions.net/documentation/manual-1.5/ch08.html#PostGIS_GeographyFunctions
         z = Zipcode.objects.get(code='77002')
         # ST_Within not available.
         self.assertRaises(ValueError, City.objects.filter(point__within=z.poly).count)
@@ -76,7 +76,7 @@ class GeographyTest(TestCase):
 
         # Reference county names, number of polygons, and state names.
         names = ['Bexar', 'Galveston', 'Harris', 'Honolulu', 'Pueblo']
-        num_polys = [1, 2, 1, 19, 1] # Number of polygons for each.
+        num_polys = [1, 2, 1, 19, 1]  # Number of polygons for each.
         st_names = ['Texas', 'Texas', 'Texas', 'Hawaii', 'Colorado']
 
         lm = LayerMapping(County, co_shp, co_mapping, source_srs=4269, unique='name')
diff --git a/django/contrib/gis/tests/layermap/models.py b/django/contrib/gis/tests/layermap/models.py
index 5e8b0879ed..1b66c6d94c 100644
--- a/django/contrib/gis/tests/layermap/models.py
+++ b/django/contrib/gis/tests/layermap/models.py
@@ -9,7 +9,7 @@ class State(models.Model):
 class County(models.Model):
     name = models.CharField(max_length=25)
     state = models.ForeignKey(State)
-    mpoly = models.MultiPolygonField(srid=4269) # Multipolygon in NAD83
+    mpoly = models.MultiPolygonField(srid=4269)  # Multipolygon in NAD83
     objects = models.GeoManager()
 
 
@@ -58,8 +58,8 @@ class Invalid(models.Model):
 
 # Mapping dictionaries for the models above.
 co_mapping = {'name': 'Name',
-              'state': {'name': 'State'}, # ForeignKey's use another mapping dictionary for the _related_ Model (State in this case).
-              'mpoly': 'MULTIPOLYGON', # Will convert POLYGON features into MULTIPOLYGONS.
+              'state': {'name': 'State'},  # ForeignKey's use another mapping dictionary for the _related_ Model (State in this case).
+              'mpoly': 'MULTIPOLYGON',  # Will convert POLYGON features into MULTIPOLYGONS.
               }
 
 cofeat_mapping = {'name': 'Name',
diff --git a/django/contrib/gis/tests/layermap/tests.py b/django/contrib/gis/tests/layermap/tests.py
index d42fe1d6ee..df6f22c38a 100644
--- a/django/contrib/gis/tests/layermap/tests.py
+++ b/django/contrib/gis/tests/layermap/tests.py
@@ -32,7 +32,7 @@ invalid_shp = os.path.join(shp_path, 'invalid', 'emptypoints.shp')
 
 # Dictionaries to hold what's expected in the county shapefile.
 NAMES = ['Bexar', 'Galveston', 'Harris', 'Honolulu', 'Pueblo']
-NUMS = [1, 2, 1, 19, 1] # Number of polygons for each.
+NUMS = [1, 2, 1, 19, 1]  # Number of polygons for each.
 STATES = ['Texas', 'Texas', 'Texas', 'Hawaii', 'Colorado']
 
 
@@ -129,7 +129,7 @@ class LayerMapTest(TestCase):
             # Should only be one record b/c of `unique` keyword.
             c = County.objects.get(name=name)
             self.assertEqual(n, len(c.mpoly))
-            self.assertEqual(st, c.state.name) # Checking ForeignKey mapping.
+            self.assertEqual(st, c.state.name)  # Checking ForeignKey mapping.
 
             # Multiple records because `unique` was not set.
             if county_feat:
@@ -224,7 +224,7 @@ class LayerMapTest(TestCase):
             self.assertRaises(TypeError, lm.save, fid_range=bad)
 
         # Step keyword should not be allowed w/`fid_range`.
-        fr = (3, 5) # layer[3:5]
+        fr = (3, 5)  # layer[3:5]
         self.assertRaises(LayerMapError, lm.save, fid_range=fr, step=10)
         lm.save(fid_range=fr)
 
@@ -237,8 +237,8 @@ class LayerMapTest(TestCase):
         # Features IDs 5 and beyond for Honolulu County, Hawaii, and
         # FID 0 is for Pueblo County, Colorado.
         clear_counties()
-        lm.save(fid_range=slice(5, None), silent=True, strict=True) # layer[5:]
-        lm.save(fid_range=slice(None, 1), silent=True, strict=True) # layer[:1]
+        lm.save(fid_range=slice(5, None), silent=True, strict=True)  # layer[5:]
+        lm.save(fid_range=slice(None, 1), silent=True, strict=True)  # layer[:1]
 
         # Only Pueblo & Honolulu counties should be present because of
         # the `unique` keyword.  Have to set `order_by` on this QuerySet
diff --git a/django/contrib/gis/tests/test_spatialrefsys.py b/django/contrib/gis/tests/test_spatialrefsys.py
index 8bc9177fb4..194578d1e0 100644
--- a/django/contrib/gis/tests/test_spatialrefsys.py
+++ b/django/contrib/gis/tests/test_spatialrefsys.py
@@ -15,7 +15,7 @@ test_srs = ({'srid': 4326,
              'proj4_re': r'\+proj=longlat (\+ellps=WGS84 )?\+datum=WGS84 \+no_defs ',
              'spheroid': 'WGS 84', 'name': 'WGS 84',
              'geographic': True, 'projected': False, 'spatialite': True,
-             'ellipsoid': (6378137.0, 6356752.3, 298.257223563), # From proj's "cs2cs -le" and Wikipedia (semi-minor only)
+             'ellipsoid': (6378137.0, 6356752.3, 298.257223563),  # From proj's "cs2cs -le" and Wikipedia (semi-minor only)
              'eprec': (1, 1, 9),
              },
             {'srid': 32140,
@@ -27,7 +27,7 @@ test_srs = ({'srid': 4326,
                           r'(\+datum=NAD83 |\+towgs84=0,0,0,0,0,0,0 )?\+units=m \+no_defs ',
              'spheroid': 'GRS 1980', 'name': 'NAD83 / Texas South Central',
              'geographic': False, 'projected': True, 'spatialite': False,
-             'ellipsoid': (6378137.0, 6356752.31414, 298.257222101), # From proj's "cs2cs -le" and Wikipedia (semi-minor only)
+             'ellipsoid': (6378137.0, 6356752.31414, 298.257222101),  # From proj's "cs2cs -le" and Wikipedia (semi-minor only)
              'eprec': (1, 5, 10),
              },
             )
diff --git a/django/contrib/gis/utils/layermapping.py b/django/contrib/gis/utils/layermapping.py
index 9d70026dbb..5f57bc1749 100644
--- a/django/contrib/gis/utils/layermapping.py
+++ b/django/contrib/gis/utils/layermapping.py
@@ -129,7 +129,7 @@ class LayerMapping(object):
 
         if unique:
             self.check_unique(unique)
-            transaction_mode = 'autocommit' # Has to be set to autocommit.
+            transaction_mode = 'autocommit'  # Has to be set to autocommit.
             self.unique = unique
         else:
             self.unique = None
@@ -286,7 +286,7 @@ class LayerMapping(object):
         else:
             raise TypeError('Unique keyword argument must be set with a tuple, list, or string.')
 
-    #### Keyword argument retrieval routines ####
+    # Keyword argument retrieval routines ####
     def feature_kwargs(self, feat):
         """
         Given an OGR Feature, this will return a dictionary of keyword arguments
@@ -359,7 +359,7 @@ class LayerMapping(object):
             # Getting the decimal value as a tuple.
             dtup = d.as_tuple()
             digits = dtup[1]
-            d_idx = dtup[2] # index where the decimal is
+            d_idx = dtup[2]  # index where the decimal is
 
             # Maximum amount of precision, or digits to the left of the decimal.
             max_prec = model_field.max_digits - model_field.decimal_places
diff --git a/django/contrib/messages/storage/cookie.py b/django/contrib/messages/storage/cookie.py
index 2ec3fe484b..d0d09dee48 100644
--- a/django/contrib/messages/storage/cookie.py
+++ b/django/contrib/messages/storage/cookie.py
@@ -101,7 +101,7 @@ class CookieStorage(BaseStorage):
         if self.max_cookie_size:
             # data is going to be stored eventually by SimpleCookie, which
             # adds it's own overhead, which we must account for.
-            cookie = SimpleCookie() # create outside the loop
+            cookie = SimpleCookie()  # create outside the loop
 
             def stored_length(val):
                 return len(cookie.value_encode(val)[1])
diff --git a/django/contrib/messages/tests/test_cookie.py b/django/contrib/messages/tests/test_cookie.py
index c4e2b0abfb..028f01382b 100644
--- a/django/contrib/messages/tests/test_cookie.py
+++ b/django/contrib/messages/tests/test_cookie.py
@@ -77,7 +77,7 @@ class CookieTest(BaseTests, TestCase):
         response = self.get_response()
         storage.add(constants.INFO, 'test')
         for m in storage:
-            pass # Iterate through the storage to simulate consumption of messages.
+            pass  # Iterate through the storage to simulate consumption of messages.
         storage.update(response)
         self.assertEqual(response.cookies['messages'].value, '')
         self.assertEqual(response.cookies['messages']['domain'], '.example.com')
diff --git a/django/contrib/sessions/models.py b/django/contrib/sessions/models.py
index 3a6e31152f..1ab42c03e1 100644
--- a/django/contrib/sessions/models.py
+++ b/django/contrib/sessions/models.py
@@ -14,7 +14,7 @@ class SessionManager(models.Manager):
         if session_dict:
             s.save()
         else:
-            s.delete() # Clear sessions with no data.
+            s.delete()  # Clear sessions with no data.
         return s
 
 
diff --git a/django/contrib/sessions/tests.py b/django/contrib/sessions/tests.py
index 275eba5713..862bdfb69b 100644
--- a/django/contrib/sessions/tests.py
+++ b/django/contrib/sessions/tests.py
@@ -388,7 +388,7 @@ class CacheDBSessionTests(SessionTestsMixin, TestCase):
 
     @override_settings(SESSION_CACHE_ALIAS='sessions')
     def test_non_default_cache(self):
-        #21000 - CacheDB backend should respect SESSION_CACHE_ALIAS.
+        # 21000 - CacheDB backend should respect SESSION_CACHE_ALIAS.
         self.assertRaises(InvalidCacheBackendError, self.backend)
 
 
diff --git a/django/core/cache/backends/memcached.py b/django/core/cache/backends/memcached.py
index 9b2c5e8bd1..c49c20e59b 100644
--- a/django/core/cache/backends/memcached.py
+++ b/django/core/cache/backends/memcached.py
@@ -60,7 +60,7 @@ class BaseMemcachedCache(six.with_metaclass(BaseMemcachedCacheMethods, BaseCache
             # in memcache backends, a negative timeout must be passed.
             timeout = -1
 
-        if timeout > 2592000: # 60*60*24*30, 30 days
+        if timeout > 2592000:  # 60*60*24*30, 30 days
             # See http://code.google.com/p/memcached/wiki/FAQ
             # "You can set expire times up to 30 days in the future. After that
             # memcached interprets it as a date, and will expire the item after
diff --git a/django/core/files/uploadhandler.py b/django/core/files/uploadhandler.py
index 3bd6993771..4b23d48fb4 100644
--- a/django/core/files/uploadhandler.py
+++ b/django/core/files/uploadhandler.py
@@ -64,7 +64,7 @@ class FileUploadHandler(object):
     """
     Base class for streaming upload handlers.
     """
-    chunk_size = 64 * 2 ** 10 #: The default chunk size is 64 KB.
+    chunk_size = 64 * 2 ** 10  # : The default chunk size is 64 KB.
 
     def __init__(self, request=None):
         self.file_name = None
diff --git a/django/core/handlers/base.py b/django/core/handlers/base.py
index 577cb2176b..bf65687d5c 100644
--- a/django/core/handlers/base.py
+++ b/django/core/handlers/base.py
@@ -189,7 +189,7 @@ class BaseHandler(object):
             # Allow sys.exit() to actually exit. See tickets #1023 and #4701
             raise
 
-        except: # Handle everything else.
+        except:  # Handle everything else.
             # Get the exception info now, in case another exception is thrown later.
             signals.got_request_exception.send(sender=self.__class__, request=request)
             response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
@@ -199,7 +199,7 @@ class BaseHandler(object):
             for middleware_method in self._response_middleware:
                 response = middleware_method(request, response)
             response = self.apply_response_fixes(request, response)
-        except: # Any exception should be gathered and handled
+        except:  # Any exception should be gathered and handled
             signals.got_request_exception.send(sender=self.__class__, request=request)
             response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
 
diff --git a/django/core/handlers/wsgi.py b/django/core/handlers/wsgi.py
index 4c54b3e39d..21cadf48b8 100644
--- a/django/core/handlers/wsgi.py
+++ b/django/core/handlers/wsgi.py
@@ -52,7 +52,7 @@ class LimitedStream(object):
         elif size < len(self.buffer):
             result = self.buffer[:size]
             self.buffer = self.buffer[size:]
-        else: # size >= len(self.buffer)
+        else:  # size >= len(self.buffer)
             result = self.buffer + self._read_limited(size - len(self.buffer))
             self.buffer = b''
         return result
diff --git a/django/core/management/__init__.py b/django/core/management/__init__.py
index 3516ac330b..de49f5e241 100644
--- a/django/core/management/__init__.py
+++ b/django/core/management/__init__.py
@@ -121,7 +121,7 @@ def get_commands():
                 _commands.update(dict((name, app_name)
                                        for name in find_commands(path)))
             except ImportError:
-                pass # No management module - ignore this app
+                pass  # No management module - ignore this app
 
     return _commands
 
@@ -379,12 +379,12 @@ class ManagementUtility(object):
             options, args = parser.parse_args(self.argv)
             handle_default_options(options)
         except:  # Needed because parser.parse_args can raise SystemExit
-            pass # Ignore any option errors at this point.
+            pass  # Ignore any option errors at this point.
 
         try:
             subcommand = self.argv[1]
         except IndexError:
-            subcommand = 'help' # Display help if no arguments were given.
+            subcommand = 'help'  # Display help if no arguments were given.
 
         if subcommand == 'help':
             if len(args) <= 2:
diff --git a/django/core/management/commands/inspectdb.py b/django/core/management/commands/inspectdb.py
index 89549dc3c1..a24ae2b51e 100644
--- a/django/core/management/commands/inspectdb.py
+++ b/django/core/management/commands/inspectdb.py
@@ -66,9 +66,9 @@ class Command(NoArgsCommand):
                 indexes = connection.introspection.get_indexes(cursor, table_name)
             except NotImplementedError:
                 indexes = {}
-            used_column_names = [] # Holds column names used in the table so far
+            used_column_names = []  # Holds column names used in the table so far
             for i, row in enumerate(connection.introspection.get_table_description(cursor, table_name)):
-                comment_notes = [] # Holds Field notes, to be displayed in a Python comment.
+                comment_notes = []  # Holds Field notes, to be displayed in a Python comment.
                 extra_params = OrderedDict()  # Holds Field parameters such as 'db_column'.
                 column_name = row[0]
                 is_relation = i in relations
@@ -112,7 +112,7 @@ class Command(NoArgsCommand):
 
                 # Add 'null' and 'blank', if the 'null_ok' flag was present in the
                 # table description.
-                if row[6]: # If it's NULL...
+                if row[6]:  # If it's NULL...
                     if field_type == 'BooleanField(':
                         field_type = 'NullBooleanField('
                     else:
diff --git a/django/core/urlresolvers.py b/django/core/urlresolvers.py
index 723fe626be..76b50916e0 100644
--- a/django/core/urlresolvers.py
+++ b/django/core/urlresolvers.py
@@ -24,9 +24,9 @@ from django.utils import six
 from django.utils.translation import get_language
 
 
-_resolver_cache = {} # Maps URLconf modules to RegexURLResolver instances.
-_ns_resolver_cache = {} # Maps namespaces to RegexURLResolver instances.
-_callable_cache = {} # Maps view and url pattern names to their view functions.
+_resolver_cache = {}  # Maps URLconf modules to RegexURLResolver instances.
+_ns_resolver_cache = {}  # Maps namespaces to RegexURLResolver instances.
+_callable_cache = {}  # Maps view and url pattern names to their view functions.
 
 # SCRIPT_NAME prefixes for each thread are stored here. If there's no entry for
 # the current thread (which is the only one we ever access), it is assumed to
diff --git a/django/core/validators.py b/django/core/validators.py
index cf5ec7aa77..695dda258b 100644
--- a/django/core/validators.py
+++ b/django/core/validators.py
@@ -86,7 +86,7 @@ class EmailValidator(object):
     code = 'invalid'
     user_regex = re.compile(
         r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*$"  # dot-atom
-        r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"$)', # quoted-string
+        r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"$)',  # quoted-string
         re.IGNORECASE)
     domain_regex = re.compile(
         r'(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}|[A-Z0-9-]{2,})$'  # domain
diff --git a/django/db/backends/mysql/base.py b/django/db/backends/mysql/base.py
index 84bbf1569f..b38d00c84a 100644
--- a/django/db/backends/mysql/base.py
+++ b/django/db/backends/mysql/base.py
@@ -226,7 +226,7 @@ class DatabaseOperations(BaseDatabaseOperations):
 
     def date_trunc_sql(self, lookup_type, field_name):
         fields = ['year', 'month', 'day', 'hour', 'minute', 'second']
-        format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape.
+        format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s')  # Use double percents to escape.
         format_def = ('0000-', '01', '-01', ' 00:', '00', ':00')
         try:
             i = fields.index(lookup_type) + 1
@@ -259,7 +259,7 @@ class DatabaseOperations(BaseDatabaseOperations):
         else:
             params = []
         fields = ['year', 'month', 'day', 'hour', 'minute', 'second']
-        format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape.
+        format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s')  # Use double percents to escape.
         format_def = ('0000-', '01', '-01', ' 00:', '00', ':00')
         try:
             i = fields.index(lookup_type) + 1
@@ -300,7 +300,7 @@ class DatabaseOperations(BaseDatabaseOperations):
 
     def quote_name(self, name):
         if name.startswith("`") and name.endswith("`"):
-            return name # Quoting once is enough.
+            return name  # Quoting once is enough.
         return "`%s`" % name
 
     def quote_parameter(self, value):
diff --git a/django/db/backends/oracle/creation.py b/django/db/backends/oracle/creation.py
index fc9a0d034f..6cb2f1467e 100644
--- a/django/db/backends/oracle/creation.py
+++ b/django/db/backends/oracle/creation.py
@@ -147,7 +147,7 @@ class DatabaseCreation(BaseDatabaseCreation):
         }
 
         cursor = self.connection.cursor()
-        time.sleep(1) # To avoid "database is being accessed by other users" errors.
+        time.sleep(1)  # To avoid "database is being accessed by other users" errors.
         if self._test_user_create():
             if verbosity >= 1:
                 print('Destroying test user...')
diff --git a/django/db/backends/oracle/introspection.py b/django/db/backends/oracle/introspection.py
index 9e6e29d5e3..43f61faf0a 100644
--- a/django/db/backends/oracle/introspection.py
+++ b/django/db/backends/oracle/introspection.py
@@ -52,8 +52,8 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
         cursor.execute("SELECT * FROM %s WHERE ROWNUM < 2" % self.connection.ops.quote_name(table_name))
         description = []
         for desc in cursor.description:
-            name = force_text(desc[0]) # cx_Oracle always returns a 'str' on both Python 2 and 3
-            name = name % {} # cx_Oracle, for some reason, doubles percent signs.
+            name = force_text(desc[0])  # cx_Oracle always returns a 'str' on both Python 2 and 3
+            name = name % {}  # cx_Oracle, for some reason, doubles percent signs.
             description.append(FieldInfo(*(name.lower(),) + desc[1:]))
         return description
 
diff --git a/django/db/backends/postgresql_psycopg2/introspection.py b/django/db/backends/postgresql_psycopg2/introspection.py
index 046af9af55..aef0bf08aa 100644
--- a/django/db/backends/postgresql_psycopg2/introspection.py
+++ b/django/db/backends/postgresql_psycopg2/introspection.py
@@ -16,7 +16,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
         700: 'FloatField',
         701: 'FloatField',
         869: 'GenericIPAddressField',
-        1042: 'CharField', # blank-padded
+        1042: 'CharField',  # blank-padded
         1043: 'CharField',
         1082: 'DateField',
         1083: 'TimeField',
diff --git a/django/db/backends/postgresql_psycopg2/operations.py b/django/db/backends/postgresql_psycopg2/operations.py
index 723453c9c5..b9496868b0 100644
--- a/django/db/backends/postgresql_psycopg2/operations.py
+++ b/django/db/backends/postgresql_psycopg2/operations.py
@@ -95,7 +95,7 @@ class DatabaseOperations(BaseDatabaseOperations):
 
     def quote_name(self, name):
         if name.startswith('"') and name.endswith('"'):
-            return name # Quoting once is enough.
+            return name  # Quoting once is enough.
         return '"%s"' % name
 
     def quote_parameter(self, value):
@@ -175,7 +175,7 @@ class DatabaseOperations(BaseDatabaseOperations):
                         style.SQL_KEYWORD('IS NOT'),
                         style.SQL_KEYWORD('FROM'),
                         style.SQL_TABLE(qn(model._meta.db_table))))
-                    break # Only one AutoField is allowed per model, so don't bother continuing.
+                    break  # Only one AutoField is allowed per model, so don't bother continuing.
             for f in model._meta.many_to_many:
                 if not f.rel.through:
                     output.append("%s setval(pg_get_serial_sequence('%s','%s'), coalesce(max(%s), 1), max(%s) %s null) %s %s;" %
diff --git a/django/db/backends/sqlite3/base.py b/django/db/backends/sqlite3/base.py
index 5d07f68f73..6c9728889f 100644
--- a/django/db/backends/sqlite3/base.py
+++ b/django/db/backends/sqlite3/base.py
@@ -212,7 +212,7 @@ class DatabaseOperations(BaseDatabaseOperations):
 
     def quote_name(self, name):
         if name.startswith('"') and name.endswith('"'):
-            return name # Quoting once is enough.
+            return name  # Quoting once is enough.
         return '"%s"' % name
 
     def quote_parameter(self, value):
diff --git a/django/db/backends/sqlite3/introspection.py b/django/db/backends/sqlite3/introspection.py
index 6ebc572e0c..da8629ace6 100644
--- a/django/db/backends/sqlite3/introspection.py
+++ b/django/db/backends/sqlite3/introspection.py
@@ -157,7 +157,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
             # Skip indexes across multiple fields
             if len(info) != 1:
                 continue
-            name = info[0][2] # seqno, cid, name
+            name = info[0][2]  # seqno, cid, name
             indexes[name] = {'primary_key': indexes.get(name, {}).get("primary_key", False),
                              'unique': unique}
         return indexes
diff --git a/django/db/backends/utils.py b/django/db/backends/utils.py
index 095cb4efe4..8bed6415c3 100644
--- a/django/db/backends/utils.py
+++ b/django/db/backends/utils.py
@@ -112,21 +112,21 @@ class CursorDebugWrapper(CursorWrapper):
 ###############################################
 
 def typecast_date(s):
-    return datetime.date(*map(int, s.split('-'))) if s else None # returns None if s is null
+    return datetime.date(*map(int, s.split('-'))) if s else None  # returns None if s is null
 
 
-def typecast_time(s): # does NOT store time zone information
+def typecast_time(s):  # does NOT store time zone information
     if not s:
         return None
     hour, minutes, seconds = s.split(':')
-    if '.' in seconds: # check whether seconds have a fractional part
+    if '.' in seconds:  # check whether seconds have a fractional part
         seconds, microseconds = seconds.split('.')
     else:
         microseconds = '0'
     return datetime.time(int(hour), int(minutes), int(seconds), int(float('.' + microseconds) * 1000000))
 
 
-def typecast_timestamp(s): # does NOT store time zone information
+def typecast_timestamp(s):  # does NOT store time zone information
     # "2005-07-29 15:48:00.590358-05"
     # "2005-07-29 09:56:00-05"
     if not s:
@@ -147,7 +147,7 @@ def typecast_timestamp(s): # does NOT store time zone information
     dates = d.split('-')
     times = t.split(':')
     seconds = times[2]
-    if '.' in seconds: # check whether seconds have a fractional part
+    if '.' in seconds:  # check whether seconds have a fractional part
         seconds, microseconds = seconds.split('.')
     else:
         microseconds = '0'
diff --git a/django/db/models/__init__.py b/django/db/models/__init__.py
index cf219d39aa..13785ed17a 100644
--- a/django/db/models/__init__.py
+++ b/django/db/models/__init__.py
@@ -11,7 +11,7 @@ from django.db.models.base import Model  # NOQA
 from django.db.models.aggregates import *  # NOQA
 from django.db.models.fields import *  # NOQA
 from django.db.models.fields.subclassing import SubfieldBase        # NOQA
-from django.db.models.fields.files import FileField, ImageField # NOQA
+from django.db.models.fields.files import FileField, ImageField  # NOQA
 from django.db.models.fields.related import (  # NOQA
     ForeignKey, ForeignObject, OneToOneField, ManyToManyField,
     ManyToOneRel, ManyToManyRel, OneToOneRel)
diff --git a/django/db/models/base.py b/django/db/models/base.py
index 73df8633ca..ce3f095055 100644
--- a/django/db/models/base.py
+++ b/django/db/models/base.py
@@ -280,7 +280,7 @@ class ModelBase(type):
     def copy_managers(cls, base_managers):
         # This is in-place sorting of an Options attribute, but that's fine.
         base_managers.sort()
-        for _, mgr_name, manager in base_managers: # NOQA (redefinition of _)
+        for _, mgr_name, manager in base_managers:  # NOQA (redefinition of _)
             val = getattr(cls, mgr_name, None)
             if not val or val is manager:
                 new_manager = manager._copy_to_model(cls)
diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py
index 022de52134..dec2e2dd9e 100644
--- a/django/db/models/fields/__init__.py
+++ b/django/db/models/fields/__init__.py
@@ -93,7 +93,7 @@ class Field(object):
     # creates, creation_counter is used for all user-specified fields.
     creation_counter = 0
     auto_creation_counter = -1
-    default_validators = [] # Default set of validators
+    default_validators = []  # Default set of validators
     default_error_messages = {
         'invalid_choice': _('Value %(value)r is not a valid choice.'),
         'null': _('This field cannot be null.'),
diff --git a/django/db/models/query.py b/django/db/models/query.py
index ca49f67712..5bfa68b071 100644
--- a/django/db/models/query.py
+++ b/django/db/models/query.py
@@ -1627,16 +1627,16 @@ def prefetch_related_objects(result_cache, related_lookups):
     from a QuerySet
     """
     if len(result_cache) == 0:
-        return # nothing to do
+        return  # nothing to do
 
     # We need to be able to dynamically add to the list of prefetch_related
     # lookups that we look up (see below).  So we need some book keeping to
     # ensure we don't do duplicate work.
-    done_lookups = set() # list of lookups like foo__bar__baz
+    done_lookups = set()  # list of lookups like foo__bar__baz
     done_queries = {}    # dictionary of things like 'foo__bar': [results]
 
-    auto_lookups = [] # we add to this as we go through.
-    followed_descriptors = set() # recursion protection
+    auto_lookups = []  # we add to this as we go through.
+    followed_descriptors = set()  # recursion protection
 
     all_lookups = itertools.chain(related_lookups, auto_lookups)
     for lookup in all_lookups:
diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py
index 46a308f5ce..988b8bc644 100644
--- a/django/db/models/sql/query.py
+++ b/django/db/models/sql/query.py
@@ -146,7 +146,7 @@ class Query(object):
         # The _aggregates will be an OrderedDict when used. Due to the cost
         # of creating OrderedDict this attribute is created lazily (in
         # self.aggregates property).
-        self._aggregates = None # Maps alias -> SQL aggregate function
+        self._aggregates = None  # Maps alias -> SQL aggregate function
         self.aggregate_select_mask = None
         self._aggregate_select_cache = None
 
diff --git a/django/http/multipartparser.py b/django/http/multipartparser.py
index 664a817f37..28c0195a48 100644
--- a/django/http/multipartparser.py
+++ b/django/http/multipartparser.py
@@ -127,7 +127,7 @@ class MultiPartParser(object):
                                               self._content_length,
                                               self._boundary,
                                               encoding)
-            #Check to see if it was handled
+            # Check to see if it was handled
             if result is not None:
                 return result[0], result[1]
 
@@ -483,7 +483,7 @@ class BoundaryIter(six.Iterator):
         else:
             # make sure we dont treat a partial boundary (and
             # its separators) as data
-            if not chunk[:-rollback]:# and len(chunk) >= (len(self._boundary) + 6):
+            if not chunk[:-rollback]:  # and len(chunk) >= (len(self._boundary) + 6):
                 # There's nothing left, we should just return and mark as done.
                 self._done = True
                 return chunk
diff --git a/django/http/request.py b/django/http/request.py
index 07ab6cb27d..4d11fb21e0 100644
--- a/django/http/request.py
+++ b/django/http/request.py
@@ -249,13 +249,13 @@ class HttpRequest(object):
         else:
             self._post, self._files = QueryDict('', encoding=self._encoding), MultiValueDict()
 
-    ## File-like and iterator interface.
-    ##
-    ## Expects self._stream to be set to an appropriate source of bytes by
-    ## a corresponding request subclass (e.g. WSGIRequest).
-    ## Also when request data has already been read by request.POST or
-    ## request.body, self._stream points to a BytesIO instance
-    ## containing that data.
+    # File-like and iterator interface.
+    #
+    # Expects self._stream to be set to an appropriate source of bytes by
+    # a corresponding request subclass (e.g. WSGIRequest).
+    # Also when request data has already been read by request.POST or
+    # request.body, self._stream points to a BytesIO instance
+    # containing that data.
 
     def read(self, *args, **kwargs):
         self._read_started = True
diff --git a/django/middleware/cache.py b/django/middleware/cache.py
index 96c6b24034..361e46f5e5 100644
--- a/django/middleware/cache.py
+++ b/django/middleware/cache.py
@@ -134,13 +134,13 @@ class FetchFromCacheMiddleware(object):
         """
         if not request.method in ('GET', 'HEAD'):
             request._cache_update_cache = False
-            return None # Don't bother checking the cache.
+            return None  # Don't bother checking the cache.
 
         # try and get the cached GET response
         cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache)
         if cache_key is None:
             request._cache_update_cache = True
-            return None # No cache information available, need to rebuild.
+            return None  # No cache information available, need to rebuild.
         response = self.cache.get(cache_key, None)
         # if it wasn't found and we are looking for a HEAD, try looking just for that
         if response is None and request.method == 'HEAD':
@@ -149,7 +149,7 @@ class FetchFromCacheMiddleware(object):
 
         if response is None:
             request._cache_update_cache = True
-            return None # No cache information available, need to rebuild.
+            return None  # No cache information available, need to rebuild.
 
         # hit, return cached response
         request._cache_update_cache = False
diff --git a/django/templatetags/cache.py b/django/templatetags/cache.py
index 0de00210fe..1ef97d7cf0 100644
--- a/django/templatetags/cache.py
+++ b/django/templatetags/cache.py
@@ -87,7 +87,7 @@ def do_cache(parser, token):
         cache_name = None
     return CacheNode(nodelist,
         parser.compile_filter(tokens[1]),
-        tokens[2], # fragment_name can't be a variable.
+        tokens[2],  # fragment_name can't be a variable.
         [parser.compile_filter(t) for t in tokens[3:]],
         cache_name,
     )
diff --git a/django/test/_doctest.py b/django/test/_doctest.py
index 2b90f1dc2e..048d886720 100644
--- a/django/test/_doctest.py
+++ b/django/test/_doctest.py
@@ -898,7 +898,7 @@ class DocTestFinder:
         elif hasattr(object, '__module__'):
             return module.__name__ == object.__module__
         elif isinstance(object, property):
-            return True # [XX] no way not be sure.
+            return True  # [XX] no way not be sure.
         else:
             raise ValueError("object must be a class or function")
 
@@ -1221,7 +1221,7 @@ class DocTestRunner:
         # to modify them).
         original_optionflags = self.optionflags
 
-        SUCCESS, FAILURE, BOOM = range(3) # `outcome` state
+        SUCCESS, FAILURE, BOOM = range(3)  # `outcome` state
 
         check = self._checker.check_output
 
@@ -1274,7 +1274,7 @@ class DocTestRunner:
                     # Strip b"" and u"" prefixes from the repr and expected output
                     # TODO: better way of stripping the prefixes?
                     expected = example.want
-                    expected = expected.strip() # be wary of newlines
+                    expected = expected.strip()  # be wary of newlines
                     s = s.replace("u", "")
                     s = s.replace("b", "")
                     expected = expected.replace("u", "")
@@ -1288,7 +1288,7 @@ class DocTestRunner:
                     lines.append(s)
 
                     # let them match
-                    if s == expected: # be wary of false positives here
+                    if s == expected:  # be wary of false positives here
                         # they should be the same, print expected value
                         sys.stdout.write("%s\n" % example.want.strip())
 
@@ -1314,13 +1314,13 @@ class DocTestRunner:
                 # Don't blink!  This is where the user's code gets run.
                 six.exec_(compile(example.source, filename, "single",
                              compileflags, 1), test.globs)
-                self.debugger.set_continue() # ==== Example Finished ====
+                self.debugger.set_continue()  # ==== Example Finished ====
                 exception = None
             except KeyboardInterrupt:
                 raise
             except:
                 exception = sys.exc_info()
-                self.debugger.set_continue() # ==== Example Finished ====
+                self.debugger.set_continue()  # ==== Example Finished ====
             finally:
                 # restore the original displayhook
                 sys.displayhook = original_displayhook
@@ -1647,11 +1647,11 @@ class OutputChecker:
             # Use difflib to find their differences.
             if optionflags & REPORT_UDIFF:
                 diff = difflib.unified_diff(want_lines, got_lines, n=2)
-                diff = list(diff)[2:] # strip the diff header
+                diff = list(diff)[2:]  # strip the diff header
                 kind = 'unified diff with -expected +actual'
             elif optionflags & REPORT_CDIFF:
                 diff = difflib.context_diff(want_lines, got_lines, n=2)
-                diff = list(diff)[2:] # strip the diff header
+                diff = list(diff)[2:]  # strip the diff header
                 kind = 'context diff with expected followed by actual'
             elif optionflags & REPORT_NDIFF:
                 engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
diff --git a/django/test/simple.py b/django/test/simple.py
index b2ab1269b5..05a7329fae 100644
--- a/django/test/simple.py
+++ b/django/test/simple.py
@@ -191,7 +191,7 @@ def build_test(label):
 
     try:
         if issubclass(TestClass, (unittest.TestCase, real_unittest.TestCase)):
-            if len(parts) == 2: # label is app.TestClass
+            if len(parts) == 2:  # label is app.TestClass
                 try:
                     return unittest.TestLoader().loadTestsFromTestCase(
                         TestClass)
@@ -199,7 +199,7 @@ def build_test(label):
                     raise ValueError(
                         "Test label '%s' does not refer to a test class"
                         % label)
-            else: # label is app.TestClass.test_method
+            else:  # label is app.TestClass.test_method
                 return TestClass(parts[2])
     except TypeError:
         # TestClass isn't a TestClass - it must be a method or normal class
diff --git a/django/utils/dictconfig.py b/django/utils/dictconfig.py
index d01b785001..773b703497 100644
--- a/django/utils/dictconfig.py
+++ b/django/utils/dictconfig.py
@@ -71,7 +71,7 @@ class ConvertingDict(dict):
     def __getitem__(self, key):
         value = dict.__getitem__(self, key)
         result = self.configurator.convert(value)
-        #If the converted value is different, save for next time
+        # If the converted value is different, save for next time
         if value is not result:
             self[key] = result
             if type(result) in (ConvertingDict, ConvertingList,
@@ -83,7 +83,7 @@ class ConvertingDict(dict):
     def get(self, key, default=None):
         value = dict.get(self, key, default)
         result = self.configurator.convert(value)
-        #If the converted value is different, save for next time
+        # If the converted value is different, save for next time
         if value is not result:
             self[key] = result
             if type(result) in (ConvertingDict, ConvertingList,
@@ -107,7 +107,7 @@ class ConvertingList(list):
     def __getitem__(self, key):
         value = list.__getitem__(self, key)
         result = self.configurator.convert(value)
-        #If the converted value is different, save for next time
+        # If the converted value is different, save for next time
         if value is not result:
             self[key] = result
             if type(result) in (ConvertingDict, ConvertingList,
@@ -197,7 +197,7 @@ class BaseConfigurator(object):
         else:
             rest = rest[m.end():]
             d = self.config[m.groups()[0]]
-            #print d, rest
+            # print d, rest
             while rest:
                 m = self.DOT_PATTERN.match(rest)
                 if m:
@@ -219,7 +219,7 @@ class BaseConfigurator(object):
                 else:
                     raise ValueError('Unable to convert '
                                      '%r at %r' % (value, rest))
-        #rest should be empty
+        # rest should be empty
         return d
 
     def convert(self, value):
@@ -359,25 +359,25 @@ class DictConfigurator(BaseConfigurator):
                                          '%r: %s' % (name, e))
                 # Next, do loggers - they refer to handlers and filters
 
-                #we don't want to lose the existing loggers,
-                #since other threads may have pointers to them.
-                #existing is set to contain all existing loggers,
-                #and as we go through the new configuration we
-                #remove any which are configured. At the end,
-                #what's left in existing is the set of loggers
-                #which were in the previous configuration but
-                #which are not in the new configuration.
+                # we don't want to lose the existing loggers,
+                # since other threads may have pointers to them.
+                # existing is set to contain all existing loggers,
+                # and as we go through the new configuration we
+                # remove any which are configured. At the end,
+                # what's left in existing is the set of loggers
+                # which were in the previous configuration but
+                # which are not in the new configuration.
                 root = logging.root
                 existing = list(root.manager.loggerDict)
-                #The list needs to be sorted so that we can
-                #avoid disabling child loggers of explicitly
-                #named loggers. With a sorted list it is easier
-                #to find the child loggers.
+                # The list needs to be sorted so that we can
+                # avoid disabling child loggers of explicitly
+                # named loggers. With a sorted list it is easier
+                # to find the child loggers.
                 existing.sort()
-                #We'll keep the list of existing loggers
-                #which are children of named loggers here...
+                # We'll keep the list of existing loggers
+                # which are children of named loggers here...
                 child_loggers = []
-                #now set up the new ones...
+                # now set up the new ones...
                 loggers = config.get('loggers', EMPTY_DICT)
                 for name in loggers:
                     if name in existing:
@@ -397,11 +397,11 @@ class DictConfigurator(BaseConfigurator):
                         raise ValueError('Unable to configure logger '
                                          '%r: %s' % (name, e))
 
-                #Disable any old loggers. There's no point deleting
-                #them as other threads may continue to hold references
-                #and by disabling them, you stop them doing any logging.
-                #However, don't disable children of named loggers, as that's
-                #probably not what was intended by the user.
+                # Disable any old loggers. There's no point deleting
+                # them as other threads may continue to hold references
+                # and by disabling them, you stop them doing any logging.
+                # However, don't disable children of named loggers, as that's
+                # probably not what was intended by the user.
                 for log in existing:
                     logger = root.manager.loggerDict[log]
                     if log in child_loggers:
@@ -431,9 +431,9 @@ class DictConfigurator(BaseConfigurator):
             except TypeError as te:
                 if "'format'" not in str(te):
                     raise
-                #Name of parameter changed from fmt to format.
-                #Retry with old name.
-                #This is so that code can be used with older Python versions
+                # Name of parameter changed from fmt to format.
+                # Retry with old name.
+                # This is so that code can be used with older Python versions
                 #(e.g. by Django)
                 config['fmt'] = config.pop('format')
                 config['()'] = factory
@@ -479,7 +479,7 @@ class DictConfigurator(BaseConfigurator):
             factory = c
         else:
             klass = self.resolve(config.pop('class'))
-            #Special case for handler which refers to another handler
+            # Special case for handler which refers to another handler
             if issubclass(klass, logging.handlers.MemoryHandler) and\
                 'target' in config:
                 try:
@@ -500,9 +500,9 @@ class DictConfigurator(BaseConfigurator):
         except TypeError as te:
             if "'stream'" not in str(te):
                 raise
-            #The argument name changed from strm to stream
-            #Retry with old name.
-            #This is so that code can be used with older Python versions
+            # The argument name changed from strm to stream
+            # Retry with old name.
+            # This is so that code can be used with older Python versions
             #(e.g. by Django)
             kwargs['strm'] = kwargs.pop('stream')
             result = factory(**kwargs)
@@ -530,7 +530,7 @@ class DictConfigurator(BaseConfigurator):
         if level is not None:
             logger.setLevel(_checkLevel(level))
         if not incremental:
-            #Remove any existing handlers
+            # Remove any existing handlers
             for h in logger.handlers[:]:
                 logger.removeHandler(h)
             handlers = config.get('handlers', None)
diff --git a/django/views/debug.py b/django/views/debug.py
index 96d3e65189..2829ca1443 100644
--- a/django/views/debug.py
+++ b/django/views/debug.py
@@ -483,7 +483,7 @@ def technical_404_response(request, exception):
     c = Context({
         'urlconf': urlconf,
         'root_urlconf': settings.ROOT_URLCONF,
-        'request_path': request.path_info[1:], # Trim leading slash
+        'request_path': request.path_info[1:],  # Trim leading slash
         'urlpatterns': tried,
         'reason': force_bytes(exception, errors='replace'),
         'request': request,
diff --git a/docs/conf.py b/docs/conf.py
index f8625e73d9..49e70fab84 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -117,7 +117,7 @@ intersphinx_mapping = {
 }
 
 # Python's docs don't change every week.
-intersphinx_cache_limit = 90 # days
+intersphinx_cache_limit = 90  # days
 
 # -- Options for HTML output ---------------------------------------------------
 
diff --git a/setup.cfg b/setup.cfg
index 9a4776a319..994c4e5431 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -4,7 +4,7 @@ install-script = scripts/rpm-install.sh
 
 [flake8]
 exclude=./django/utils/dictconfig.py,./django/contrib/comments/*,./django/utils/unittest.py,./tests/comment_tests/*,./django/test/_doctest.py,./django/utils/six.py,./django/conf/app_template/*
-ignore=E124,E125,E127,E128,E226,E251,E501,E261,W601
+ignore=E124,E125,E127,E128,E226,E251,E501,W601
 
 [metadata]
 license-file = LICENSE
diff --git a/tests/admin_changelist/admin.py b/tests/admin_changelist/admin.py
index d0797581dc..42b8c959af 100644
--- a/tests/admin_changelist/admin.py
+++ b/tests/admin_changelist/admin.py
@@ -98,7 +98,7 @@ site.register(Parent, NoListDisplayLinksParentAdmin)
 
 
 class SwallowAdmin(admin.ModelAdmin):
-    actions = None # prevent ['action_checkbox'] + list(list_display)
+    actions = None  # prevent ['action_checkbox'] + list(list_display)
     list_display = ('origin', 'load', 'speed')
 
 site.register(Swallow, SwallowAdmin)
diff --git a/tests/admin_filters/models.py b/tests/admin_filters/models.py
index e0b8bde2de..bd2e4e5e98 100644
--- a/tests/admin_filters/models.py
+++ b/tests/admin_filters/models.py
@@ -13,7 +13,7 @@ class Book(models.Model):
     contributors = models.ManyToManyField(User, verbose_name="Verbose Contributors", related_name='books_contributed', blank=True, null=True)
     is_best_seller = models.NullBooleanField(default=0)
     date_registered = models.DateField(null=True)
-    no = models.IntegerField(verbose_name='number', blank=True, null=True) # This field is intentionally 2 characters long. See #16080.
+    no = models.IntegerField(verbose_name='number', blank=True, null=True)  # This field is intentionally 2 characters long. See #16080.
 
     def __str__(self):
         return self.title
diff --git a/tests/admin_filters/tests.py b/tests/admin_filters/tests.py
index bdfacdc206..bbec124d4d 100644
--- a/tests/admin_filters/tests.py
+++ b/tests/admin_filters/tests.py
@@ -78,12 +78,12 @@ class DecadeListFilterWithQuerysetBasedLookups(DecadeListFilterWithTitleAndParam
 
 class DecadeListFilterParameterEndsWith__In(DecadeListFilter):
     title = 'publication decade'
-    parameter_name = 'decade__in' # Ends with '__in"
+    parameter_name = 'decade__in'  # Ends with '__in"
 
 
 class DecadeListFilterParameterEndsWith__Isnull(DecadeListFilter):
     title = 'publication decade'
-    parameter_name = 'decade__isnull' # Ends with '__isnull"
+    parameter_name = 'decade__isnull'  # Ends with '__isnull"
 
 
 class DepartmentListFilterLookupWithNonStringValue(SimpleListFilter):
diff --git a/tests/admin_inlines/admin.py b/tests/admin_inlines/admin.py
index 98c19befa4..da5ddc03b3 100644
--- a/tests/admin_inlines/admin.py
+++ b/tests/admin_inlines/admin.py
@@ -43,7 +43,7 @@ class AuthorAdmin(admin.ModelAdmin):
 class InnerInline(admin.StackedInline):
     model = Inner
     can_delete = False
-    readonly_fields = ('readonly',) # For bug #13174 tests.
+    readonly_fields = ('readonly',)  # For bug #13174 tests.
 
 
 class HolderAdmin(admin.ModelAdmin):
diff --git a/tests/admin_ordering/tests.py b/tests/admin_ordering/tests.py
index 763e97bd72..0085b35586 100644
--- a/tests/admin_ordering/tests.py
+++ b/tests/admin_ordering/tests.py
@@ -51,7 +51,7 @@ class TestAdminOrdering(TestCase):
         it actually changes.
         """
         class BandAdmin(ModelAdmin):
-            ordering = ('rank',) # default ordering is ('name',)
+            ordering = ('rank',)  # default ordering is ('name',)
         ma = BandAdmin(Band, None)
         names = [b.name for b in ma.get_queryset(request)]
         self.assertEqual(['Radiohead', 'Van Halen', 'Aerosmith'], names)
diff --git a/tests/admin_views/admin.py b/tests/admin_views/admin.py
index 36b35aeefe..2aa96fbafa 100644
--- a/tests/admin_views/admin.py
+++ b/tests/admin_views/admin.py
@@ -262,7 +262,7 @@ class Podcast(Media):
     release_date = models.DateField()
 
     class Meta:
-        ordering = ('release_date',) # overridden in PodcastAdmin
+        ordering = ('release_date',)  # overridden in PodcastAdmin
 
 
 class PodcastAdmin(admin.ModelAdmin):
@@ -444,7 +444,7 @@ class PostAdmin(admin.ModelAdmin):
 
 class CustomChangeList(ChangeList):
     def get_queryset(self, request):
-        return self.root_queryset.filter(pk=9999) # Does not exist
+        return self.root_queryset.filter(pk=9999)  # Does not exist
 
 
 class GadgetAdmin(admin.ModelAdmin):
@@ -527,7 +527,7 @@ class StoryForm(forms.ModelForm):
 
 class StoryAdmin(admin.ModelAdmin):
     list_display = ('id', 'title', 'content')
-    list_display_links = ('title',) # 'id' not in list_display_links
+    list_display_links = ('title',)  # 'id' not in list_display_links
     list_editable = ('content', )
     form = StoryForm
     ordering = ["-pk"]
@@ -535,7 +535,7 @@ class StoryAdmin(admin.ModelAdmin):
 
 class OtherStoryAdmin(admin.ModelAdmin):
     list_display = ('id', 'title', 'content')
-    list_display_links = ('title', 'id') # 'id' in list_display_links
+    list_display_links = ('title', 'id')  # 'id' in list_display_links
     list_editable = ('content', )
     ordering = ["-pk"]
 
diff --git a/tests/admin_views/customadmin.py b/tests/admin_views/customadmin.py
index f964d6cffb..560b4409c2 100644
--- a/tests/admin_views/customadmin.py
+++ b/tests/admin_views/customadmin.py
@@ -17,7 +17,7 @@ class Admin2(admin.AdminSite):
     login_form = forms.CustomAdminAuthenticationForm
     login_template = 'custom_admin/login.html'
     logout_template = 'custom_admin/logout.html'
-    index_template = ['custom_admin/index.html'] # a list, to test fix for #18697
+    index_template = ['custom_admin/index.html']  # a list, to test fix for #18697
     password_change_template = 'custom_admin/password_change_form.html'
     password_change_done_template = 'custom_admin/password_change_done.html'
 
@@ -42,7 +42,7 @@ class UserLimitedAdmin(UserAdmin):
 
 
 class CustomPwdTemplateUserAdmin(UserAdmin):
-    change_user_password_template = ['admin/auth/user/change_password.html'] # a list, to test fix for #18697
+    change_user_password_template = ['admin/auth/user/change_password.html']  # a list, to test fix for #18697
 
 
 site = Admin2(name="admin2")
diff --git a/tests/admin_views/models.py b/tests/admin_views/models.py
index 67f3b4216a..4dcca9a4cb 100644
--- a/tests/admin_views/models.py
+++ b/tests/admin_views/models.py
@@ -256,7 +256,7 @@ class Podcast(Media):
     release_date = models.DateField()
 
     class Meta:
-        ordering = ('release_date',) # overridden in PodcastAdmin
+        ordering = ('release_date',)  # overridden in PodcastAdmin
 
 
 class Vodcast(Media):
diff --git a/tests/admin_widgets/tests.py b/tests/admin_widgets/tests.py
index 0aa8e98933..4b36f8bd32 100644
--- a/tests/admin_widgets/tests.py
+++ b/tests/admin_widgets/tests.py
@@ -911,7 +911,7 @@ class HorizontalVerticalFilterSeleniumFirefoxTests(AdminSeleniumWebDriverTestCas
             self.assertSelectOptions(to_box,
                         [str(self.peter.id), str(self.jason.id)])
 
-            input.send_keys([Keys.BACK_SPACE]) # Clear text box
+            input.send_keys([Keys.BACK_SPACE])  # Clear text box
             self.assertSelectOptions(from_box,
                         [str(self.arthur.id), str(self.bob.id),
                          str(self.cliff.id), str(self.jenny.id),
@@ -922,7 +922,7 @@ class HorizontalVerticalFilterSeleniumFirefoxTests(AdminSeleniumWebDriverTestCas
         # Save and check that everything is properly stored in the database ---
         self.selenium.find_element_by_xpath('//input[@value="Save"]').click()
         self.wait_page_loaded()
-        self.school = models.School.objects.get(id=self.school.id) # Reload from database
+        self.school = models.School.objects.get(id=self.school.id)  # Reload from database
         self.assertEqual(list(self.school.students.all()),
                          [self.jason, self.peter])
         self.assertEqual(list(self.school.alumni.all()),
diff --git a/tests/aggregation_regress/tests.py b/tests/aggregation_regress/tests.py
index 8e192bd082..be42a13181 100644
--- a/tests/aggregation_regress/tests.py
+++ b/tests/aggregation_regress/tests.py
@@ -70,7 +70,7 @@ class AggregationTests(TestCase):
         Regression test for #11916: Extra params + aggregation creates
         incorrect SQL.
         """
-        #oracle doesn't support subqueries in group by clause
+        # oracle doesn't support subqueries in group by clause
         shortest_book_sql = """
         SELECT name
         FROM aggregation_regress_book b
diff --git a/tests/cache/tests.py b/tests/cache/tests.py
index 0c6ae91553..a79d4d9fac 100644
--- a/tests/cache/tests.py
+++ b/tests/cache/tests.py
@@ -1486,7 +1486,7 @@ class CacheI18nTest(TestCase):
         request = self._get_request()
         response = HttpResponse()
         with timezone.override(CustomTzName()):
-            CustomTzName.name = 'Hora estƔndar de Argentina'.encode('UTF-8') # UTF-8 string
+            CustomTzName.name = 'Hora estƔndar de Argentina'.encode('UTF-8')  # UTF-8 string
             sanitized_name = 'Hora_estndar_de_Argentina'
             self.assertIn(sanitized_name, learn_cache_key(request, response),
                     "Cache keys should include the time zone name when time zones are active")
@@ -1645,9 +1645,9 @@ class CacheMiddlewareTest(IgnoreDeprecationWarningsMixin, TestCase):
         # First, test with "defaults":
         as_view_decorator = CacheMiddleware(cache_alias=None, key_prefix=None)
 
-        self.assertEqual(as_view_decorator.cache_timeout, 300) # Timeout value for 'default' cache, i.e. 300
+        self.assertEqual(as_view_decorator.cache_timeout, 300)  # Timeout value for 'default' cache, i.e. 300
         self.assertEqual(as_view_decorator.key_prefix, '')
-        self.assertEqual(as_view_decorator.cache_alias, 'default') # Value of DEFAULT_CACHE_ALIAS from django.core.cache
+        self.assertEqual(as_view_decorator.cache_alias, 'default')  # Value of DEFAULT_CACHE_ALIAS from django.core.cache
         self.assertEqual(as_view_decorator.cache_anonymous_only, False)
 
         # Next, test with custom values:
diff --git a/tests/comment_tests/tests/test_moderation_views.py b/tests/comment_tests/tests/test_moderation_views.py
index 62007e43fb..b70b01ed16 100644
--- a/tests/comment_tests/tests/test_moderation_views.py
+++ b/tests/comment_tests/tests/test_moderation_views.py
@@ -304,12 +304,12 @@ class AdminActionsTests(CommentTestCase):
         makeModerator("normaluser")
         self.client.login(username="normaluser", password="normaluser")
         with translation.override('en'):
-            #Test approving
+            # Test approving
             self.performActionAndCheckMessage('approve_comments', one_comment, '1 comment was successfully approved')
             self.performActionAndCheckMessage('approve_comments', many_comments, '3 comments were successfully approved')
-            #Test flagging
+            # Test flagging
             self.performActionAndCheckMessage('flag_comments', one_comment, '1 comment was successfully flagged')
             self.performActionAndCheckMessage('flag_comments', many_comments, '3 comments were successfully flagged')
-            #Test removing
+            # Test removing
             self.performActionAndCheckMessage('remove_comments', one_comment, '1 comment was successfully removed')
             self.performActionAndCheckMessage('remove_comments', many_comments, '3 comments were successfully removed')
diff --git a/tests/datatypes/tests.py b/tests/datatypes/tests.py
index 41e8a2d5d3..3cd954d3ad 100644
--- a/tests/datatypes/tests.py
+++ b/tests/datatypes/tests.py
@@ -37,7 +37,7 @@ class DataTypesTestCase(TestCase):
         self.assertEqual(d2.consumed_at, datetime.datetime(2007, 4, 20, 16, 19, 59))
 
     def test_time_field(self):
-        #Test for ticket #12059: TimeField wrongly handling datetime.datetime object.
+        # Test for ticket #12059: TimeField wrongly handling datetime.datetime object.
         d = Donut(name='Apple Fritter')
         d.baked_time = datetime.datetime(year=2007, month=4, day=20, hour=16, minute=19, second=59)
         d.save()
diff --git a/tests/file_uploads/uploadhandler.py b/tests/file_uploads/uploadhandler.py
index b30ef136e9..2d4e52e4d5 100644
--- a/tests/file_uploads/uploadhandler.py
+++ b/tests/file_uploads/uploadhandler.py
@@ -11,7 +11,7 @@ class QuotaUploadHandler(FileUploadHandler):
     (5MB) is uploaded.
     """
 
-    QUOTA = 5 * 2**20 # 5 MB
+    QUOTA = 5 * 2**20  # 5 MB
 
     def __init__(self, request=None):
         super(QuotaUploadHandler, self).__init__(request)
diff --git a/tests/forms_tests/tests/test_forms.py b/tests/forms_tests/tests/test_forms.py
index aecf8f32d5..b30742106b 100644
--- a/tests/forms_tests/tests/test_forms.py
+++ b/tests/forms_tests/tests/test_forms.py
@@ -938,7 +938,7 @@ class FormsTestCase(TestCase):
         class UserRegistration(Form):
             username = CharField(max_length=10)                   # uses TextInput by default
             password = CharField(max_length=10, widget=PasswordInput)
-            realname = CharField(max_length=10, widget=TextInput) # redundantly define widget, just to test
+            realname = CharField(max_length=10, widget=TextInput)  # redundantly define widget, just to test
             address = CharField()                                 # no max_length defined here
 
         p = UserRegistration(auto_id=False)
diff --git a/tests/forms_tests/tests/test_formsets.py b/tests/forms_tests/tests/test_formsets.py
index 784724bf41..cf721b5510 100644
--- a/tests/forms_tests/tests/test_formsets.py
+++ b/tests/forms_tests/tests/test_formsets.py
@@ -198,10 +198,10 @@ class FormsFormsetTestCase(TestCase):
         # number of forms to be completed.
 
         data = {
-            'choices-TOTAL_FORMS': '3', # the number of forms rendered
-            'choices-INITIAL_FORMS': '0', # the number of forms with initial data
-            'choices-MIN_NUM_FORMS': '0', # min number of forms
-            'choices-MAX_NUM_FORMS': '0', # max number of forms
+            'choices-TOTAL_FORMS': '3',  # the number of forms rendered
+            'choices-INITIAL_FORMS': '0',  # the number of forms with initial data
+            'choices-MIN_NUM_FORMS': '0',  # min number of forms
+            'choices-MAX_NUM_FORMS': '0',  # max number of forms
             'choices-0-choice': '',
             'choices-0-votes': '',
             'choices-1-choice': '',
@@ -251,10 +251,10 @@ class FormsFormsetTestCase(TestCase):
         # We can just fill out one of the forms.
 
         data = {
-            'choices-TOTAL_FORMS': '3', # the number of forms rendered
-            'choices-INITIAL_FORMS': '0', # the number of forms with initial data
-            'choices-MIN_NUM_FORMS': '0', # min number of forms
-            'choices-MAX_NUM_FORMS': '0', # max number of forms
+            'choices-TOTAL_FORMS': '3',  # the number of forms rendered
+            'choices-INITIAL_FORMS': '0',  # the number of forms with initial data
+            'choices-MIN_NUM_FORMS': '0',  # min number of forms
+            'choices-MAX_NUM_FORMS': '0',  # max number of forms
             'choices-0-choice': 'Calexico',
             'choices-0-votes': '100',
             'choices-1-choice': '',
@@ -275,10 +275,10 @@ class FormsFormsetTestCase(TestCase):
         # value in the returned data is not checked)
 
         data = {
-            'choices-TOTAL_FORMS': '2', # the number of forms rendered
-            'choices-INITIAL_FORMS': '0', # the number of forms with initial data
-            'choices-MIN_NUM_FORMS': '0', # min number of forms
-            'choices-MAX_NUM_FORMS': '2', # max number of forms - should be ignored
+            'choices-TOTAL_FORMS': '2',  # the number of forms rendered
+            'choices-INITIAL_FORMS': '0',  # the number of forms with initial data
+            'choices-MIN_NUM_FORMS': '0',  # min number of forms
+            'choices-MAX_NUM_FORMS': '2',  # max number of forms - should be ignored
             'choices-0-choice': 'Zero',
             'choices-0-votes': '0',
             'choices-1-choice': 'One',
@@ -297,10 +297,10 @@ class FormsFormsetTestCase(TestCase):
         # value in the returned data is not checked)
 
         data = {
-            'choices-TOTAL_FORMS': '2', # the number of forms rendered
-            'choices-INITIAL_FORMS': '0', # the number of forms with initial data
-            'choices-MIN_NUM_FORMS': '0', # min number of forms
-            'choices-MAX_NUM_FORMS': '0', # max number of forms - should be ignored
+            'choices-TOTAL_FORMS': '2',  # the number of forms rendered
+            'choices-INITIAL_FORMS': '0',  # the number of forms with initial data
+            'choices-MIN_NUM_FORMS': '0',  # min number of forms
+            'choices-MAX_NUM_FORMS': '0',  # max number of forms - should be ignored
             'choices-0-choice': 'Zero',
             'choices-0-votes': '0',
             'choices-1-choice': 'One',
@@ -316,14 +316,14 @@ class FormsFormsetTestCase(TestCase):
         # And once again, if we try to partially complete a form, validation will fail.
 
         data = {
-            'choices-TOTAL_FORMS': '3', # the number of forms rendered
-            'choices-INITIAL_FORMS': '0', # the number of forms with initial data
-            'choices-MIN_NUM_FORMS': '0', # min number of forms
-            'choices-MAX_NUM_FORMS': '0', # max number of forms
+            'choices-TOTAL_FORMS': '3',  # the number of forms rendered
+            'choices-INITIAL_FORMS': '0',  # the number of forms with initial data
+            'choices-MIN_NUM_FORMS': '0',  # min number of forms
+            'choices-MAX_NUM_FORMS': '0',  # max number of forms
             'choices-0-choice': 'Calexico',
             'choices-0-votes': '100',
             'choices-1-choice': 'The Decemberists',
-            'choices-1-votes': '', # missing value
+            'choices-1-votes': '',  # missing value
             'choices-2-choice': '',
             'choices-2-votes': '',
         }
@@ -388,10 +388,10 @@ class FormsFormsetTestCase(TestCase):
         # 'on'. Let's go ahead and delete Fergie.
 
         data = {
-            'choices-TOTAL_FORMS': '3', # the number of forms rendered
-            'choices-INITIAL_FORMS': '2', # the number of forms with initial data
-            'choices-MIN_NUM_FORMS': '0', # min number of forms
-            'choices-MAX_NUM_FORMS': '0', # max number of forms
+            'choices-TOTAL_FORMS': '3',  # the number of forms rendered
+            'choices-INITIAL_FORMS': '2',  # the number of forms with initial data
+            'choices-MIN_NUM_FORMS': '0',  # min number of forms
+            'choices-MAX_NUM_FORMS': '0',  # max number of forms
             'choices-0-choice': 'Calexico',
             'choices-0-votes': '100',
             'choices-0-DELETE': '',
@@ -416,10 +416,10 @@ class FormsFormsetTestCase(TestCase):
             field = IntegerField(min_value=100)
 
         data = {
-            'check-TOTAL_FORMS': '3', # the number of forms rendered
-            'check-INITIAL_FORMS': '2', # the number of forms with initial data
-            'choices-MIN_NUM_FORMS': '0', # min number of forms
-            'check-MAX_NUM_FORMS': '0', # max number of forms
+            'check-TOTAL_FORMS': '3',  # the number of forms rendered
+            'check-INITIAL_FORMS': '2',  # the number of forms with initial data
+            'choices-MIN_NUM_FORMS': '0',  # min number of forms
+            'check-MAX_NUM_FORMS': '0',  # max number of forms
             'check-0-field': '200',
             'check-0-DELETE': '',
             'check-1-field': '50',
@@ -447,7 +447,7 @@ class FormsFormsetTestCase(TestCase):
             can_delete=True)
 
         p = PeopleForm(
-            {'form-0-name': '', 'form-0-DELETE': 'on', # no name!
+            {'form-0-name': '', 'form-0-DELETE': 'on',  # no name!
              'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1,
              'form-MIN_NUM_FORMS': 0, 'form-MAX_NUM_FORMS': 1})
 
@@ -484,10 +484,10 @@ class FormsFormsetTestCase(TestCase):
 <li>Order: <input type="number" name="choices-2-ORDER" /></li>""")
 
         data = {
-            'choices-TOTAL_FORMS': '3', # the number of forms rendered
-            'choices-INITIAL_FORMS': '2', # the number of forms with initial data
-            'choices-MIN_NUM_FORMS': '0', # min number of forms
-            'choices-MAX_NUM_FORMS': '0', # max number of forms
+            'choices-TOTAL_FORMS': '3',  # the number of forms rendered
+            'choices-INITIAL_FORMS': '2',  # the number of forms with initial data
+            'choices-MIN_NUM_FORMS': '0',  # min number of forms
+            'choices-MAX_NUM_FORMS': '0',  # max number of forms
             'choices-0-choice': 'Calexico',
             'choices-0-votes': '100',
             'choices-0-ORDER': '1',
@@ -517,10 +517,10 @@ class FormsFormsetTestCase(TestCase):
         # they will be sorted below everything else.
 
         data = {
-            'choices-TOTAL_FORMS': '4', # the number of forms rendered
-            'choices-INITIAL_FORMS': '3', # the number of forms with initial data
-            'choices-MIN_NUM_FORMS': '0', # min number of forms
-            'choices-MAX_NUM_FORMS': '0', # max number of forms
+            'choices-TOTAL_FORMS': '4',  # the number of forms rendered
+            'choices-INITIAL_FORMS': '3',  # the number of forms with initial data
+            'choices-MIN_NUM_FORMS': '0',  # min number of forms
+            'choices-MAX_NUM_FORMS': '0',  # max number of forms
             'choices-0-choice': 'Calexico',
             'choices-0-votes': '100',
             'choices-0-ORDER': '1',
@@ -554,10 +554,10 @@ class FormsFormsetTestCase(TestCase):
         # Ordering should work with blank fieldsets.
 
         data = {
-            'choices-TOTAL_FORMS': '3', # the number of forms rendered
-            'choices-INITIAL_FORMS': '0', # the number of forms with initial data
-            'choices-MIN_NUM_FORMS': '0', # min number of forms
-            'choices-MAX_NUM_FORMS': '0', # max number of forms
+            'choices-TOTAL_FORMS': '3',  # the number of forms rendered
+            'choices-INITIAL_FORMS': '0',  # the number of forms with initial data
+            'choices-MIN_NUM_FORMS': '0',  # min number of forms
+            'choices-MAX_NUM_FORMS': '0',  # max number of forms
         }
 
         ChoiceFormSet = formset_factory(Choice, can_order=True)
@@ -607,10 +607,10 @@ class FormsFormsetTestCase(TestCase):
         # Let's delete Fergie, and put The Decemberists ahead of Calexico.
 
         data = {
-            'choices-TOTAL_FORMS': '4', # the number of forms rendered
-            'choices-INITIAL_FORMS': '3', # the number of forms with initial data
-            'choices-MIN_NUM_FORMS': '0', # min number of forms
-            'choices-MAX_NUM_FORMS': '0', # max number of forms
+            'choices-TOTAL_FORMS': '4',  # the number of forms rendered
+            'choices-INITIAL_FORMS': '3',  # the number of forms with initial data
+            'choices-MIN_NUM_FORMS': '0',  # min number of forms
+            'choices-MAX_NUM_FORMS': '0',  # max number of forms
             'choices-0-choice': 'Calexico',
             'choices-0-votes': '100',
             'choices-0-ORDER': '1',
@@ -653,7 +653,7 @@ class FormsFormsetTestCase(TestCase):
 
         p = PeopleForm({
             'form-0-name': '',
-            'form-0-DELETE': 'on', # no name!
+            'form-0-DELETE': 'on',  # no name!
             'form-TOTAL_FORMS': 1,
             'form-INITIAL_FORMS': 1,
             'form-MIN_NUM_FORMS': 0,
@@ -671,10 +671,10 @@ class FormsFormsetTestCase(TestCase):
         # We start out with a some duplicate data.
 
         data = {
-            'drinks-TOTAL_FORMS': '2', # the number of forms rendered
-            'drinks-INITIAL_FORMS': '0', # the number of forms with initial data
-            'drinks-MIN_NUM_FORMS': '0', # min number of forms
-            'drinks-MAX_NUM_FORMS': '0', # max number of forms
+            'drinks-TOTAL_FORMS': '2',  # the number of forms rendered
+            'drinks-INITIAL_FORMS': '0',  # the number of forms with initial data
+            'drinks-MIN_NUM_FORMS': '0',  # min number of forms
+            'drinks-MAX_NUM_FORMS': '0',  # max number of forms
             'drinks-0-name': 'Gin and Tonic',
             'drinks-1-name': 'Gin and Tonic',
         }
@@ -691,10 +691,10 @@ class FormsFormsetTestCase(TestCase):
         # Make sure we didn't break the valid case.
 
         data = {
-            'drinks-TOTAL_FORMS': '2', # the number of forms rendered
-            'drinks-INITIAL_FORMS': '0', # the number of forms with initial data
-            'drinks-MIN_NUM_FORMS': '0', # min number of forms
-            'drinks-MAX_NUM_FORMS': '0', # max number of forms
+            'drinks-TOTAL_FORMS': '2',  # the number of forms rendered
+            'drinks-INITIAL_FORMS': '0',  # the number of forms with initial data
+            'drinks-MIN_NUM_FORMS': '0',  # min number of forms
+            'drinks-MAX_NUM_FORMS': '0',  # max number of forms
             'drinks-0-name': 'Gin and Tonic',
             'drinks-1-name': 'Bloody Mary',
         }
@@ -859,10 +859,10 @@ class FormsFormsetTestCase(TestCase):
         # Regression test for #12878 #################################################
 
         data = {
-            'drinks-TOTAL_FORMS': '2', # the number of forms rendered
-            'drinks-INITIAL_FORMS': '0', # the number of forms with initial data
-            'drinks-MIN_NUM_FORMS': '0', # min number of forms
-            'drinks-MAX_NUM_FORMS': '0', # max number of forms
+            'drinks-TOTAL_FORMS': '2',  # the number of forms rendered
+            'drinks-INITIAL_FORMS': '0',  # the number of forms with initial data
+            'drinks-MIN_NUM_FORMS': '0',  # min number of forms
+            'drinks-MAX_NUM_FORMS': '0',  # max number of forms
             'drinks-0-name': 'Gin and Tonic',
             'drinks-1-name': 'Gin and Tonic',
         }
@@ -951,7 +951,7 @@ class FormsFormsetTestCase(TestCase):
         data = {
             'choices-TOTAL_FORMS': '1',  # number of forms rendered
             'choices-INITIAL_FORMS': '0',  # number of forms with initial data
-            'choices-MIN_NUM_FORMS': '0', # min number of forms
+            'choices-MIN_NUM_FORMS': '0',  # min number of forms
             'choices-MAX_NUM_FORMS': '0',  # max number of forms
             'choices-0-choice': 'Calexico',
             'choices-0-votes': '100',
@@ -972,7 +972,7 @@ class FormsFormsetTestCase(TestCase):
                 {
                     'choices-TOTAL_FORMS': '4',
                     'choices-INITIAL_FORMS': '0',
-                    'choices-MIN_NUM_FORMS': '0', # min number of forms
+                    'choices-MIN_NUM_FORMS': '0',  # min number of forms
                     'choices-MAX_NUM_FORMS': '4',
                     'choices-0-choice': 'Zero',
                     'choices-0-votes': '0',
@@ -1004,7 +1004,7 @@ class FormsFormsetTestCase(TestCase):
                 {
                     'choices-TOTAL_FORMS': '4',
                     'choices-INITIAL_FORMS': '0',
-                    'choices-MIN_NUM_FORMS': '0', # min number of forms
+                    'choices-MIN_NUM_FORMS': '0',  # min number of forms
                     'choices-MAX_NUM_FORMS': '4',
                     'choices-0-choice': 'Zero',
                     'choices-0-votes': '0',
@@ -1070,9 +1070,9 @@ class FormsFormsetTestCase(TestCase):
 
     def test_formset_total_error_count_with_non_form_errors(self):
         data = {
-            'choices-TOTAL_FORMS': '2', # the number of forms rendered
-            'choices-INITIAL_FORMS': '0', # the number of forms with initial data
-            'choices-MAX_NUM_FORMS': '2', # max number of forms - should be ignored
+            'choices-TOTAL_FORMS': '2',  # the number of forms rendered
+            'choices-INITIAL_FORMS': '0',  # the number of forms with initial data
+            'choices-MAX_NUM_FORMS': '2',  # max number of forms - should be ignored
             'choices-0-choice': 'Zero',
             'choices-0-votes': '0',
             'choices-1-choice': 'One',
@@ -1089,10 +1089,10 @@ class FormsFormsetTestCase(TestCase):
 
 
 data = {
-    'choices-TOTAL_FORMS': '1', # the number of forms rendered
-    'choices-INITIAL_FORMS': '0', # the number of forms with initial data
-    'choices-MIN_NUM_FORMS': '0', # min number of forms
-    'choices-MAX_NUM_FORMS': '0', # max number of forms
+    'choices-TOTAL_FORMS': '1',  # the number of forms rendered
+    'choices-INITIAL_FORMS': '0',  # the number of forms with initial data
+    'choices-MIN_NUM_FORMS': '0',  # min number of forms
+    'choices-MAX_NUM_FORMS': '0',  # max number of forms
     'choices-0-choice': 'Calexico',
     'choices-0-votes': '100',
 }
@@ -1156,7 +1156,7 @@ class TestIsBoundBehavior(TestCase):
             'form-0-title': 'Test',
             'form-0-pub_date': '1904-06-16',
             'form-1-title': 'Test',
-            'form-1-pub_date': '', # <-- this date is missing but required
+            'form-1-pub_date': '',  # <-- this date is missing but required
         }
         formset = ArticleFormSet(data)
         self.assertFalse(formset.is_valid())
diff --git a/tests/forms_tests/tests/test_input_formats.py b/tests/forms_tests/tests/test_input_formats.py
index 95308d4eeb..25b491a499 100644
--- a/tests/forms_tests/tests/test_input_formats.py
+++ b/tests/forms_tests/tests/test_input_formats.py
@@ -191,7 +191,7 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
         result = f.clean('13.30.05')
         self.assertEqual(result, time(13, 30, 5))
 
-        # # Check that the parsed result does a round trip to the same format
+        # Check that the parsed result does a round trip to the same format
         text = f.widget._format_value(result)
         self.assertEqual(text, "01:30:05 PM")
 
@@ -385,7 +385,7 @@ class LocalizedDateTests(SimpleTestCase):
         result = f.clean('12.21.2010')
         self.assertEqual(result, date(2010, 12, 21))
 
-        # # Check that the parsed result does a round trip to the same format
+        # Check that the parsed result does a round trip to the same format
         text = f.widget._format_value(result)
         self.assertEqual(text, "21.12.2010")
 
@@ -478,7 +478,7 @@ class CustomDateInputFormatsTests(SimpleTestCase):
         result = f.clean('12.21.2010')
         self.assertEqual(result, date(2010, 12, 21))
 
-        # # Check that the parsed result does a round trip to the same format
+        # Check that the parsed result does a round trip to the same format
         text = f.widget._format_value(result)
         self.assertEqual(text, "21.12.2010")
 
@@ -671,7 +671,7 @@ class LocalizedDateTimeTests(SimpleTestCase):
         result = f.clean('13.30.05 12.21.2010')
         self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5))
 
-        # # Check that the parsed result does a round trip to the same format
+        # Check that the parsed result does a round trip to the same format
         text = f.widget._format_value(result)
         self.assertEqual(text, "21.12.2010 13:30:05")
 
@@ -764,7 +764,7 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
         result = f.clean('12.21.2010 13:30:05')
         self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5))
 
-        # # Check that the parsed result does a round trip to the same format
+        # Check that the parsed result does a round trip to the same format
         text = f.widget._format_value(result)
         self.assertEqual(text, "01:30:05 PM 21/12/2010")
 
diff --git a/tests/generic_inline_admin/tests.py b/tests/generic_inline_admin/tests.py
index 1cf2f492a4..23f17f7b22 100644
--- a/tests/generic_inline_admin/tests.py
+++ b/tests/generic_inline_admin/tests.py
@@ -72,7 +72,7 @@ class GenericAdminViewTest(TestCase):
             "generic_inline_admin-media-content_type-object_id-MAX_NUM_FORMS": "0",
         }
         response = self.client.post('/generic_inline_admin/admin/generic_inline_admin/episode/add/', post_data)
-        self.assertEqual(response.status_code, 302) # redirect somewhere
+        self.assertEqual(response.status_code, 302)  # redirect somewhere
 
     def testBasicEditPost(self):
         """
@@ -93,7 +93,7 @@ class GenericAdminViewTest(TestCase):
         }
         url = '/generic_inline_admin/admin/generic_inline_admin/episode/%d/' % self.episode_pk
         response = self.client.post(url, post_data)
-        self.assertEqual(response.status_code, 302) # redirect somewhere
+        self.assertEqual(response.status_code, 302)  # redirect somewhere
 
     def testGenericInlineFormset(self):
         EpisodeMediaFormSet = generic_inlineformset_factory(Media, can_delete=False, exclude=['description', 'keywords'], extra=3)
@@ -208,7 +208,7 @@ class GenericInlineAdminWithUniqueTogetherTest(TestCase):
         response = self.client.get('/generic_inline_admin/admin/generic_inline_admin/contact/add/')
         self.assertEqual(response.status_code, 200)
         response = self.client.post('/generic_inline_admin/admin/generic_inline_admin/contact/add/', post_data)
-        self.assertEqual(response.status_code, 302) # redirect somewhere
+        self.assertEqual(response.status_code, 302)  # redirect somewhere
 
 class NoInlineDeletionTest(TestCase):
     urls = "generic_inline_admin.urls"
diff --git a/tests/httpwrappers/tests.py b/tests/httpwrappers/tests.py
index 1e099d2bb4..820aecf1f7 100644
--- a/tests/httpwrappers/tests.py
+++ b/tests/httpwrappers/tests.py
@@ -315,11 +315,11 @@ class HttpResponseTests(unittest.TestCase):
         self.assertEqual(r.get('test'), None)
 
     def test_non_string_content(self):
-        #Bug 16494: HttpResponse should behave consistently with non-strings
+        # Bug 16494: HttpResponse should behave consistently with non-strings
         r = HttpResponse(12345)
         self.assertEqual(r.content, b'12345')
 
-        #test content via property
+        # test content via property
         r = HttpResponse()
         r.content = 12345
         self.assertEqual(r.content, b'12345')
@@ -328,7 +328,7 @@ class HttpResponseTests(unittest.TestCase):
         r = HttpResponse(['abc', 'def', 'ghi'])
         self.assertEqual(r.content, b'abcdefghi')
 
-        #test iter content via property
+        # test iter content via property
         r = HttpResponse()
         r.content = ['idan', 'alex', 'jacob']
         self.assertEqual(r.content, b'idanalexjacob')
@@ -337,13 +337,13 @@ class HttpResponseTests(unittest.TestCase):
         r.content = [1, 2, 3]
         self.assertEqual(r.content, b'123')
 
-        #test odd inputs
+        # test odd inputs
         r = HttpResponse()
         r.content = ['1', '2', 3, '\u079e']
         #'\xde\x9e' == unichr(1950).encode('utf-8')
         self.assertEqual(r.content, b'123\xde\x9e')
 
-        #with Content-Encoding header
+        # with Content-Encoding header
         r = HttpResponse()
         r['Content-Encoding'] = 'winning'
         r.content = [b'abc', b'def']
@@ -573,8 +573,8 @@ class CookieTests(unittest.TestCase):
         """
         c = SimpleCookie()
         c['test'] = "An,awkward;value"
-        self.assertTrue(";" not in c.output().rstrip(';')) # IE compat
-        self.assertTrue("," not in c.output().rstrip(';')) # Safari compat
+        self.assertTrue(";" not in c.output().rstrip(';'))  # IE compat
+        self.assertTrue("," not in c.output().rstrip(';'))  # Safari compat
 
     def test_decode(self):
         """
diff --git a/tests/i18n/test_extraction.py b/tests/i18n/test_extraction.py
index 04bc0a8632..18088e5e16 100644
--- a/tests/i18n/test_extraction.py
+++ b/tests/i18n/test_extraction.py
@@ -423,7 +423,7 @@ class LocationCommentsTests(ExtractorTests):
 
             # #21208 -- Leaky paths in comments on Windows e.g. #: path\to\file.html.py:123
             bad_suffix = '.py'
-            bad_string = 'templates%stest.html%s' % (os.sep, bad_suffix) #
+            bad_string = 'templates%stest.html%s' % (os.sep, bad_suffix)
             self.assertFalse(bad_string in po_contents, '"%s" shouldn\'t be in final .po file.' % bad_string)
 
 
diff --git a/tests/i18n/tests.py b/tests/i18n/tests.py
index e8b3ac7b7d..b1f3de0ef9 100644
--- a/tests/i18n/tests.py
+++ b/tests/i18n/tests.py
@@ -735,7 +735,7 @@ class FormattingTests(TransRealMixin, TestCase):
         with self.settings(FORMAT_MODULE_PATH='i18n.other.locale'):
             with translation.override('de', deactivate=True):
                 old = str("%r") % get_format_modules(reverse=True)
-                new = str("%r") % get_format_modules(reverse=True) # second try
+                new = str("%r") % get_format_modules(reverse=True)  # second try
                 self.assertEqual(new, old, 'Value returned by get_formats_modules() must be preserved between calls.')
 
     def test_localize_templatetag_and_filter(self):
diff --git a/tests/invalid_models/invalid_models/models.py b/tests/invalid_models/invalid_models/models.py
index 8e04a4d328..0c991dcf13 100644
--- a/tests/invalid_models/invalid_models/models.py
+++ b/tests/invalid_models/invalid_models/models.py
@@ -1,4 +1,4 @@
-#encoding=utf-8
+# encoding=utf-8
 """
 26. Invalid models
 
diff --git a/tests/m2m_and_m2o/tests.py b/tests/m2m_and_m2o/tests.py
index ee5d77919f..35443e32e4 100644
--- a/tests/m2m_and_m2o/tests.py
+++ b/tests/m2m_and_m2o/tests.py
@@ -82,6 +82,6 @@ class RelatedObjectUnicodeTests(TestCase):
         """
         m1 = UnicodeReferenceModel.objects.create()
         m2 = UnicodeReferenceModel.objects.create()
-        m2.others.add(m1) # used to cause an error (see ticket #6045)
+        m2.others.add(m1)  # used to cause an error (see ticket #6045)
         m2.save()
-        list(m2.others.all()) # Force retrieval.
+        list(m2.others.all())  # Force retrieval.
diff --git a/tests/max_lengths/tests.py b/tests/max_lengths/tests.py
index feb3351cf7..5dd33fc80f 100644
--- a/tests/max_lengths/tests.py
+++ b/tests/max_lengths/tests.py
@@ -34,6 +34,6 @@ class MaxLengthORMTests(unittest.TestCase):
 
         for field in ("email", "vcard", "homepage", "avatar"):
             new_args = args.copy()
-            new_args[field] = "X" * 250 # a value longer than any of the default fields could hold.
+            new_args[field] = "X" * 250  # a value longer than any of the default fields could hold.
             p = PersonWithCustomMaxLengths.objects.create(**new_args)
             self.assertEqual(getattr(p, field), ("X" * 250))
diff --git a/tests/model_forms/tests.py b/tests/model_forms/tests.py
index 2da852d11e..ddc7a4ceef 100644
--- a/tests/model_forms/tests.py
+++ b/tests/model_forms/tests.py
@@ -318,7 +318,7 @@ class ModelFormBaseTest(TestCase):
 
             class Meta:
                 model = Category
-                fields = [] # url will still appear, since it is explicit above
+                fields = []  # url will still appear, since it is explicit above
 
         self.assertIsInstance(ReplaceField.base_fields['url'],
                                      forms.fields.BooleanField)
@@ -348,7 +348,7 @@ class ModelFormBaseTest(TestCase):
             class CategoryForm(forms.ModelForm):
                 class Meta:
                     model = Category
-                    fields = ('url') # note the missing comma
+                    fields = ('url')  # note the missing comma
 
     def test_exclude_fields(self):
         class ExcludeFields(forms.ModelForm):
@@ -374,7 +374,7 @@ class ModelFormBaseTest(TestCase):
             class CategoryForm(forms.ModelForm):
                 class Meta:
                     model = Category
-                    exclude = ('url') # note the missing comma
+                    exclude = ('url')  # note the missing comma
 
     def test_confused_form(self):
         class ConfusedForm(forms.ModelForm):
@@ -415,7 +415,7 @@ class ModelFormBaseTest(TestCase):
         )
 
     def test_bad_form(self):
-        #First class with a Meta class wins...
+        # First class with a Meta class wins...
         class BadForm(ArticleForm, BaseCategoryForm):
             pass
 
@@ -818,10 +818,10 @@ class ModelToDictTests(TestCase):
         with self.assertNumQueries(1):
             d = model_to_dict(art)
 
-        #Ensure all many-to-many categories appear in model_to_dict
+        # Ensure all many-to-many categories appear in model_to_dict
         for c in categories:
             self.assertIn(c.pk, d['categories'])
-        #Ensure many-to-many relation appears as a list
+        # Ensure many-to-many relation appears as a list
         self.assertIsInstance(d['categories'], list)
 
 class OldFormForXTests(TestCase):
diff --git a/tests/model_formsets/tests.py b/tests/model_formsets/tests.py
index 4c57e0f549..ac9d68132e 100644
--- a/tests/model_formsets/tests.py
+++ b/tests/model_formsets/tests.py
@@ -54,8 +54,8 @@ class DeletionTests(TestCase):
             'form-0-id': six.text_type(poet.id),
             'form-0-name': 'test',
             'form-1-id': '',
-            'form-1-name': 'x' * 1000, # Too long
-            'form-1-id': six.text_type(poet.id), # Violate unique constraint
+            'form-1-name': 'x' * 1000,  # Too long
+            'form-1-id': six.text_type(poet.id),  # Violate unique constraint
             'form-1-name': 'test2',
         }
         formset = PoetFormSet(data, queryset=Poet.objects.all())
@@ -145,9 +145,9 @@ class ModelFormsetTest(TestCase):
             '<p><label for="id_form-2-name">Name:</label> <input id="id_form-2-name" type="text" name="form-2-name" maxlength="100" /><input type="hidden" name="form-2-id" id="id_form-2-id" /></p>')
 
         data = {
-            'form-TOTAL_FORMS': '3', # the number of forms rendered
-            'form-INITIAL_FORMS': '0', # the number of forms with initial data
-            'form-MAX_NUM_FORMS': '', # the max number of forms
+            'form-TOTAL_FORMS': '3',  # the number of forms rendered
+            'form-INITIAL_FORMS': '0',  # the number of forms with initial data
+            'form-MAX_NUM_FORMS': '',  # the max number of forms
             'form-0-name': 'Charles Baudelaire',
             'form-1-name': 'Arthur Rimbaud',
             'form-2-name': '',
@@ -183,9 +183,9 @@ class ModelFormsetTest(TestCase):
             '<p><label for="id_form-2-name">Name:</label> <input id="id_form-2-name" type="text" name="form-2-name" maxlength="100" /><input type="hidden" name="form-2-id" id="id_form-2-id" /></p>')
 
         data = {
-            'form-TOTAL_FORMS': '3', # the number of forms rendered
-            'form-INITIAL_FORMS': '2', # the number of forms with initial data
-            'form-MAX_NUM_FORMS': '', # the max number of forms
+            'form-TOTAL_FORMS': '3',  # the number of forms rendered
+            'form-INITIAL_FORMS': '2',  # the number of forms with initial data
+            'form-MAX_NUM_FORMS': '',  # the max number of forms
             'form-0-id': str(author2.id),
             'form-0-name': 'Arthur Rimbaud',
             'form-1-id': str(author1.id),
@@ -227,9 +227,9 @@ class ModelFormsetTest(TestCase):
             '<p><label for="id_form-3-DELETE">Delete:</label> <input type="checkbox" name="form-3-DELETE" id="id_form-3-DELETE" /><input type="hidden" name="form-3-id" id="id_form-3-id" /></p>')
 
         data = {
-            'form-TOTAL_FORMS': '4', # the number of forms rendered
-            'form-INITIAL_FORMS': '3', # the number of forms with initial data
-            'form-MAX_NUM_FORMS': '', # the max number of forms
+            'form-TOTAL_FORMS': '4',  # the number of forms rendered
+            'form-INITIAL_FORMS': '3',  # the number of forms with initial data
+            'form-MAX_NUM_FORMS': '',  # the max number of forms
             'form-0-id': str(author2.id),
             'form-0-name': 'Arthur Rimbaud',
             'form-1-id': str(author1.id),
@@ -253,9 +253,9 @@ class ModelFormsetTest(TestCase):
         # Let's edit a record to ensure save only returns that one record.
 
         data = {
-            'form-TOTAL_FORMS': '4', # the number of forms rendered
-            'form-INITIAL_FORMS': '3', # the number of forms with initial data
-            'form-MAX_NUM_FORMS': '', # the max number of forms
+            'form-TOTAL_FORMS': '4',  # the number of forms rendered
+            'form-INITIAL_FORMS': '3',  # the number of forms with initial data
+            'form-MAX_NUM_FORMS': '',  # the max number of forms
             'form-0-id': str(author2.id),
             'form-0-name': 'Walt Whitman',
             'form-1-id': str(author1.id),
@@ -291,9 +291,9 @@ class ModelFormsetTest(TestCase):
 
         AuthorMeetingFormSet = modelformset_factory(AuthorMeeting, fields="__all__", extra=1, can_delete=True)
         data = {
-            'form-TOTAL_FORMS': '2', # the number of forms rendered
-            'form-INITIAL_FORMS': '1', # the number of forms with initial data
-            'form-MAX_NUM_FORMS': '', # the max number of forms
+            'form-TOTAL_FORMS': '2',  # the number of forms rendered
+            'form-INITIAL_FORMS': '1',  # the number of forms with initial data
+            'form-MAX_NUM_FORMS': '',  # the max number of forms
             'form-0-id': str(meeting.id),
             'form-0-name': '2nd Tuesday of the Week Meeting',
             'form-0-authors': [author2.id, author1.id, author3.id, author4.id],
@@ -379,9 +379,9 @@ class ModelFormsetTest(TestCase):
         PoetFormSet = modelformset_factory(Poet, fields="__all__", form=PoetForm)
 
         data = {
-            'form-TOTAL_FORMS': '3', # the number of forms rendered
-            'form-INITIAL_FORMS': '0', # the number of forms with initial data
-            'form-MAX_NUM_FORMS': '', # the max number of forms
+            'form-TOTAL_FORMS': '3',  # the number of forms rendered
+            'form-INITIAL_FORMS': '0',  # the number of forms with initial data
+            'form-MAX_NUM_FORMS': '',  # the max number of forms
             'form-0-name': 'Walt Whitman',
             'form-1-name': 'Charles Baudelaire',
             'form-2-name': '',
@@ -445,9 +445,9 @@ class ModelFormsetTest(TestCase):
             '<p><label for="id_form-0-write_speed">Write speed:</label> <input type="number" name="form-0-write_speed" id="id_form-0-write_speed" /><input type="hidden" name="form-0-author_ptr" id="id_form-0-author_ptr" /></p>')
 
         data = {
-            'form-TOTAL_FORMS': '1', # the number of forms rendered
-            'form-INITIAL_FORMS': '0', # the number of forms with initial data
-            'form-MAX_NUM_FORMS': '', # the max number of forms
+            'form-TOTAL_FORMS': '1',  # the number of forms rendered
+            'form-INITIAL_FORMS': '0',  # the number of forms with initial data
+            'form-MAX_NUM_FORMS': '',  # the max number of forms
             'form-0-author_ptr': '',
             'form-0-name': 'Ernest Hemingway',
             'form-0-write_speed': '10',
@@ -471,9 +471,9 @@ class ModelFormsetTest(TestCase):
             '<p><label for="id_form-1-write_speed">Write speed:</label> <input type="number" name="form-1-write_speed" id="id_form-1-write_speed" /><input type="hidden" name="form-1-author_ptr" id="id_form-1-author_ptr" /></p>')
 
         data = {
-            'form-TOTAL_FORMS': '2', # the number of forms rendered
-            'form-INITIAL_FORMS': '1', # the number of forms with initial data
-            'form-MAX_NUM_FORMS': '', # the max number of forms
+            'form-TOTAL_FORMS': '2',  # the number of forms rendered
+            'form-INITIAL_FORMS': '1',  # the number of forms with initial data
+            'form-MAX_NUM_FORMS': '',  # the max number of forms
             'form-0-author_ptr': hemingway_id,
             'form-0-name': 'Ernest Hemingway',
             'form-0-write_speed': '10',
@@ -503,9 +503,9 @@ class ModelFormsetTest(TestCase):
             '<p><label for="id_book_set-2-title">Title:</label> <input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100" /><input type="hidden" name="book_set-2-author" value="%d" id="id_book_set-2-author" /><input type="hidden" name="book_set-2-id" id="id_book_set-2-id" /></p>' % author.id)
 
         data = {
-            'book_set-TOTAL_FORMS': '3', # the number of forms rendered
-            'book_set-INITIAL_FORMS': '0', # the number of forms with initial data
-            'book_set-MAX_NUM_FORMS': '', # the max number of forms
+            'book_set-TOTAL_FORMS': '3',  # the number of forms rendered
+            'book_set-INITIAL_FORMS': '0',  # the number of forms with initial data
+            'book_set-MAX_NUM_FORMS': '',  # the max number of forms
             'book_set-0-title': 'Les Fleurs du Mal',
             'book_set-1-title': '',
             'book_set-2-title': '',
@@ -537,9 +537,9 @@ class ModelFormsetTest(TestCase):
             '<p><label for="id_book_set-2-title">Title:</label> <input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100" /><input type="hidden" name="book_set-2-author" value="%d" id="id_book_set-2-author" /><input type="hidden" name="book_set-2-id" id="id_book_set-2-id" /></p>' % author.id)
 
         data = {
-            'book_set-TOTAL_FORMS': '3', # the number of forms rendered
-            'book_set-INITIAL_FORMS': '1', # the number of forms with initial data
-            'book_set-MAX_NUM_FORMS': '', # the max number of forms
+            'book_set-TOTAL_FORMS': '3',  # the number of forms rendered
+            'book_set-INITIAL_FORMS': '1',  # the number of forms with initial data
+            'book_set-MAX_NUM_FORMS': '',  # the max number of forms
             'book_set-0-id': str(book1.id),
             'book_set-0-title': 'Les Fleurs du Mal',
             'book_set-1-title': 'Les Paradis Artificiels',
@@ -568,9 +568,9 @@ class ModelFormsetTest(TestCase):
         Author.objects.create(name='Charles Baudelaire')
 
         data = {
-            'book_set-TOTAL_FORMS': '3', # the number of forms rendered
-            'book_set-INITIAL_FORMS': '2', # the number of forms with initial data
-            'book_set-MAX_NUM_FORMS': '', # the max number of forms
+            'book_set-TOTAL_FORMS': '3',  # the number of forms rendered
+            'book_set-INITIAL_FORMS': '2',  # the number of forms with initial data
+            'book_set-MAX_NUM_FORMS': '',  # the max number of forms
             'book_set-0-id': '1',
             'book_set-0-title': 'Les Fleurs du Mal',
             'book_set-1-id': '2',
@@ -613,9 +613,9 @@ class ModelFormsetTest(TestCase):
             '<p><label for="id_bookwithcustompk_set-0-title">Title:</label> <input id="id_bookwithcustompk_set-0-title" type="text" name="bookwithcustompk_set-0-title" maxlength="100" /><input type="hidden" name="bookwithcustompk_set-0-author" value="1" id="id_bookwithcustompk_set-0-author" /></p>')
 
         data = {
-            'bookwithcustompk_set-TOTAL_FORMS': '1', # the number of forms rendered
-            'bookwithcustompk_set-INITIAL_FORMS': '0', # the number of forms with initial data
-            'bookwithcustompk_set-MAX_NUM_FORMS': '', # the max number of forms
+            'bookwithcustompk_set-TOTAL_FORMS': '1',  # the number of forms rendered
+            'bookwithcustompk_set-INITIAL_FORMS': '0',  # the number of forms with initial data
+            'bookwithcustompk_set-MAX_NUM_FORMS': '',  # the max number of forms
             'bookwithcustompk_set-0-my_pk': '77777',
             'bookwithcustompk_set-0-title': 'Les Fleurs du Mal',
         }
@@ -645,9 +645,9 @@ class ModelFormsetTest(TestCase):
             '<p><label for="id_alternatebook_set-0-notes">Notes:</label> <input id="id_alternatebook_set-0-notes" type="text" name="alternatebook_set-0-notes" maxlength="100" /><input type="hidden" name="alternatebook_set-0-author" value="1" id="id_alternatebook_set-0-author" /><input type="hidden" name="alternatebook_set-0-book_ptr" id="id_alternatebook_set-0-book_ptr" /></p>')
 
         data = {
-            'alternatebook_set-TOTAL_FORMS': '1', # the number of forms rendered
-            'alternatebook_set-INITIAL_FORMS': '0', # the number of forms with initial data
-            'alternatebook_set-MAX_NUM_FORMS': '', # the max number of forms
+            'alternatebook_set-TOTAL_FORMS': '1',  # the number of forms rendered
+            'alternatebook_set-INITIAL_FORMS': '0',  # the number of forms with initial data
+            'alternatebook_set-MAX_NUM_FORMS': '',  # the max number of forms
             'alternatebook_set-0-title': 'Flowers of Evil',
             'alternatebook_set-0-notes': 'English translation of Les Fleurs du Mal'
         }
@@ -670,9 +670,9 @@ class ModelFormsetTest(TestCase):
         author = Author.objects.create(pk=1, name='Charles Baudelaire')
 
         data = {
-            'bookwithoptionalalteditor_set-TOTAL_FORMS': '2', # the number of forms rendered
-            'bookwithoptionalalteditor_set-INITIAL_FORMS': '0', # the number of forms with initial data
-            'bookwithoptionalalteditor_set-MAX_NUM_FORMS': '', # the max number of forms
+            'bookwithoptionalalteditor_set-TOTAL_FORMS': '2',  # the number of forms rendered
+            'bookwithoptionalalteditor_set-INITIAL_FORMS': '0',  # the number of forms with initial data
+            'bookwithoptionalalteditor_set-MAX_NUM_FORMS': '',  # the max number of forms
             'bookwithoptionalalteditor_set-0-author': '1',
             'bookwithoptionalalteditor_set-0-title': 'Les Fleurs du Mal',
             'bookwithoptionalalteditor_set-1-author': '1',
@@ -708,9 +708,9 @@ class ModelFormsetTest(TestCase):
         PoemFormSet = inlineformset_factory(Poet, Poem, form=PoemForm, fields="__all__")
 
         data = {
-            'poem_set-TOTAL_FORMS': '3', # the number of forms rendered
-            'poem_set-INITIAL_FORMS': '0', # the number of forms with initial data
-            'poem_set-MAX_NUM_FORMS': '', # the max number of forms
+            'poem_set-TOTAL_FORMS': '3',  # the number of forms rendered
+            'poem_set-INITIAL_FORMS': '0',  # the number of forms with initial data
+            'poem_set-MAX_NUM_FORMS': '',  # the max number of forms
             'poem_set-0-name': 'The Cloud in Trousers',
             'poem_set-1-name': 'I',
             'poem_set-2-name': '',
@@ -743,9 +743,9 @@ class ModelFormsetTest(TestCase):
             '<p><label for="id_book_set-4-title">Title:</label> <input id="id_book_set-4-title" type="text" name="book_set-4-title" maxlength="100" /><input type="hidden" name="book_set-4-author" value="1" id="id_book_set-4-author" /><input type="hidden" name="book_set-4-id" id="id_book_set-4-id" /></p>')
 
         data = {
-            'book_set-TOTAL_FORMS': '5', # the number of forms rendered
-            'book_set-INITIAL_FORMS': '3', # the number of forms with initial data
-            'book_set-MAX_NUM_FORMS': '', # the max number of forms
+            'book_set-TOTAL_FORMS': '5',  # the number of forms rendered
+            'book_set-INITIAL_FORMS': '3',  # the number of forms with initial data
+            'book_set-MAX_NUM_FORMS': '',  # the max number of forms
             'book_set-0-id': str(book1.id),
             'book_set-0-title': 'Les Paradis Artificiels',
             'book_set-1-id': str(book2.id),
@@ -768,9 +768,9 @@ class ModelFormsetTest(TestCase):
             '<p><label for="id_book_set-2-title">Title:</label> <input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100" /><input type="hidden" name="book_set-2-author" value="1" id="id_book_set-2-author" /><input type="hidden" name="book_set-2-id" id="id_book_set-2-id" /></p>')
 
         data = {
-            'book_set-TOTAL_FORMS': '3', # the number of forms rendered
-            'book_set-INITIAL_FORMS': '1', # the number of forms with initial data
-            'book_set-MAX_NUM_FORMS': '', # the max number of forms
+            'book_set-TOTAL_FORMS': '3',  # the number of forms rendered
+            'book_set-INITIAL_FORMS': '1',  # the number of forms with initial data
+            'book_set-MAX_NUM_FORMS': '',  # the max number of forms
             'book_set-0-id': str(book3.id),
             'book_set-0-title': 'Flowers of Evil',
             'book_set-1-title': 'Revue des deux mondes',
@@ -958,7 +958,7 @@ class ModelFormsetTest(TestCase):
         data = {
             'form-TOTAL_FORMS': '2',
             'form-INITIAL_FORMS': '0',
-            'form-MAX_NUM_FORMS': '2', # should be ignored
+            'form-MAX_NUM_FORMS': '2',  # should be ignored
             'form-0-price': '12.00',
             'form-0-quantity': '1',
             'form-1-price': '24.00',
@@ -1064,7 +1064,7 @@ class ModelFormsetTest(TestCase):
         # default. This is required to ensure the value is tested for change correctly
         # when determine what extra forms have changed to save.
 
-        self.assertEqual(len(formset.forms), 1) # this formset only has one form
+        self.assertEqual(len(formset.forms), 1)  # this formset only has one form
         form = formset.forms[0]
         now = form.fields['date_joined'].initial()
         result = form.as_p()
diff --git a/tests/modeladmin/models.py b/tests/modeladmin/models.py
index 4789e35a43..27f54821d6 100644
--- a/tests/modeladmin/models.py
+++ b/tests/modeladmin/models.py
@@ -35,7 +35,7 @@ class ValidationTestModel(models.Model):
     is_active = models.BooleanField(default=False)
     pub_date = models.DateTimeField()
     band = models.ForeignKey(Band)
-    no = models.IntegerField(verbose_name="Number", blank=True, null=True) # This field is intentionally 2 characters long. See #16080.
+    no = models.IntegerField(verbose_name="Number", blank=True, null=True)  # This field is intentionally 2 characters long. See #16080.
 
     def decade_published_in(self):
         return self.pub_date.strftime('%Y')[:3] + "0's"
diff --git a/tests/multiple_database/tests.py b/tests/multiple_database/tests.py
index 046b8fb14b..8596346c7e 100644
--- a/tests/multiple_database/tests.py
+++ b/tests/multiple_database/tests.py
@@ -1791,10 +1791,10 @@ class RouterAttributeErrorTestCase(TestCase):
 
     def test_attribute_error_read(self):
         "Check that the AttributeError from AttributeErrorRouter bubbles up"
-        router.routers = [] # Reset routers so we can save a Book instance
+        router.routers = []  # Reset routers so we can save a Book instance
         b = Book.objects.create(title="Pro Django",
                                 published=datetime.date(2008, 12, 16))
-        router.routers = [AttributeErrorRouter()] # Install our router
+        router.routers = [AttributeErrorRouter()]  # Install our router
         self.assertRaises(AttributeError, Book.objects.get, pk=b.pk)
 
     def test_attribute_error_save(self):
@@ -1806,22 +1806,22 @@ class RouterAttributeErrorTestCase(TestCase):
 
     def test_attribute_error_delete(self):
         "Check that the AttributeError from AttributeErrorRouter bubbles up"
-        router.routers = [] # Reset routers so we can save our Book, Person instances
+        router.routers = []  # Reset routers so we can save our Book, Person instances
         b = Book.objects.create(title="Pro Django",
                                 published=datetime.date(2008, 12, 16))
         p = Person.objects.create(name="Marty Alchin")
         b.authors = [p]
         b.editor = p
-        router.routers = [AttributeErrorRouter()] # Install our router
+        router.routers = [AttributeErrorRouter()]  # Install our router
         self.assertRaises(AttributeError, b.delete)
 
     def test_attribute_error_m2m(self):
         "Check that the AttributeError from AttributeErrorRouter bubbles up"
-        router.routers = [] # Reset routers so we can save our Book, Person instances
+        router.routers = []  # Reset routers so we can save our Book, Person instances
         b = Book.objects.create(title="Pro Django",
                                 published=datetime.date(2008, 12, 16))
         p = Person.objects.create(name="Marty Alchin")
-        router.routers = [AttributeErrorRouter()] # Install our router
+        router.routers = [AttributeErrorRouter()]  # Install our router
         self.assertRaises(AttributeError, setattr, b, 'authors', [p])
 
 class ModelMetaRouter(object):
diff --git a/tests/null_fk/tests.py b/tests/null_fk/tests.py
index 29e1fcb4bb..d5b68658ff 100644
--- a/tests/null_fk/tests.py
+++ b/tests/null_fk/tests.py
@@ -50,7 +50,7 @@ class NullFkTests(TestCase):
         item = Item.objects.create(title='Some Item')
         pv = PropertyValue.objects.create(label='Some Value')
         item.props.create(key='a', value=pv)
-        item.props.create(key='b') # value=NULL
+        item.props.create(key='b')  # value=NULL
         q1 = Q(props__key='a', props__value=pv)
         q2 = Q(props__key='b', props__value__isnull=True)
 
diff --git a/tests/queryset_pickle/tests.py b/tests/queryset_pickle/tests.py
index 7ce4348c1a..077ac6f59c 100644
--- a/tests/queryset_pickle/tests.py
+++ b/tests/queryset_pickle/tests.py
@@ -10,7 +10,7 @@ from .models import Group, Event, Happening, Container, M2MModel
 
 class PickleabilityTestCase(TestCase):
     def setUp(self):
-        Happening.objects.create() # make sure the defaults are working (#20158)
+        Happening.objects.create()  # make sure the defaults are working (#20158)
 
     def assert_pickles(self, qs):
         self.assertEqual(list(pickle.loads(pickle.dumps(qs))), list(qs))
diff --git a/tests/requests/tests.py b/tests/requests/tests.py
index 137b324588..c00f5bb5e0 100644
--- a/tests/requests/tests.py
+++ b/tests/requests/tests.py
@@ -524,7 +524,7 @@ class HostValidationTests(SimpleTestCase):
             '12.34.56.78:443',
             '[2001:19f0:feee::dead:beef:cafe]',
             '[2001:19f0:feee::dead:beef:cafe]:8080',
-            'xn--4ca9at.com', # Punnycode for Ć¶Ć¤Ć¼.com
+            'xn--4ca9at.com',  # Punnycode for Ć¶Ć¤Ć¼.com
             'anything.multitenant.com',
             'multitenant.com',
             'insensitive.com',
@@ -594,7 +594,7 @@ class HostValidationTests(SimpleTestCase):
             '12.34.56.78:443',
             '[2001:19f0:feee::dead:beef:cafe]',
             '[2001:19f0:feee::dead:beef:cafe]:8080',
-            'xn--4ca9at.com', # Punnycode for Ć¶Ć¤Ć¼.com
+            'xn--4ca9at.com',  # Punnycode for Ć¶Ć¤Ć¼.com
         ]
 
         for host in legit_hosts:
@@ -636,11 +636,11 @@ class HostValidationTests(SimpleTestCase):
         msg_suggestion = msg_invalid_host + "You may need to add %r to ALLOWED_HOSTS."
         msg_suggestion2 = msg_invalid_host + "The domain name provided is not valid according to RFC 1034/1035"
 
-        for host in [ # Valid-looking hosts
+        for host in [  # Valid-looking hosts
             'example.com',
             '12.34.56.78',
             '[2001:19f0:feee::dead:beef:cafe]',
-            'xn--4ca9at.com', # Punnycode for Ć¶Ć¤Ć¼.com
+            'xn--4ca9at.com',  # Punnycode for Ć¶Ć¤Ć¼.com
         ]:
             request = HttpRequest()
             request.META = {'HTTP_HOST': host}
@@ -650,7 +650,7 @@ class HostValidationTests(SimpleTestCase):
                 request.get_host
             )
 
-        for domain, port in [ # Valid-looking hosts with a port number
+        for domain, port in [  # Valid-looking hosts with a port number
             ('example.com', 80),
             ('12.34.56.78', 443),
             ('[2001:19f0:feee::dead:beef:cafe]', 8080),
diff --git a/tests/serializers_regress/tests.py b/tests/serializers_regress/tests.py
index c8f29f471e..d71dd8c406 100644
--- a/tests/serializers_regress/tests.py
+++ b/tests/serializers_regress/tests.py
@@ -308,7 +308,7 @@ The end."""),
 
     (im2m_obj, 470, M2MIntermediateData, None),
 
-    #testing post- and prereferences and extra fields
+    # testing post- and prereferences and extra fields
     (im_obj, 480, Intermediate, {'right': 300, 'left': 470}),
     (im_obj, 481, Intermediate, {'right': 300, 'left': 490}),
     (im_obj, 482, Intermediate, {'right': 500, 'left': 470}),
diff --git a/tests/template_tests/filters.py b/tests/template_tests/filters.py
index 0531fb09cf..ad85d0cb0b 100644
--- a/tests/template_tests/filters.py
+++ b/tests/template_tests/filters.py
@@ -357,7 +357,7 @@ def get_filter_tests():
 
         'date01': (r'{{ d|date:"m" }}', {'d': datetime(2008, 1, 1)}, '01'),
         'date02': (r'{{ d|date }}', {'d': datetime(2008, 1, 1)}, 'Jan. 1, 2008'),
-        #Ticket 9520: Make sure |date doesn't blow up on non-dates
+        # Ticket 9520: Make sure |date doesn't blow up on non-dates
         'date03': (r'{{ d|date:"m" }}', {'d': 'fail_string'}, ''),
         # ISO date formats
         'date04': (r'{{ d|date:"o" }}', {'d': datetime(2008, 12, 29)}, '2009'),
diff --git a/tests/template_tests/tests.py b/tests/template_tests/tests.py
index 9ee845ec51..bad15e2834 100644
--- a/tests/template_tests/tests.py
+++ b/tests/template_tests/tests.py
@@ -853,7 +853,7 @@ class TemplateTests(TransRealMixin, TestCase):
             # Numbers as filter arguments should work
             'filter-syntax19': ('{{ var|truncatewords:1 }}', {"var": "hello world"}, "hello ..."),
 
-            #filters should accept empty string constants
+            # filters should accept empty string constants
             'filter-syntax20': ('{{ ""|default_if_none:"was none" }}', {}, ""),
 
             # Fail silently for non-callable attribute and dict lookups which
diff --git a/tests/test_client/tests.py b/tests/test_client/tests.py
index 75801427d3..14191306c4 100644
--- a/tests/test_client/tests.py
+++ b/tests/test_client/tests.py
@@ -439,7 +439,7 @@ class ClientTest(TestCase):
         "Request a page that is known to throw an error"
         self.assertRaises(KeyError, self.client.get, "/test_client/broken_view/")
 
-        #Try the same assertion, a different way
+        # Try the same assertion, a different way
         try:
             self.client.get('/test_client/broken_view/')
             self.fail('Should raise an error')
diff --git a/tests/test_client_regress/tests.py b/tests/test_client_regress/tests.py
index 83d6a0097e..04fa734ddc 100644
--- a/tests/test_client_regress/tests.py
+++ b/tests/test_client_regress/tests.py
@@ -122,14 +122,14 @@ class AssertContainsTests(TestCase):
 
     def test_unicode_contains(self):
         "Unicode characters can be found in template context"
-        #Regression test for #10183
+        # Regression test for #10183
         r = self.client.get('/test_client_regress/check_unicode/')
         self.assertContains(r, '恕恋恍')
         self.assertContains(r, b'\xe5\xb3\xa0'.decode('utf-8'))
 
     def test_unicode_not_contains(self):
         "Unicode characters can be searched for, and not found in template context"
-        #Regression test for #10183
+        # Regression test for #10183
         r = self.client.get('/test_client_regress/check_unicode/')
         self.assertNotContains(r, 'ćÆ恟恑')
         self.assertNotContains(r, b'\xe3\x81\xaf\xe3\x81\x9f\xe3\x81\x91'.decode('utf-8'))
@@ -1204,7 +1204,7 @@ class UnicodePayloadTests(TestCase):
 
     def test_unicode_payload_non_utf(self):
         "A non-ASCII unicode data as a non-UTF based encoding can be POSTed"
-        #Regression test for #10571
+        # Regression test for #10571
         json = '{"dog": "сŠ¾Š±Š°ŠŗŠ°"}'
         response = self.client.post("/test_client_regress/parse_unicode_json/", json,
                                     content_type="application/json; charset=koi8-r")
diff --git a/tests/view_tests/__init__.py b/tests/view_tests/__init__.py
index b031e205e0..371ab40b40 100644
--- a/tests/view_tests/__init__.py
+++ b/tests/view_tests/__init__.py
@@ -7,5 +7,5 @@ class BrokenException(Exception):
 
 except_args = (b'Broken!',         # plain exception with ASCII text
                'Ā”Broken!',         # non-ASCII unicode data
-               'Ā”Broken!'.encode('utf-8'), # non-ASCII, utf-8 encoded bytestring
+               'Ā”Broken!'.encode('utf-8'),  # non-ASCII, utf-8 encoded bytestring
                b'\xa1Broken!', )   # non-ASCII, latin1 bytestring
diff --git a/tests/view_tests/tests/test_defaults.py b/tests/view_tests/tests/test_defaults.py
index 13e56d604b..128fb7cb07 100644
--- a/tests/view_tests/tests/test_defaults.py
+++ b/tests/view_tests/tests/test_defaults.py
@@ -10,8 +10,8 @@ from ..models import UrlArticle
 class DefaultsTests(TestCase):
     """Test django views in django/views/defaults.py"""
     fixtures = ['testdata.json']
-    non_existing_urls = ['/views/non_existing_url/', # this is in urls.py
-                         '/views/other_non_existing_url/'] # this NOT in urls.py
+    non_existing_urls = ['/views/non_existing_url/',  # this is in urls.py
+                         '/views/other_non_existing_url/']  # this NOT in urls.py
 
     def test_page_not_found(self):
         "A 404 status is returned by the page_not_found view"

From 3f115776e1ffaf7b48976f88faf36c423e544d1d Mon Sep 17 00:00:00 2001
From: Jason Myers <jason@jasonamyers.com>
Date: Sat, 2 Nov 2013 17:50:35 -0500
Subject: [PATCH 3/8] PEP8

Signed-off-by: Jason Myers <jason@jasonamyers.com>
---
 tests/admin_views/admin.py                    | 22 +++++++++++
 tests/decorators/tests.py                     |  3 +-
 tests/defer/models.py                         |  4 ++
 tests/defer_regress/models.py                 | 14 +++++++
 tests/model_forms/tests.py                    | 11 ++++--
 tests/model_forms_regress/models.py           | 12 ++++++
 tests/model_forms_regress/tests.py            |  7 +++-
 tests/model_formsets/models.py                | 26 +++++++++++++
 tests/model_formsets_regress/models.py        |  6 +++
 tests/model_formsets_regress/tests.py         |  1 +
 tests/model_inheritance/models.py             | 22 +++++++++++
 tests/model_inheritance_regress/models.py     | 37 +++++++++++++++++++
 .../models.py                                 |  2 +
 tests/model_validation/models.py              |  1 +
 tests/modeladmin/models.py                    |  3 ++
 tests/multiple_database/models.py             |  6 +++
 16 files changed, 172 insertions(+), 5 deletions(-)

diff --git a/tests/admin_views/admin.py b/tests/admin_views/admin.py
index 2aa96fbafa..039383a7dc 100644
--- a/tests/admin_views/admin.py
+++ b/tests/admin_views/admin.py
@@ -58,6 +58,7 @@ class ArticleInline(admin.TabularInline):
         })
     )
 
+
 class ChapterInline(admin.TabularInline):
     model = Chapter
 
@@ -578,10 +579,12 @@ class AdminOrderedFieldAdmin(admin.ModelAdmin):
     ordering = ('order',)
     list_display = ('stuff', 'order')
 
+
 class AdminOrderedModelMethodAdmin(admin.ModelAdmin):
     ordering = ('order',)
     list_display = ('stuff', 'some_order')
 
+
 class AdminOrderedAdminMethodAdmin(admin.ModelAdmin):
     def some_admin_order(self, obj):
         return obj.order
@@ -589,13 +592,17 @@ class AdminOrderedAdminMethodAdmin(admin.ModelAdmin):
     ordering = ('order',)
     list_display = ('stuff', 'some_admin_order')
 
+
 def admin_ordered_callable(obj):
     return obj.order
 admin_ordered_callable.admin_order_field = 'order'
+
+
 class AdminOrderedCallableAdmin(admin.ModelAdmin):
     ordering = ('order',)
     list_display = ('stuff', admin_ordered_callable)
 
+
 class ReportAdmin(admin.ModelAdmin):
     def extra(self, request):
         return HttpResponse()
@@ -612,6 +619,7 @@ class ReportAdmin(admin.ModelAdmin):
 class CustomTemplateBooleanFieldListFilter(BooleanFieldListFilter):
     template = 'custom_filter_template.html'
 
+
 class CustomTemplateFilterColorAdmin(admin.ModelAdmin):
     list_filter = (('warm', CustomTemplateBooleanFieldListFilter),)
 
@@ -628,12 +636,14 @@ class RelatedPrepopulatedInline1(admin.StackedInline):
     prepopulated_fields = {'slug1': ['name', 'pubdate'],
                            'slug2': ['status', 'name']}
 
+
 class RelatedPrepopulatedInline2(admin.TabularInline):
     model = RelatedPrepopulated
     extra = 1
     prepopulated_fields = {'slug1': ['name', 'pubdate'],
                            'slug2': ['status', 'name']}
 
+
 class MainPrepopulatedAdmin(admin.ModelAdmin):
     inlines = [RelatedPrepopulatedInline1, RelatedPrepopulatedInline2]
     fieldsets = (
@@ -712,14 +722,17 @@ class FormWithoutHiddenField(forms.ModelForm):
     first = forms.CharField()
     second = forms.CharField()
 
+
 class FormWithoutVisibleField(forms.ModelForm):
     first = forms.CharField(widget=forms.HiddenInput)
     second = forms.CharField(widget=forms.HiddenInput)
 
+
 class FormWithVisibleAndHiddenField(forms.ModelForm):
     first = forms.CharField(widget=forms.HiddenInput)
     second = forms.CharField()
 
+
 class EmptyModelVisibleAdmin(admin.ModelAdmin):
     form = FormWithoutHiddenField
     fieldsets = (
@@ -728,39 +741,48 @@ class EmptyModelVisibleAdmin(admin.ModelAdmin):
         }),
     )
 
+
 class EmptyModelHiddenAdmin(admin.ModelAdmin):
     form = FormWithoutVisibleField
     fieldsets = EmptyModelVisibleAdmin.fieldsets
 
+
 class EmptyModelMixinAdmin(admin.ModelAdmin):
     form = FormWithVisibleAndHiddenField
     fieldsets = EmptyModelVisibleAdmin.fieldsets
 
+
 class CityInlineAdmin(admin.TabularInline):
     model = City
     view_on_site = False
 
+
 class StateAdmin(admin.ModelAdmin):
     inlines = [CityInlineAdmin]
 
+
 class RestaurantInlineAdmin(admin.TabularInline):
     model = Restaurant
     view_on_site = True
 
+
 class CityAdmin(admin.ModelAdmin):
     inlines = [RestaurantInlineAdmin]
     view_on_site = True
 
+
 class WorkerAdmin(admin.ModelAdmin):
     def view_on_site(self, obj):
         return '/worker/%s/%s/' % (obj.surname, obj.name)
 
+
 class WorkerInlineAdmin(admin.TabularInline):
     model = Worker
 
     def view_on_site(self, obj):
         return '/worker_inline/%s/%s/' % (obj.surname, obj.name)
 
+
 class RestaurantAdmin(admin.ModelAdmin):
     inlines = [WorkerInlineAdmin]
     view_on_site = False
diff --git a/tests/decorators/tests.py b/tests/decorators/tests.py
index 4016273ef5..db00f36051 100644
--- a/tests/decorators/tests.py
+++ b/tests/decorators/tests.py
@@ -44,7 +44,7 @@ full_decorator = compose(
     vary_on_cookie,
 
     # django.views.decorators.cache
-    cache_page(60*15),
+    cache_page(60 * 15),
     cache_control(private=True),
     never_cache,
 
@@ -65,6 +65,7 @@ full_decorator = compose(
 
 fully_decorated = full_decorator(fully_decorated)
 
+
 class DecoratorsTest(TestCase):
 
     def test_attributes(self):
diff --git a/tests/defer/models.py b/tests/defer/models.py
index cf3bae86bb..ffc8a0c2c7 100644
--- a/tests/defer/models.py
+++ b/tests/defer/models.py
@@ -10,6 +10,7 @@ class Secondary(models.Model):
     first = models.CharField(max_length=50)
     second = models.CharField(max_length=50)
 
+
 @python_2_unicode_compatible
 class Primary(models.Model):
     name = models.CharField(max_length=50)
@@ -19,12 +20,15 @@ class Primary(models.Model):
     def __str__(self):
         return self.name
 
+
 class Child(Primary):
     pass
 
+
 class BigChild(Primary):
     other = models.CharField(max_length=50)
 
+
 class ChildProxy(Child):
     class Meta:
         proxy = True
diff --git a/tests/defer_regress/models.py b/tests/defer_regress/models.py
index 0170221cb9..d858558e97 100644
--- a/tests/defer_regress/models.py
+++ b/tests/defer_regress/models.py
@@ -16,13 +16,16 @@ class Item(models.Model):
     def __str__(self):
         return self.name
 
+
 class RelatedItem(models.Model):
     item = models.ForeignKey(Item)
 
+
 class Child(models.Model):
     name = models.CharField(max_length=10)
     value = models.IntegerField()
 
+
 @python_2_unicode_compatible
 class Leaf(models.Model):
     name = models.CharField(max_length=10)
@@ -33,14 +36,17 @@ class Leaf(models.Model):
     def __str__(self):
         return self.name
 
+
 class ResolveThis(models.Model):
     num = models.FloatField()
     name = models.CharField(max_length=16)
 
+
 class Proxy(Item):
     class Meta:
         proxy = True
 
+
 @python_2_unicode_compatible
 class SimpleItem(models.Model):
     name = models.CharField(max_length=15)
@@ -49,29 +55,37 @@ class SimpleItem(models.Model):
     def __str__(self):
         return self.name
 
+
 class Feature(models.Model):
     item = models.ForeignKey(SimpleItem)
 
+
 class SpecialFeature(models.Model):
     feature = models.ForeignKey(Feature)
 
+
 class OneToOneItem(models.Model):
     item = models.OneToOneField(Item, related_name="one_to_one_item")
     name = models.CharField(max_length=15)
 
+
 class ItemAndSimpleItem(models.Model):
     item = models.ForeignKey(Item)
     simple = models.ForeignKey(SimpleItem)
 
+
 class Profile(models.Model):
     profile1 = models.CharField(max_length=1000, default='profile1')
 
+
 class Location(models.Model):
     location1 = models.CharField(max_length=1000, default='location1')
 
+
 class Item(models.Model):
     pass
 
+
 class Request(models.Model):
     profile = models.ForeignKey(Profile, null=True, blank=True)
     location = models.ForeignKey(Location)
diff --git a/tests/model_forms/tests.py b/tests/model_forms/tests.py
index ddc7a4ceef..5e443011c2 100644
--- a/tests/model_forms/tests.py
+++ b/tests/model_forms/tests.py
@@ -185,6 +185,7 @@ class BetterWriterForm(forms.ModelForm):
         model = BetterWriter
         fields = '__all__'
 
+
 class WriterProfileForm(forms.ModelForm):
     class Meta:
         model = WriterProfile
@@ -234,6 +235,7 @@ class ColourfulItemForm(forms.ModelForm):
 
 # model forms for testing work on #9321:
 
+
 class StatusNoteForm(forms.ModelForm):
     class Meta:
         model = ArticleStatusNote
@@ -295,7 +297,7 @@ class ModelFormBaseTest(TestCase):
                 fields = '__all__'
 
         self.assertIsInstance(ReplaceField.base_fields['url'],
-                                     forms.fields.BooleanField)
+            forms.fields.BooleanField)
 
     def test_replace_field_variant_2(self):
         # Should have the same result as before,
@@ -308,7 +310,7 @@ class ModelFormBaseTest(TestCase):
                 fields = ['url']
 
         self.assertIsInstance(ReplaceField.base_fields['url'],
-                                     forms.fields.BooleanField)
+            forms.fields.BooleanField)
 
     def test_replace_field_variant_3(self):
         # Should have the same result as before,
@@ -321,7 +323,7 @@ class ModelFormBaseTest(TestCase):
                 fields = []  # url will still appear, since it is explicit above
 
         self.assertIsInstance(ReplaceField.base_fields['url'],
-                                     forms.fields.BooleanField)
+            forms.fields.BooleanField)
 
     def test_override_field(self):
         class WriterForm(forms.ModelForm):
@@ -583,6 +585,7 @@ class IncompleteCategoryFormWithFields(forms.ModelForm):
         fields = ('name', 'slug')
         model = Category
 
+
 class IncompleteCategoryFormWithExclude(forms.ModelForm):
     """
     A form that replaces the model's url field with a custom one. This should
@@ -788,6 +791,7 @@ class UniqueTest(TestCase):
             "slug": "Django 1.0"}, instance=p)
         self.assertTrue(form.is_valid())
 
+
 class ModelToDictTests(TestCase):
     """
     Tests for forms.models.model_to_dict
@@ -824,6 +828,7 @@ class ModelToDictTests(TestCase):
         # Ensure many-to-many relation appears as a list
         self.assertIsInstance(d['categories'], list)
 
+
 class OldFormForXTests(TestCase):
     def test_base_form(self):
         self.assertEqual(Category.objects.count(), 0)
diff --git a/tests/model_forms_regress/models.py b/tests/model_forms_regress/models.py
index 2c2fd39158..396bd1eaa4 100644
--- a/tests/model_forms_regress/models.py
+++ b/tests/model_forms_regress/models.py
@@ -11,6 +11,7 @@ from django.utils._os import upath
 class Person(models.Model):
     name = models.CharField(max_length=100)
 
+
 class Triple(models.Model):
     left = models.IntegerField()
     middle = models.IntegerField()
@@ -19,9 +20,11 @@ class Triple(models.Model):
     class Meta:
         unique_together = (('left', 'middle'), ('middle', 'right'))
 
+
 class FilePathModel(models.Model):
     path = models.FilePathField(path=os.path.dirname(upath(__file__)), match=".*\.py$", blank=True)
 
+
 @python_2_unicode_compatible
 class Publication(models.Model):
     title = models.CharField(max_length=30)
@@ -30,6 +33,7 @@ class Publication(models.Model):
     def __str__(self):
         return self.title
 
+
 @python_2_unicode_compatible
 class Article(models.Model):
     headline = models.CharField(max_length=100)
@@ -38,15 +42,18 @@ class Article(models.Model):
     def __str__(self):
         return self.headline
 
+
 class CustomFileField(models.FileField):
     def save_form_data(self, instance, data):
         been_here = getattr(self, 'been_saved', False)
         assert not been_here, "save_form_data called more than once"
         setattr(self, 'been_saved', True)
 
+
 class CustomFF(models.Model):
     f = CustomFileField(upload_to='unused', blank=True)
 
+
 class RealPerson(models.Model):
     name = models.CharField(max_length=100)
 
@@ -54,20 +61,25 @@ class RealPerson(models.Model):
         if self.name.lower() == 'anonymous':
             raise ValidationError("Please specify a real name.")
 
+
 class Author(models.Model):
     publication = models.OneToOneField(Publication, null=True, blank=True)
     full_name = models.CharField(max_length=255)
 
+
 class Author1(models.Model):
     publication = models.OneToOneField(Publication, null=False)
     full_name = models.CharField(max_length=255)
 
+
 class Homepage(models.Model):
     url = models.URLField()
 
+
 class Document(models.Model):
     myfile = models.FileField(upload_to='unused', blank=True)
 
+
 class Edition(models.Model):
     author = models.ForeignKey(Person)
     publication = models.ForeignKey(Publication)
diff --git a/tests/model_forms_regress/tests.py b/tests/model_forms_regress/tests.py
index b7f4cf5979..963c7e552d 100644
--- a/tests/model_forms_regress/tests.py
+++ b/tests/model_forms_regress/tests.py
@@ -106,6 +106,7 @@ class FullyLocalizedTripleForm(forms.ModelForm):
         localized_fields = '__all__'
         fields = '__all__'
 
+
 class LocalizedModelFormTest(TestCase):
     def test_model_form_applies_localize_to_some_fields(self):
         f = PartiallyLocalizedTripleForm({'left': 10, 'middle': 10, 'right': 10})
@@ -167,6 +168,7 @@ class FilePathFieldTests(TestCase):
         names.sort()
         self.assertEqual(names, ['---------', '__init__.py', 'models.py', 'tests.py'])
 
+
 class ManyToManyCallableInitialTests(TestCase):
     def test_callable(self):
         "Regression for #10349: A callable can be provided as the initial value for an m2m field"
@@ -207,9 +209,10 @@ class CustomFieldSaveTests(TestCase):
 
         # It's enough that the form saves without error -- the custom save routine will
         # generate an AssertionError if it is called more than once during save.
-        form = CFFForm(data = {'f': None})
+        form = CFFForm(data={'f': None})
         form.save()
 
+
 class ModelChoiceIteratorTests(TestCase):
     def test_len(self):
         class Form(forms.ModelForm):
@@ -236,12 +239,14 @@ class CustomModelFormSaveMethod(TestCase):
         self.assertEqual(form.is_valid(), False)
         self.assertEqual(form.errors['__all__'], ['Please specify a real name.'])
 
+
 class ModelClassTests(TestCase):
     def test_no_model_class(self):
         class NoModelModelForm(forms.ModelForm):
             pass
         self.assertRaises(ValueError, NoModelModelForm)
 
+
 class OneToOneFieldTests(TestCase):
     def test_assignment_of_none(self):
         class AuthorForm(forms.ModelForm):
diff --git a/tests/model_formsets/models.py b/tests/model_formsets/models.py
index adeb3455a4..da79c6a573 100644
--- a/tests/model_formsets/models.py
+++ b/tests/model_formsets/models.py
@@ -17,9 +17,11 @@ class Author(models.Model):
     def __str__(self):
         return self.name
 
+
 class BetterAuthor(Author):
     write_speed = models.IntegerField()
 
+
 @python_2_unicode_compatible
 class Book(models.Model):
     author = models.ForeignKey(Author)
@@ -34,6 +36,7 @@ class Book(models.Model):
     def __str__(self):
         return self.title
 
+
 @python_2_unicode_compatible
 class BookWithCustomPK(models.Model):
     my_pk = models.DecimalField(max_digits=5, decimal_places=0, primary_key=True)
@@ -43,9 +46,11 @@ class BookWithCustomPK(models.Model):
     def __str__(self):
         return '%s: %s' % (self.my_pk, self.title)
 
+
 class Editor(models.Model):
     name = models.CharField(max_length=100)
 
+
 @python_2_unicode_compatible
 class BookWithOptionalAltEditor(models.Model):
     author = models.ForeignKey(Author)
@@ -61,6 +66,7 @@ class BookWithOptionalAltEditor(models.Model):
     def __str__(self):
         return self.title
 
+
 @python_2_unicode_compatible
 class AlternateBook(Book):
     notes = models.CharField(max_length=100)
@@ -68,6 +74,7 @@ class AlternateBook(Book):
     def __str__(self):
         return '%s - %s' % (self.title, self.notes)
 
+
 @python_2_unicode_compatible
 class AuthorMeeting(models.Model):
     name = models.CharField(max_length=100)
@@ -77,6 +84,7 @@ class AuthorMeeting(models.Model):
     def __str__(self):
         return self.name
 
+
 class CustomPrimaryKey(models.Model):
     my_pk = models.CharField(max_length=10, primary_key=True)
     some_field = models.CharField(max_length=100)
@@ -84,6 +92,7 @@ class CustomPrimaryKey(models.Model):
 
 # models for inheritance tests.
 
+
 @python_2_unicode_compatible
 class Place(models.Model):
     name = models.CharField(max_length=50)
@@ -92,6 +101,7 @@ class Place(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Owner(models.Model):
     auto_id = models.AutoField(primary_key=True)
@@ -101,12 +111,14 @@ class Owner(models.Model):
     def __str__(self):
         return "%s at %s" % (self.name, self.place)
 
+
 class Location(models.Model):
     place = models.ForeignKey(Place, unique=True)
     # this is purely for testing the data doesn't matter here :)
     lat = models.CharField(max_length=100)
     lon = models.CharField(max_length=100)
 
+
 @python_2_unicode_compatible
 class OwnerProfile(models.Model):
     owner = models.OneToOneField(Owner, primary_key=True)
@@ -115,6 +127,7 @@ class OwnerProfile(models.Model):
     def __str__(self):
         return "%s is %d" % (self.owner.name, self.age)
 
+
 @python_2_unicode_compatible
 class Restaurant(Place):
     serves_pizza = models.BooleanField(default=False)
@@ -122,6 +135,7 @@ class Restaurant(Place):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Product(models.Model):
     slug = models.SlugField(unique=True)
@@ -129,6 +143,7 @@ class Product(models.Model):
     def __str__(self):
         return self.slug
 
+
 @python_2_unicode_compatible
 class Price(models.Model):
     price = models.DecimalField(max_digits=10, decimal_places=2)
@@ -140,13 +155,16 @@ class Price(models.Model):
     class Meta:
         unique_together = (('price', 'quantity'),)
 
+
 class MexicanRestaurant(Restaurant):
     serves_tacos = models.BooleanField(default=False)
 
+
 class ClassyMexicanRestaurant(MexicanRestaurant):
     restaurant = models.OneToOneField(MexicanRestaurant, parent_link=True, primary_key=True)
     tacos_are_yummy = models.BooleanField(default=False)
 
+
 # models for testing unique_together validation when a fk is involved and
 # using inlineformset_factory.
 @python_2_unicode_compatible
@@ -156,6 +174,7 @@ class Repository(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Revision(models.Model):
     repository = models.ForeignKey(Repository)
@@ -167,21 +186,25 @@ class Revision(models.Model):
     def __str__(self):
         return "%s (%s)" % (self.revision, six.text_type(self.repository))
 
+
 # models for testing callable defaults (see bug #7975). If you define a model
 # with a callable default value, you cannot rely on the initial value in a
 # form.
 class Person(models.Model):
     name = models.CharField(max_length=128)
 
+
 class Membership(models.Model):
     person = models.ForeignKey(Person)
     date_joined = models.DateTimeField(default=datetime.datetime.now)
     karma = models.IntegerField()
 
+
 # models for testing a null=True fk to a parent
 class Team(models.Model):
     name = models.CharField(max_length=100)
 
+
 @python_2_unicode_compatible
 class Player(models.Model):
     team = models.ForeignKey(Team, null=True)
@@ -190,6 +213,7 @@ class Player(models.Model):
     def __str__(self):
         return self.name
 
+
 # Models for testing custom ModelForm save methods in formsets and inline formsets
 @python_2_unicode_compatible
 class Poet(models.Model):
@@ -198,6 +222,7 @@ class Poet(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Poem(models.Model):
     poet = models.ForeignKey(Poet)
@@ -206,6 +231,7 @@ class Poem(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Post(models.Model):
     title = models.CharField(max_length=50, unique_for_date='posted', blank=True)
diff --git a/tests/model_formsets_regress/models.py b/tests/model_formsets_regress/models.py
index f94ad51929..58eed6a22b 100644
--- a/tests/model_formsets_regress/models.py
+++ b/tests/model_formsets_regress/models.py
@@ -6,23 +6,29 @@ class User(models.Model):
     username = models.CharField(max_length=12, unique=True)
     serial = models.IntegerField()
 
+
 class UserSite(models.Model):
     user = models.ForeignKey(User, to_field="username")
     data = models.IntegerField()
 
+
 class Place(models.Model):
     name = models.CharField(max_length=50)
 
+
 class Restaurant(Place):
     pass
 
+
 class Manager(models.Model):
     retaurant = models.ForeignKey(Restaurant)
     name = models.CharField(max_length=50)
 
+
 class Network(models.Model):
     name = models.CharField(max_length=15)
 
+
 @python_2_unicode_compatible
 class Host(models.Model):
     network = models.ForeignKey(Network)
diff --git a/tests/model_formsets_regress/tests.py b/tests/model_formsets_regress/tests.py
index f8a5b7b3ac..7d400d2f87 100644
--- a/tests/model_formsets_regress/tests.py
+++ b/tests/model_formsets_regress/tests.py
@@ -330,6 +330,7 @@ class FormfieldCallbackTests(TestCase):
                              formfield_callback=callback)
         self.assertCallbackCalled(callback)
 
+
 class BaseCustomDeleteFormSet(BaseFormSet):
     """
     A formset mix-in that lets a form decide if it's to be deleted.
diff --git a/tests/model_inheritance/models.py b/tests/model_inheritance/models.py
index 020bb35bc7..7f5702da59 100644
--- a/tests/model_inheritance/models.py
+++ b/tests/model_inheritance/models.py
@@ -20,6 +20,7 @@ from django.utils.encoding import python_2_unicode_compatible
 # Abstract base classes
 #
 
+
 @python_2_unicode_compatible
 class CommonInfo(models.Model):
     name = models.CharField(max_length=50)
@@ -32,18 +33,22 @@ class CommonInfo(models.Model):
     def __str__(self):
         return '%s %s' % (self.__class__.__name__, self.name)
 
+
 class Worker(CommonInfo):
     job = models.CharField(max_length=50)
 
+
 class Student(CommonInfo):
     school_class = models.CharField(max_length=10)
 
     class Meta:
         pass
 
+
 class StudentWorker(Student, Worker):
     pass
 
+
 #
 # Abstract base classes with related models
 #
@@ -51,6 +56,7 @@ class StudentWorker(Student, Worker):
 class Post(models.Model):
     title = models.CharField(max_length=50)
 
+
 @python_2_unicode_compatible
 class Attachment(models.Model):
     post = models.ForeignKey(Post, related_name='attached_%(class)s_set')
@@ -62,12 +68,15 @@ class Attachment(models.Model):
     def __str__(self):
         return self.content
 
+
 class Comment(Attachment):
     is_spam = models.BooleanField(default=False)
 
+
 class Link(Attachment):
     url = models.URLField()
 
+
 #
 # Multi-table inheritance
 #
@@ -79,6 +88,7 @@ class Chef(models.Model):
     def __str__(self):
         return "%s the chef" % self.name
 
+
 @python_2_unicode_compatible
 class Place(models.Model):
     name = models.CharField(max_length=50)
@@ -87,6 +97,7 @@ class Place(models.Model):
     def __str__(self):
         return "%s the place" % self.name
 
+
 class Rating(models.Model):
     rating = models.IntegerField(null=True, blank=True)
 
@@ -94,6 +105,7 @@ class Rating(models.Model):
         abstract = True
         ordering = ['-rating']
 
+
 @python_2_unicode_compatible
 class Restaurant(Place, Rating):
     serves_hot_dogs = models.BooleanField(default=False)
@@ -106,6 +118,7 @@ class Restaurant(Place, Rating):
     def __str__(self):
         return "%s the restaurant" % self.name
 
+
 @python_2_unicode_compatible
 class ItalianRestaurant(Restaurant):
     serves_gnocchi = models.BooleanField(default=False)
@@ -113,6 +126,7 @@ class ItalianRestaurant(Restaurant):
     def __str__(self):
         return "%s the italian restaurant" % self.name
 
+
 @python_2_unicode_compatible
 class Supplier(Place):
     customers = models.ManyToManyField(Restaurant, related_name='provider')
@@ -120,6 +134,7 @@ class Supplier(Place):
     def __str__(self):
         return "%s the supplier" % self.name
 
+
 @python_2_unicode_compatible
 class ParkingLot(Place):
     # An explicit link to the parent (we can control the attribute name).
@@ -129,6 +144,7 @@ class ParkingLot(Place):
     def __str__(self):
         return "%s the parking lot" % self.name
 
+
 #
 # Abstract base classes with related models where the sub-class has the
 # same name in a different app and inherits from the same abstract base
@@ -141,6 +157,7 @@ class ParkingLot(Place):
 class Title(models.Model):
     title = models.CharField(max_length=50)
 
+
 class NamedURL(models.Model):
     title = models.ForeignKey(Title, related_name='attached_%(app_label)s_%(class)s_set')
     url = models.URLField()
@@ -148,6 +165,7 @@ class NamedURL(models.Model):
     class Meta:
         abstract = True
 
+
 @python_2_unicode_compatible
 class Copy(NamedURL):
     content = models.TextField()
@@ -155,16 +173,20 @@ class Copy(NamedURL):
     def __str__(self):
         return self.content
 
+
 class Mixin(object):
     def __init__(self):
         self.other_attr = 1
         super(Mixin, self).__init__()
 
+
 class MixinModel(models.Model, Mixin):
     pass
 
+
 class Base(models.Model):
     titles = models.ManyToManyField(Title)
 
+
 class SubBase(Base):
     sub_id = models.IntegerField(primary_key=True)
diff --git a/tests/model_inheritance_regress/models.py b/tests/model_inheritance_regress/models.py
index 04febf54a6..53752b6948 100644
--- a/tests/model_inheritance_regress/models.py
+++ b/tests/model_inheritance_regress/models.py
@@ -5,6 +5,7 @@ import datetime
 from django.db import models
 from django.utils.encoding import python_2_unicode_compatible
 
+
 @python_2_unicode_compatible
 class Place(models.Model):
     name = models.CharField(max_length=50)
@@ -16,6 +17,7 @@ class Place(models.Model):
     def __str__(self):
         return "%s the place" % self.name
 
+
 @python_2_unicode_compatible
 class Restaurant(Place):
     serves_hot_dogs = models.BooleanField(default=False)
@@ -24,6 +26,7 @@ class Restaurant(Place):
     def __str__(self):
         return "%s the restaurant" % self.name
 
+
 @python_2_unicode_compatible
 class ItalianRestaurant(Restaurant):
     serves_gnocchi = models.BooleanField(default=False)
@@ -31,6 +34,7 @@ class ItalianRestaurant(Restaurant):
     def __str__(self):
         return "%s the italian restaurant" % self.name
 
+
 @python_2_unicode_compatible
 class ParkingLot(Place):
     # An explicit link to the parent (we can control the attribute name).
@@ -40,16 +44,19 @@ class ParkingLot(Place):
     def __str__(self):
         return "%s the parking lot" % self.name
 
+
 class ParkingLot2(Place):
     # In lieu of any other connector, an existing OneToOneField will be
     # promoted to the primary key.
     parent = models.OneToOneField(Place)
 
+
 class ParkingLot3(Place):
     # The parent_link connector need not be the pk on the model.
     primary_key = models.AutoField(primary_key=True)
     parent = models.OneToOneField(Place, parent_link=True)
 
+
 class ParkingLot4(models.Model):
     # Test parent_link connector can be discovered in abstract classes.
     parent = models.OneToOneField(Place, parent_link=True)
@@ -57,31 +64,40 @@ class ParkingLot4(models.Model):
     class Meta:
         abstract = True
 
+
 class ParkingLot4A(ParkingLot4, Place):
     pass
 
+
 class ParkingLot4B(Place, ParkingLot4):
     pass
 
+
 class Supplier(models.Model):
     restaurant = models.ForeignKey(Restaurant)
 
+
 class Wholesaler(Supplier):
     retailer = models.ForeignKey(Supplier, related_name='wholesale_supplier')
 
+
 class Parent(models.Model):
     created = models.DateTimeField(default=datetime.datetime.now)
 
+
 class Child(Parent):
     name = models.CharField(max_length=10)
 
+
 class SelfRefParent(models.Model):
     parent_data = models.IntegerField()
     self_data = models.ForeignKey('self', null=True)
 
+
 class SelfRefChild(SelfRefParent):
     child_data = models.IntegerField()
 
+
 @python_2_unicode_compatible
 class Article(models.Model):
     headline = models.CharField(max_length=100)
@@ -93,24 +109,30 @@ class Article(models.Model):
     def __str__(self):
         return self.headline
 
+
 class ArticleWithAuthor(Article):
     author = models.CharField(max_length=100)
 
+
 class M2MBase(models.Model):
     articles = models.ManyToManyField(Article)
 
+
 class M2MChild(M2MBase):
     name = models.CharField(max_length=50)
 
+
 class Evaluation(Article):
     quality = models.IntegerField()
 
     class Meta:
         abstract = True
 
+
 class QualityControl(Evaluation):
     assignee = models.CharField(max_length=50)
 
+
 @python_2_unicode_compatible
 class BaseM(models.Model):
     base_name = models.CharField(max_length=100)
@@ -118,6 +140,7 @@ class BaseM(models.Model):
     def __str__(self):
         return self.base_name
 
+
 @python_2_unicode_compatible
 class DerivedM(BaseM):
     customPK = models.IntegerField(primary_key=True)
@@ -127,6 +150,7 @@ class DerivedM(BaseM):
         return "PK = %d, base_name = %s, derived_name = %s" % (
             self.customPK, self.base_name, self.derived_name)
 
+
 class AuditBase(models.Model):
     planned_date = models.DateField()
 
@@ -134,13 +158,16 @@ class AuditBase(models.Model):
         abstract = True
         verbose_name_plural = 'Audits'
 
+
 class CertificationAudit(AuditBase):
     class Meta(AuditBase.Meta):
         abstract = True
 
+
 class InternalCertificationAudit(CertificationAudit):
     auditing_dept = models.CharField(max_length=20)
 
+
 # Check that abstract classes don't get m2m tables autocreated.
 @python_2_unicode_compatible
 class Person(models.Model):
@@ -152,6 +179,7 @@ class Person(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class AbstractEvent(models.Model):
     name = models.CharField(max_length=100)
@@ -164,35 +192,44 @@ class AbstractEvent(models.Model):
     def __str__(self):
         return self.name
 
+
 class BirthdayParty(AbstractEvent):
     pass
 
+
 class BachelorParty(AbstractEvent):
     pass
 
+
 class MessyBachelorParty(BachelorParty):
     pass
 
+
 # Check concrete -> abstract -> concrete inheritance
 class SearchableLocation(models.Model):
     keywords = models.CharField(max_length=256)
 
+
 class Station(SearchableLocation):
     name = models.CharField(max_length=128)
 
     class Meta:
         abstract = True
 
+
 class BusStation(Station):
     bus_routes = models.CommaSeparatedIntegerField(max_length=128)
     inbound = models.BooleanField(default=False)
 
+
 class TrainStation(Station):
     zone = models.IntegerField()
 
+
 class User(models.Model):
     username = models.CharField(max_length=30, unique=True)
 
+
 class Profile(User):
     profile_id = models.AutoField(primary_key=True)
     extra = models.CharField(max_length=30, blank=True)
diff --git a/tests/model_inheritance_select_related/models.py b/tests/model_inheritance_select_related/models.py
index 46c67cf07d..81f267589c 100644
--- a/tests/model_inheritance_select_related/models.py
+++ b/tests/model_inheritance_select_related/models.py
@@ -18,6 +18,7 @@ class Place(models.Model):
     def __str__(self):
         return "%s the place" % self.name
 
+
 @python_2_unicode_compatible
 class Restaurant(Place):
     serves_sushi = models.BooleanField(default=False)
@@ -26,6 +27,7 @@ class Restaurant(Place):
     def __str__(self):
         return "%s the restaurant" % self.name
 
+
 @python_2_unicode_compatible
 class Person(models.Model):
     name = models.CharField(max_length=50)
diff --git a/tests/model_validation/models.py b/tests/model_validation/models.py
index d2e77cbccc..dfe6d62996 100644
--- a/tests/model_validation/models.py
+++ b/tests/model_validation/models.py
@@ -39,6 +39,7 @@ class ManyToManyRel(models.Model):
         # Models created as unmanaged as these aren't ever queried
         managed = False
 
+
 class FKRel(models.Model):
     thing1 = models.ForeignKey(ThingWithIterableChoices, related_name='+')
     thing2 = models.ForeignKey(ThingWithIterableChoices, related_name='+')
diff --git a/tests/modeladmin/models.py b/tests/modeladmin/models.py
index 27f54821d6..8f57a9fa82 100644
--- a/tests/modeladmin/models.py
+++ b/tests/modeladmin/models.py
@@ -16,6 +16,7 @@ class Band(models.Model):
     def __str__(self):
         return self.name
 
+
 class Concert(models.Model):
     main_band = models.ForeignKey(Band, related_name='main_concerts')
     opening_band = models.ForeignKey(Band, related_name='opening_concerts',
@@ -27,6 +28,7 @@ class Concert(models.Model):
         (3, 'Bus')
     ), blank=True)
 
+
 class ValidationTestModel(models.Model):
     name = models.CharField(max_length=100)
     slug = models.SlugField()
@@ -40,5 +42,6 @@ class ValidationTestModel(models.Model):
     def decade_published_in(self):
         return self.pub_date.strftime('%Y')[:3] + "0's"
 
+
 class ValidationTestInlineModel(models.Model):
     parent = models.ForeignKey(ValidationTestModel)
diff --git a/tests/multiple_database/models.py b/tests/multiple_database/models.py
index 00534c870c..fc5b28ad92 100644
--- a/tests/multiple_database/models.py
+++ b/tests/multiple_database/models.py
@@ -18,10 +18,12 @@ class Review(models.Model):
     class Meta:
         ordering = ('source',)
 
+
 class PersonManager(models.Manager):
     def get_by_natural_key(self, name):
         return self.get(name=name)
 
+
 @python_2_unicode_compatible
 class Person(models.Model):
     objects = PersonManager()
@@ -33,6 +35,7 @@ class Person(models.Model):
     class Meta:
         ordering = ('name',)
 
+
 # This book manager doesn't do anything interesting; it just
 # exists to strip out the 'extra_arg' argument to certain
 # calls. This argument is used to establish that the BookManager
@@ -46,6 +49,7 @@ class BookManager(models.Manager):
         kwargs.pop('extra_arg', None)
         return super(BookManager, self).get_or_create(*args, **kwargs)
 
+
 @python_2_unicode_compatible
 class Book(models.Model):
     objects = BookManager()
@@ -62,6 +66,7 @@ class Book(models.Model):
     class Meta:
         ordering = ('title',)
 
+
 @python_2_unicode_compatible
 class Pet(models.Model):
     name = models.CharField(max_length=100)
@@ -73,6 +78,7 @@ class Pet(models.Model):
     class Meta:
         ordering = ('name',)
 
+
 class UserProfile(models.Model):
     user = models.OneToOneField(User, null=True)
     flavor = models.CharField(max_length=100)

From 5732bc52f1d8f65cb35e19f0621d051233913fe8 Mon Sep 17 00:00:00 2001
From: Ray Ashman Jr <ray.ashman.jr@gmail.com>
Date: Sat, 2 Nov 2013 19:53:29 -0400
Subject: [PATCH 4/8] Correct flake8 E302 violations

---
 django/test/_doctest.py                | 39 +++++++++++++++++++++++++-
 django/test/testcases.py               |  3 ++
 django/utils/_os.py                    |  1 +
 django/utils/autoreload.py             |  8 ++++++
 django/utils/cache.py                  | 12 ++++++++
 django/utils/datastructures.py         |  6 ++++
 django/utils/dateformat.py             |  2 ++
 django/utils/dateparse.py              |  2 ++
 django/utils/datetime_safe.py          |  4 +++
 django/utils/dictconfig.py             |  7 +++++
 django/utils/encoding.py               |  7 +++++
 django/utils/feedgenerator.py          |  8 ++++++
 django/utils/formats.py                | 10 +++++++
 django/utils/html.py                   | 11 ++++++++
 django/utils/http.py                   | 17 +++++++++++
 django/utils/regex_helper.py           |  5 ++++
 django/utils/safestring.py             |  5 ++++
 django/utils/six.py                    |  4 +++
 django/utils/text.py                   | 14 +++++++++
 django/utils/timesince.py              |  2 ++
 django/utils/timezone.py               | 18 ++++++++++++
 django/utils/translation/__init__.py   | 24 ++++++++++++++++
 django/utils/translation/trans_null.py |  9 ++++++
 django/utils/translation/trans_real.py | 24 ++++++++++++++++
 django/views/debug.py                  |  9 ++++++
 django/views/decorators/http.py        |  3 ++
 django/views/decorators/vary.py        |  2 ++
 django/views/generic/dates.py          |  1 +
 django/views/i18n.py                   |  1 +
 django/views/static.py                 |  3 ++
 30 files changed, 260 insertions(+), 1 deletion(-)

diff --git a/django/test/_doctest.py b/django/test/_doctest.py
index 048d886720..c5b94c83a0 100644
--- a/django/test/_doctest.py
+++ b/django/test/_doctest.py
@@ -144,6 +144,8 @@ if sys.platform.startswith('java'):
 # Option constants.
 
 OPTIONFLAGS_BY_NAME = {}
+
+
 def register_optionflag(name):
     # Create a new flag unless `name` is already known.
     return OPTIONFLAGS_BY_NAME.setdefault(name, 1 << len(OPTIONFLAGS_BY_NAME))
@@ -194,6 +196,7 @@ ELLIPSIS_MARKER = '...'
 ## 1. Utility Functions
 ######################################################################
 
+
 def _extract_future_flags(globs):
     """
     Return the compiler-flags associated with the future features that
@@ -206,6 +209,7 @@ def _extract_future_flags(globs):
             flags |= feature.compiler_flag
     return flags
 
+
 def _normalize_module(module, depth=2):
     """
     Return the module specified by `module`.  In particular:
@@ -225,6 +229,7 @@ def _normalize_module(module, depth=2):
     else:
         raise TypeError("Expected a module, string, or None")
 
+
 def _load_testfile(filename, package, module_relative):
     if module_relative:
         package = _normalize_module(package, 3)
@@ -238,6 +243,7 @@ def _load_testfile(filename, package, module_relative):
     with open(filename) as fp:
         return fp.read(), filename
 
+
 def _indent(s, indent=4):
     """
     Add the given number of space characters to the beginning every
@@ -246,6 +252,7 @@ def _indent(s, indent=4):
     # This regexp matches the start of non-blank lines:
     return re.sub('(?m)^(?!$)', indent*' ', s)
 
+
 def _exception_traceback(exc_info):
     """
     Return a string containing a traceback message for the given
@@ -257,6 +264,7 @@ def _exception_traceback(exc_info):
     traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
     return excout.getvalue()
 
+
 # Override some StringIO methods.
 class _SpoofOut(StringIO):
     def getvalue(self):
@@ -277,6 +285,7 @@ class _SpoofOut(StringIO):
         if hasattr(self, "softspace"):
             del self.softspace
 
+
 # Worst-case linear-time ellipsis matching.
 def _ellipsis_match(want, got):
     """
@@ -327,6 +336,7 @@ def _ellipsis_match(want, got):
 
     return True
 
+
 def _comment_line(line):
     "Return a commented form of the given line"
     line = line.rstrip()
@@ -335,6 +345,7 @@ def _comment_line(line):
     else:
         return '#'
 
+
 class _OutputRedirectingPdb(pdb.Pdb):
     """
     A specialized version of the python debugger that redirects stdout
@@ -368,6 +379,7 @@ class _OutputRedirectingPdb(pdb.Pdb):
         finally:
             sys.stdout = save_stdout
 
+
 # [XX] Normalize with respect to os.path.pardir?
 def _module_relative_path(module, path):
     if not inspect.ismodule(module):
@@ -405,6 +417,7 @@ def _module_relative_path(module, path):
 ##   a string (such as an object's docstring).  The DocTest class also
 ##   includes information about where the string was extracted from.
 
+
 class Example:
     """
     A single doctest example, consisting of source code and expected
@@ -458,6 +471,7 @@ class Example:
         self.options = options
         self.exc_msg = exc_msg
 
+
 class DocTest:
     """
     A collection of doctest examples that should be run in a single
@@ -506,10 +520,10 @@ class DocTest:
         return ('<DocTest %s from %s:%s (%s)>' %
                 (self.name, self.filename, self.lineno, examples))
 
-
     # This lets us sort tests by name:
     def _cmpkey(self):
         return (self.name, self.filename, self.lineno, id(self))
+
     def __cmp__(self, other):
         if not isinstance(other, DocTest):
             return -1
@@ -1054,6 +1068,7 @@ class DocTestFinder:
 ## 5. DocTest Runner
 ######################################################################
 
+
 class DocTestRunner:
     """
     A class used to run DocTest test cases, and accumulate statistics.
@@ -1408,6 +1423,7 @@ class DocTestRunner:
     __LINECACHE_FILENAME_RE = re.compile(r'<doctest '
                                          r'(?P<name>[\w\.]+)'
                                          r'\[(?P<examplenum>\d+)\]>$')
+
     def __patched_linecache_getlines(self, filename, module_globals=None):
         m = self.__LINECACHE_FILENAME_RE.match(filename)
         if m and m.group('name') == self.test.name:
@@ -1541,6 +1557,7 @@ class DocTestRunner:
                 t = t + t2
             d[name] = f, t
 
+
 class OutputChecker:
     """
     A class used to check the whether the actual output from a doctest
@@ -1674,6 +1691,7 @@ class OutputChecker:
         else:
             return 'Expected nothing\nGot nothing\n'
 
+
 class DocTestFailure(Exception):
     """A DocTest example has failed in debugging mode.
 
@@ -1693,6 +1711,7 @@ class DocTestFailure(Exception):
     def __str__(self):
         return str(self.test)
 
+
 class UnexpectedException(Exception):
     """A DocTest example has encountered an unexpected exception
 
@@ -1712,6 +1731,7 @@ class UnexpectedException(Exception):
     def __str__(self):
         return str(self.test)
 
+
 class DebugRunner(DocTestRunner):
     r"""Run doc tests but raise an exception as soon as there is a failure.
 
@@ -1824,6 +1844,7 @@ class DebugRunner(DocTestRunner):
 # class, updated by testmod.
 master = None
 
+
 def testmod(m=None, name=None, globs=None, verbose=None,
             report=True, optionflags=0, extraglobs=None,
             raise_on_error=False, exclude_empty=False):
@@ -1928,6 +1949,7 @@ def testmod(m=None, name=None, globs=None, verbose=None,
 
     return runner.failures, runner.tries
 
+
 def testfile(filename, module_relative=True, name=None, package=None,
              globs=None, verbose=None, report=True, optionflags=0,
              extraglobs=None, raise_on_error=False, parser=DocTestParser(),
@@ -2051,6 +2073,7 @@ def testfile(filename, module_relative=True, name=None, package=None,
 
     return runner.failures, runner.tries
 
+
 def run_docstring_examples(f, globs, verbose=False, name="NoName",
                            compileflags=None, optionflags=0):
     """
@@ -2080,6 +2103,7 @@ def run_docstring_examples(f, globs, verbose=False, name="NoName",
 # This is provided only for backwards compatibility.  It's not
 # actually used in any way.
 
+
 class Tester:
     def __init__(self, mod=None, globs=None, verbose=None, optionflags=0):
 
@@ -2145,6 +2169,7 @@ class Tester:
 
 _unittest_reportflags = 0
 
+
 def set_unittest_reportflags(flags):
     """Sets the unittest option flags.
 
@@ -2328,6 +2353,7 @@ class DocTestCase(unittest.TestCase):
     def shortDescription(self):
         return "Doctest: " + self._dt_test.name
 
+
 def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
                  test_class=DocTestCase, **options):
     """
@@ -2391,6 +2417,7 @@ def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
 
     return suite
 
+
 class DocFileCase(DocTestCase):
 
     def id(self):
@@ -2405,6 +2432,7 @@ class DocFileCase(DocTestCase):
                 % (self._dt_test.name, self._dt_test.filename, err)
                 )
 
+
 def DocFileTest(path, module_relative=True, package=None,
                 globs=None, parser=DocTestParser(),
                 encoding=None, **options):
@@ -2434,6 +2462,7 @@ def DocFileTest(path, module_relative=True, package=None,
     test = parser.get_doctest(doc, globs, name, path, 0)
     return DocFileCase(test, **options)
 
+
 def DocFileSuite(*paths, **kw):
     """A unittest suite for one or more doctest files.
 
@@ -2507,6 +2536,7 @@ def DocFileSuite(*paths, **kw):
 ## 9. Debugging Support
 ######################################################################
 
+
 def script_from_examples(s):
     r"""Extract script from text with examples.
 
@@ -2587,6 +2617,7 @@ def script_from_examples(s):
     # Combine the output, and return it.
     return '\n'.join(output)
 
+
 def testsource(module, name):
     """Extract the test sources from a doctest docstring as a script.
 
@@ -2603,11 +2634,13 @@ def testsource(module, name):
     testsrc = script_from_examples(test.docstring)
     return testsrc
 
+
 def debug_src(src, pm=False, globs=None):
     """Debug a single doctest docstring, in argument `src`'"""
     testsrc = script_from_examples(src)
     debug_script(testsrc, pm, globs)
 
+
 def debug_script(src, pm=False, globs=None):
     "Debug a test script.  `src` is the script, as a string."
     import pdb
@@ -2639,6 +2672,7 @@ def debug_script(src, pm=False, globs=None):
     finally:
         os.remove(srcfilename)
 
+
 def debug(module, name, pm=False):
     """Debug a single doctest docstring.
 
@@ -2653,6 +2687,8 @@ def debug(module, name, pm=False):
 ######################################################################
 ## 10. Example Usage
 ######################################################################
+
+
 class _TestClass:
     """
     A pointless class, for sanity-checking of docstring testing.
@@ -2747,6 +2783,7 @@ __test__ = {"_TestClass": _TestClass,
             """,
            }
 
+
 def _test():
     r = unittest.TextTestRunner()
     r.run(DocTestSuite())
diff --git a/django/test/testcases.py b/django/test/testcases.py
index 3fed8c6aa7..fa044ba6ec 100644
--- a/django/test/testcases.py
+++ b/django/test/testcases.py
@@ -61,9 +61,11 @@ real_enter_transaction_management = transaction.enter_transaction_management
 real_leave_transaction_management = transaction.leave_transaction_management
 real_abort = transaction.abort
 
+
 def nop(*args, **kwargs):
     return
 
+
 def disable_transaction_methods():
     transaction.commit = nop
     transaction.rollback = nop
@@ -71,6 +73,7 @@ def disable_transaction_methods():
     transaction.leave_transaction_management = nop
     transaction.abort = nop
 
+
 def restore_transaction_methods():
     transaction.commit = real_commit
     transaction.rollback = real_rollback
diff --git a/django/utils/_os.py b/django/utils/_os.py
index 40a8e278fc..11fc5afe49 100644
--- a/django/utils/_os.py
+++ b/django/utils/_os.py
@@ -53,6 +53,7 @@ def npath(path):
         return path.encode(fs_encoding)
     return path
 
+
 def safe_join(base, *paths):
     """
     Joins one or more path components to the base path component intelligently.
diff --git a/django/utils/autoreload.py b/django/utils/autoreload.py
index ca162d18d0..00f7ce160a 100644
--- a/django/utils/autoreload.py
+++ b/django/utils/autoreload.py
@@ -119,6 +119,7 @@ def gen_filenames():
         if os.path.exists(filename):
             yield filename
 
+
 def inotify_code_changed():
     """
     Checks for changed code using inotify. After being called
@@ -149,6 +150,7 @@ def inotify_code_changed():
     # If we are here the code must have changed.
     return True
 
+
 def kqueue_code_changed():
     """
     Checks for changed code using kqueue. After being called
@@ -193,6 +195,7 @@ def kqueue_code_changed():
 
     return True
 
+
 def code_changed():
     global _mtimes, _win
     for filename in gen_filenames():
@@ -212,6 +215,7 @@ def code_changed():
             return True
     return False
 
+
 def check_errors(fn):
     def wrapper(*args, **kwargs):
         try:
@@ -233,6 +237,7 @@ def check_errors(fn):
 
     return wrapper
 
+
 def ensure_echo_on():
     if termios:
         fd = sys.stdin
@@ -248,6 +253,7 @@ def ensure_echo_on():
                 if old_handler is not None:
                     signal.signal(signal.SIGTTOU, old_handler)
 
+
 def reloader_thread():
     ensure_echo_on()
     if USE_INOTIFY:
@@ -273,6 +279,7 @@ def restart_with_reloader():
         if exit_code != 3:
             return exit_code
 
+
 def python_reloader(main_func, args, kwargs):
     if os.environ.get("RUN_MAIN") == "true":
         thread.start_new_thread(main_func, args, kwargs)
@@ -290,6 +297,7 @@ def python_reloader(main_func, args, kwargs):
         except KeyboardInterrupt:
             pass
 
+
 def jython_reloader(main_func, args, kwargs):
     from _systemrestart import SystemRestart
     thread.start_new_thread(main_func, args)
diff --git a/django/utils/cache.py b/django/utils/cache.py
index 0d664afdf4..7e38f7b021 100644
--- a/django/utils/cache.py
+++ b/django/utils/cache.py
@@ -31,6 +31,7 @@ from django.utils.translation import get_language
 
 cc_delim_re = re.compile(r'\s*,\s*')
 
+
 def patch_cache_control(response, **kwargs):
     """
     This function patches the Cache-Control header by adding all
@@ -79,6 +80,7 @@ def patch_cache_control(response, **kwargs):
     cc = ', '.join(dictvalue(el) for el in cc.items())
     response['Cache-Control'] = cc
 
+
 def get_max_age(response):
     """
     Returns the max-age from the response Cache-Control header as an integer
@@ -94,11 +96,13 @@ def get_max_age(response):
         except (ValueError, TypeError):
             pass
 
+
 def _set_response_etag(response):
     if not response.streaming:
         response['ETag'] = '"%s"' % hashlib.md5(response.content).hexdigest()
     return response
 
+
 def patch_response_headers(response, cache_timeout=None):
     """
     Adds some useful headers to the given HttpResponse object:
@@ -124,12 +128,14 @@ def patch_response_headers(response, cache_timeout=None):
         response['Expires'] = http_date(time.time() + cache_timeout)
     patch_cache_control(response, max_age=cache_timeout)
 
+
 def add_never_cache_headers(response):
     """
     Adds headers to a response to indicate that a page should never be cached.
     """
     patch_response_headers(response, cache_timeout=-1)
 
+
 def patch_vary_headers(response, newheaders):
     """
     Adds (or updates) the "Vary" header in the given HttpResponse object.
@@ -149,6 +155,7 @@ def patch_vary_headers(response, newheaders):
                           if newheader.lower() not in existing_headers]
     response['Vary'] = ', '.join(vary_headers + additional_headers)
 
+
 def has_vary_header(response, header_query):
     """
     Checks to see if the response has a given header name in its Vary header.
@@ -159,6 +166,7 @@ def has_vary_header(response, header_query):
     existing_headers = set(header.lower() for header in vary_headers)
     return header_query.lower() in existing_headers
 
+
 def _i18n_cache_key_suffix(request, cache_key):
     """If necessary, adds the current locale or time zone to the cache key."""
     if settings.USE_I18N or settings.USE_L10N:
@@ -175,6 +183,7 @@ def _i18n_cache_key_suffix(request, cache_key):
         cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
     return cache_key
 
+
 def _generate_cache_key(request, method, headerlist, key_prefix):
     """Returns a cache key from the headers given in the header list."""
     ctx = hashlib.md5()
@@ -187,6 +196,7 @@ def _generate_cache_key(request, method, headerlist, key_prefix):
         key_prefix, method, path.hexdigest(), ctx.hexdigest())
     return _i18n_cache_key_suffix(request, cache_key)
 
+
 def _generate_cache_header_key(key_prefix, request):
     """Returns a cache key for the header cache."""
     path = hashlib.md5(force_bytes(iri_to_uri(request.get_full_path())))
@@ -194,6 +204,7 @@ def _generate_cache_header_key(key_prefix, request):
         key_prefix, path.hexdigest())
     return _i18n_cache_key_suffix(request, cache_key)
 
+
 def get_cache_key(request, key_prefix=None, method='GET', cache=None):
     """
     Returns a cache key based on the request path and query. It can be used
@@ -215,6 +226,7 @@ def get_cache_key(request, key_prefix=None, method='GET', cache=None):
     else:
         return None
 
+
 def learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None):
     """
     Learns what headers to take into account for some request path from the
diff --git a/django/utils/datastructures.py b/django/utils/datastructures.py
index e5fe4a776a..49855dd33b 100644
--- a/django/utils/datastructures.py
+++ b/django/utils/datastructures.py
@@ -3,6 +3,7 @@ import warnings
 from collections import OrderedDict
 from django.utils import six
 
+
 class MergeDict(object):
     """
     A simple class for creating new "virtual" dictionaries that actually look
@@ -117,6 +118,7 @@ class MergeDict(object):
         dictreprs = ', '.join(repr(d) for d in self.dicts)
         return '%s(%s)' % (self.__class__.__name__, dictreprs)
 
+
 class SortedDict(dict):
     """
     A dictionary that keeps its keys in the order in which they're inserted.
@@ -239,6 +241,7 @@ class SortedDict(dict):
         super(SortedDict, self).clear()
         self.keyOrder = []
 
+
 class OrderedSet(object):
     """
     A set which keeps the ordering of the inserted items.
@@ -269,9 +272,11 @@ class OrderedSet(object):
     def __nonzero__(self):
         return bool(self.dict)
 
+
 class MultiValueDictKeyError(KeyError):
     pass
 
+
 class MultiValueDict(dict):
     """
     A subclass of dictionary customized to handle multiple values for the
@@ -504,6 +509,7 @@ class ImmutableList(tuple):
     sort = complain
     reverse = complain
 
+
 class DictWrapper(dict):
     """
     Wraps accesses to a dictionary so that certain values (those starting with
diff --git a/django/utils/dateformat.py b/django/utils/dateformat.py
index 27413a2e67..78483f2d4c 100644
--- a/django/utils/dateformat.py
+++ b/django/utils/dateformat.py
@@ -26,6 +26,7 @@ from django.utils.timezone import get_default_timezone, is_aware, is_naive
 re_formatchars = re.compile(r'(?<!\\)([aAbBcdDeEfFgGhHiIjlLmMnNoOPrsStTUuwWyYzZ])')
 re_escaped = re.compile(r'\\(.)')
 
+
 class Formatter(object):
     def format(self, formatstr):
         pieces = []
@@ -36,6 +37,7 @@ class Formatter(object):
                 pieces.append(re_escaped.sub(r'\1', piece))
         return ''.join(pieces)
 
+
 class TimeFormat(Formatter):
 
     def __init__(self, obj):
diff --git a/django/utils/dateparse.py b/django/utils/dateparse.py
index 1e2cad7d01..f2c079023f 100644
--- a/django/utils/dateparse.py
+++ b/django/utils/dateparse.py
@@ -39,6 +39,7 @@ def parse_date(value):
         kw = dict((k, int(v)) for k, v in six.iteritems(match.groupdict()))
         return datetime.date(**kw)
 
+
 def parse_time(value):
     """Parses a string and return a datetime.time.
 
@@ -56,6 +57,7 @@ def parse_time(value):
         kw = dict((k, int(v)) for k, v in six.iteritems(kw) if v is not None)
         return datetime.time(**kw)
 
+
 def parse_datetime(value):
     """Parses a string and return a datetime.datetime.
 
diff --git a/django/utils/datetime_safe.py b/django/utils/datetime_safe.py
index 6aa32f30bf..a584011db5 100644
--- a/django/utils/datetime_safe.py
+++ b/django/utils/datetime_safe.py
@@ -30,10 +30,12 @@ class datetime(real_datetime):
     def date(self):
         return date(self.year, self.month, self.day)
 
+
 def new_date(d):
     "Generate a safe date from a datetime.date object."
     return date(d.year, d.month, d.day)
 
+
 def new_datetime(d):
     """
     Generate a safe datetime from a datetime.date or datetime.datetime object.
@@ -47,6 +49,7 @@ def new_datetime(d):
 # Allowed if there's an even number of "%"s because they are escaped.
 _illegal_formatting = re.compile(r"((^|[^%])(%%)*%[sy])")
 
+
 def _findall(text, substr):
     # Also finds overlaps
     sites = []
@@ -59,6 +62,7 @@ def _findall(text, substr):
         i = j + 1
     return sites
 
+
 def strftime(dt, fmt):
     if dt.year >= 1900:
         return super(type(dt), dt).strftime(fmt)
diff --git a/django/utils/dictconfig.py b/django/utils/dictconfig.py
index 773b703497..e79dc041ef 100644
--- a/django/utils/dictconfig.py
+++ b/django/utils/dictconfig.py
@@ -32,6 +32,7 @@ from django.utils import six
 
 IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I)
 
+
 def valid_ident(s):
     m = IDENTIFIER.match(s)
     if not m:
@@ -65,6 +66,7 @@ except ImportError:
 # Each wrapper should have a configurator attribute holding the actual
 # configurator to use for conversion.
 
+
 class ConvertingDict(dict):
     """A converting dictionary wrapper."""
 
@@ -102,6 +104,7 @@ class ConvertingDict(dict):
                 result.key = key
         return result
 
+
 class ConvertingList(list):
     """A converting list wrapper."""
     def __getitem__(self, key):
@@ -125,6 +128,7 @@ class ConvertingList(list):
                 result.parent = self
         return result
 
+
 class ConvertingTuple(tuple):
     """A converting tuple wrapper."""
     def __getitem__(self, key):
@@ -137,6 +141,7 @@ class ConvertingTuple(tuple):
                 result.key = key
         return result
 
+
 class BaseConfigurator(object):
     """
     The configurator base class which defines some useful defaults.
@@ -270,6 +275,7 @@ class BaseConfigurator(object):
             value = tuple(value)
         return value
 
+
 class DictConfigurator(BaseConfigurator):
     """
     Configure logging using a dictionary-like object to describe the
@@ -555,6 +561,7 @@ class DictConfigurator(BaseConfigurator):
 
 dictConfigClass = DictConfigurator
 
+
 def dictConfig(config):
     """Configure logging using a dictionary."""
     dictConfigClass(config).configure()
diff --git a/django/utils/encoding.py b/django/utils/encoding.py
index ad4473df6a..ee67df30ea 100644
--- a/django/utils/encoding.py
+++ b/django/utils/encoding.py
@@ -38,6 +38,7 @@ def python_2_unicode_compatible(klass):
         klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
     return klass
 
+
 def smart_text(s, encoding='utf-8', strings_only=False, errors='strict'):
     """
     Returns a text object representing 's' -- unicode on Python 2 and str on
@@ -50,6 +51,7 @@ def smart_text(s, encoding='utf-8', strings_only=False, errors='strict'):
         return s
     return force_text(s, encoding, strings_only, errors)
 
+
 def is_protected_type(obj):
     """Determine if the object instance is of a protected type.
 
@@ -59,6 +61,7 @@ def is_protected_type(obj):
     return isinstance(obj, six.integer_types + (type(None), float, Decimal,
         datetime.datetime, datetime.date, datetime.time))
 
+
 def force_text(s, encoding='utf-8', strings_only=False, errors='strict'):
     """
     Similar to smart_text, except that lazy instances are resolved to
@@ -100,6 +103,7 @@ def force_text(s, encoding='utf-8', strings_only=False, errors='strict'):
                     errors) for arg in s])
     return s
 
+
 def smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
     """
     Returns a bytestring version of 's', encoded as specified in 'encoding'.
@@ -168,6 +172,7 @@ force_str.__doc__ = """
 Apply force_text in Python 3 and force_bytes in Python 2.
 """
 
+
 def iri_to_uri(iri):
     """
     Convert an Internationalized Resource Identifier (IRI) portion to a URI
@@ -195,6 +200,7 @@ def iri_to_uri(iri):
         return iri
     return quote(force_bytes(iri), safe=b"/#%[]=:;$&()+,!?*@'~")
 
+
 def filepath_to_uri(path):
     """Convert a file system path to a URI portion that is suitable for
     inclusion in a URL.
@@ -214,6 +220,7 @@ def filepath_to_uri(path):
     # some flexibility for hardcoding separators.
     return quote(force_bytes(path).replace(b"\\", b"/"), safe=b"/~!*()'")
 
+
 def get_system_encoding():
     """
     The encoding of the default system locale but falls back to the given
diff --git a/django/utils/feedgenerator.py b/django/utils/feedgenerator.py
index 416234521f..00d982025a 100644
--- a/django/utils/feedgenerator.py
+++ b/django/utils/feedgenerator.py
@@ -54,6 +54,7 @@ def rfc2822_date(date):
     else:
         return time_str + '-0000'
 
+
 def rfc3339_date(date):
     # Support datetime objects older than 1900
     date = datetime_safe.new_datetime(date)
@@ -68,6 +69,7 @@ def rfc3339_date(date):
     else:
         return time_str + 'Z'
 
+
 def get_tag_uri(url, date):
     """
     Creates a TagURI.
@@ -80,6 +82,7 @@ def get_tag_uri(url, date):
         d = ',%s' % datetime_safe.new_datetime(date).strftime('%Y-%m-%d')
     return 'tag:%s%s:%s/%s' % (bits.hostname, d, bits.path, bits.fragment)
 
+
 class SyndicationFeed(object):
     "Base class for all syndication feeds. Subclasses should provide write()"
     def __init__(self, title, link, description, language=None, author_email=None,
@@ -205,6 +208,7 @@ class SyndicationFeed(object):
 
         return latest_date or datetime.datetime.now()
 
+
 class Enclosure(object):
     "Represents an RSS enclosure"
     def __init__(self, url, length, mime_type):
@@ -212,6 +216,7 @@ class Enclosure(object):
         self.length, self.mime_type = length, mime_type
         self.url = iri_to_uri(url)
 
+
 class RssFeed(SyndicationFeed):
     mime_type = 'application/rss+xml; charset=utf-8'
 
@@ -255,6 +260,7 @@ class RssFeed(SyndicationFeed):
     def endChannelElement(self, handler):
         handler.endElement("channel")
 
+
 class RssUserland091Feed(RssFeed):
     _version = "0.91"
 
@@ -264,6 +270,7 @@ class RssUserland091Feed(RssFeed):
         if item['description'] is not None:
             handler.addQuickElement("description", item['description'])
 
+
 class Rss201rev2Feed(RssFeed):
     # Spec: http://blogs.law.harvard.edu/tech/rss
     _version = "2.0"
@@ -306,6 +313,7 @@ class Rss201rev2Feed(RssFeed):
         for cat in item['categories']:
             handler.addQuickElement("category", cat)
 
+
 class Atom1Feed(SyndicationFeed):
     # Spec: http://atompub.org/2005/07/11/draft-ietf-atompub-format-10.html
     mime_type = 'application/atom+xml; charset=utf-8'
diff --git a/django/utils/formats.py b/django/utils/formats.py
index 0c59e2c04a..fc68179f3a 100644
--- a/django/utils/formats.py
+++ b/django/utils/formats.py
@@ -30,6 +30,7 @@ ISO_INPUT_FORMATS = {
     ),
 }
 
+
 def reset_format_cache():
     """Clear any cached formats.
 
@@ -40,6 +41,7 @@ def reset_format_cache():
     _format_cache = {}
     _format_modules_cache = {}
 
+
 def iter_format_modules(lang, format_module_path=None):
     """
     Does the heavy lifting of finding format modules.
@@ -60,6 +62,7 @@ def iter_format_modules(lang, format_module_path=None):
                 except ImportError:
                     pass
 
+
 def get_format_modules(lang=None, reverse=False):
     """
     Returns a list of the format modules found
@@ -71,6 +74,7 @@ def get_format_modules(lang=None, reverse=False):
         return list(reversed(modules))
     return modules
 
+
 def get_format(format_type, lang=None, use_l10n=None):
     """
     For a specific format type, returns the format for the current
@@ -110,6 +114,7 @@ def get_format(format_type, lang=None, use_l10n=None):
 
 get_format_lazy = lazy(get_format, six.text_type, list, tuple)
 
+
 def date_format(value, format=None, use_l10n=None):
     """
     Formats a datetime.date or datetime.datetime object using a
@@ -120,6 +125,7 @@ def date_format(value, format=None, use_l10n=None):
     """
     return dateformat.format(value, get_format(format or 'DATE_FORMAT', use_l10n=use_l10n))
 
+
 def time_format(value, format=None, use_l10n=None):
     """
     Formats a datetime.time object using a localizable format
@@ -129,6 +135,7 @@ def time_format(value, format=None, use_l10n=None):
     """
     return dateformat.time_format(value, get_format(format or 'TIME_FORMAT', use_l10n=use_l10n))
 
+
 def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False):
     """
     Formats a numeric value using localization settings
@@ -149,6 +156,7 @@ def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False):
         force_grouping=force_grouping
     )
 
+
 def localize(value, use_l10n=None):
     """
     Checks if value is a localizable type (date, number...) and returns it
@@ -170,6 +178,7 @@ def localize(value, use_l10n=None):
     else:
         return value
 
+
 def localize_input(value, default=None):
     """
     Checks if an input value is a localizable type and returns it
@@ -190,6 +199,7 @@ def localize_input(value, default=None):
         return value.strftime(format)
     return value
 
+
 def sanitize_separators(value):
     """
     Sanitizes a value according to the current decimal and
diff --git a/django/utils/html.py b/django/utils/html.py
index 6d04ae5205..3ad549de19 100644
--- a/django/utils/html.py
+++ b/django/utils/html.py
@@ -72,6 +72,7 @@ def conditional_escape(text):
     else:
         return escape(text)
 
+
 def format_html(format_string, *args, **kwargs):
     """
     Similar to str.format, but passes all arguments through conditional_escape,
@@ -83,6 +84,7 @@ def format_html(format_string, *args, **kwargs):
                         six.iteritems(kwargs))
     return mark_safe(format_string.format(*args_safe, **kwargs_safe))
 
+
 def format_html_join(sep, format_string, args_generator):
     """
     A wrapper of format_html, for the common case of a group of arguments that
@@ -133,6 +135,7 @@ class MLStripper(HTMLParser):
     def get_data(self):
         return ''.join(self.fed)
 
+
 def strip_tags(value):
     """Returns the given HTML with all tags stripped."""
     s = MLStripper()
@@ -145,6 +148,7 @@ def strip_tags(value):
         return s.get_data()
 strip_tags = allow_lazy(strip_tags)
 
+
 def remove_tags(html, tags):
     """Returns the given HTML with given tags removed."""
     tags = [re.escape(tag) for tag in tags.split()]
@@ -156,21 +160,25 @@ def remove_tags(html, tags):
     return html
 remove_tags = allow_lazy(remove_tags, six.text_type)
 
+
 def strip_spaces_between_tags(value):
     """Returns the given HTML with spaces between tags removed."""
     return re.sub(r'>\s+<', '><', force_text(value))
 strip_spaces_between_tags = allow_lazy(strip_spaces_between_tags, six.text_type)
 
+
 def strip_entities(value):
     """Returns the given HTML with all entities (&something;) stripped."""
     return re.sub(r'&(?:\w+|#\d+);', '', force_text(value))
 strip_entities = allow_lazy(strip_entities, six.text_type)
 
+
 def fix_ampersands(value):
     """Returns the given HTML with all unencoded ampersands encoded correctly."""
     return unencoded_ampersands_re.sub('&amp;', force_text(value))
 fix_ampersands = allow_lazy(fix_ampersands, six.text_type)
 
+
 def smart_urlquote(url):
     "Quotes a URL if it isn't already quoted."
     # Handle IDN before quoting.
@@ -192,6 +200,7 @@ def smart_urlquote(url):
 
     return force_text(url)
 
+
 def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
     """
     Converts any URLs in text into clickable links.
@@ -269,6 +278,7 @@ def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
     return ''.join(words)
 urlize = allow_lazy(urlize, six.text_type)
 
+
 def clean_html(text):
     """
     Clean the given HTML.  Specifically, do the following:
@@ -304,6 +314,7 @@ def clean_html(text):
     return text
 clean_html = allow_lazy(clean_html, six.text_type)
 
+
 def avoid_wrapping(value):
     """
     Avoid text wrapping in the middle of a phrase by adding non-breaking
diff --git a/django/utils/http.py b/django/utils/http.py
index 413ac72a08..e3365776f3 100644
--- a/django/utils/http.py
+++ b/django/utils/http.py
@@ -30,6 +30,7 @@ RFC1123_DATE = re.compile(r'^\w{3}, %s %s %s %s GMT$' % (__D, __M, __Y, __T))
 RFC850_DATE = re.compile(r'^\w{6,9}, %s-%s-%s %s GMT$' % (__D, __M, __Y2, __T))
 ASCTIME_DATE = re.compile(r'^\w{3} %s %s %s %s$' % (__M, __D2, __T, __Y))
 
+
 def urlquote(url, safe='/'):
     """
     A version of Python's urllib.quote() function that can operate on unicode
@@ -40,6 +41,7 @@ def urlquote(url, safe='/'):
     return force_text(quote(force_str(url), force_str(safe)))
 urlquote = allow_lazy(urlquote, six.text_type)
 
+
 def urlquote_plus(url, safe=''):
     """
     A version of Python's urllib.quote_plus() function that can operate on
@@ -50,6 +52,7 @@ def urlquote_plus(url, safe=''):
     return force_text(quote_plus(force_str(url), force_str(safe)))
 urlquote_plus = allow_lazy(urlquote_plus, six.text_type)
 
+
 def urlunquote(quoted_url):
     """
     A wrapper for Python's urllib.unquote() function that can operate on
@@ -58,6 +61,7 @@ def urlunquote(quoted_url):
     return force_text(unquote(force_str(quoted_url)))
 urlunquote = allow_lazy(urlunquote, six.text_type)
 
+
 def urlunquote_plus(quoted_url):
     """
     A wrapper for Python's urllib.unquote_plus() function that can operate on
@@ -66,6 +70,7 @@ def urlunquote_plus(quoted_url):
     return force_text(unquote_plus(force_str(quoted_url)))
 urlunquote_plus = allow_lazy(urlunquote_plus, six.text_type)
 
+
 def urlencode(query, doseq=0):
     """
     A version of Python's urllib.urlencode() function that can operate on
@@ -82,6 +87,7 @@ def urlencode(query, doseq=0):
             for k, v in query],
         doseq)
 
+
 def cookie_date(epoch_seconds=None):
     """
     Formats the time to ensure compatibility with Netscape's cookie standard.
@@ -95,6 +101,7 @@ def cookie_date(epoch_seconds=None):
     rfcdate = formatdate(epoch_seconds)
     return '%s-%s-%s GMT' % (rfcdate[:7], rfcdate[8:11], rfcdate[12:25])
 
+
 def http_date(epoch_seconds=None):
     """
     Formats the time to match the RFC1123 date format as specified by HTTP
@@ -108,6 +115,7 @@ def http_date(epoch_seconds=None):
     """
     return formatdate(epoch_seconds, usegmt=True)
 
+
 def parse_http_date(date):
     """
     Parses a date format as specified by HTTP RFC2616 section 3.3.1.
@@ -143,6 +151,7 @@ def parse_http_date(date):
     except Exception:
         six.reraise(ValueError, ValueError("%r is not a valid date" % date), sys.exc_info()[2])
 
+
 def parse_http_date_safe(date):
     """
     Same as parse_http_date, but returns None if the input is invalid.
@@ -152,6 +161,7 @@ def parse_http_date_safe(date):
     except Exception:
         pass
 
+
 # Base 36 functions: useful for generating compact URLs
 
 def base36_to_int(s):
@@ -171,6 +181,7 @@ def base36_to_int(s):
         raise ValueError("Base36 input too large")
     return value
 
+
 def int_to_base36(i):
     """
     Converts an integer to a base36 string
@@ -199,6 +210,7 @@ def int_to_base36(i):
         factor -= 1
     return ''.join(base36)
 
+
 def urlsafe_base64_encode(s):
     """
     Encodes a bytestring in base64 for use in URLs, stripping any trailing
@@ -206,6 +218,7 @@ def urlsafe_base64_encode(s):
     """
     return base64.urlsafe_b64encode(s).rstrip(b'\n=')
 
+
 def urlsafe_base64_decode(s):
     """
     Decodes a base64 encoded string, adding back any trailing equal signs that
@@ -217,6 +230,7 @@ def urlsafe_base64_decode(s):
     except (LookupError, BinasciiError) as e:
         raise ValueError(e)
 
+
 def parse_etags(etag_str):
     """
     Parses a string with one or several etags passed in If-None-Match and
@@ -230,12 +244,14 @@ def parse_etags(etag_str):
     etags = [e.encode('ascii').decode('unicode_escape') for e in etags]
     return etags
 
+
 def quote_etag(etag):
     """
     Wraps a string in double quotes escaping contents as necessary.
     """
     return '"%s"' % etag.replace('\\', '\\\\').replace('"', '\\"')
 
+
 def same_origin(url1, url2):
     """
     Checks if two URLs are 'same-origin'
@@ -246,6 +262,7 @@ def same_origin(url1, url2):
     except ValueError:
         return False
 
+
 def is_safe_url(url, host=None):
     """
     Return ``True`` if the url is a safe redirection (i.e. it doesn't point to
diff --git a/django/utils/regex_helper.py b/django/utils/regex_helper.py
index c8390cc7eb..199b4ea87d 100644
--- a/django/utils/regex_helper.py
+++ b/django/utils/regex_helper.py
@@ -202,6 +202,7 @@ def normalize(pattern):
 
     return list(zip(*flatten_result(result)))
 
+
 def next_char(input_iter):
     """
     An iterator that yields the next character from "pattern_iter", respecting
@@ -222,6 +223,7 @@ def next_char(input_iter):
             continue
         yield representative, True
 
+
 def walk_to_end(ch, input_iter):
     """
     The iterator is currently inside a capturing group. We want to walk to the
@@ -242,6 +244,7 @@ def walk_to_end(ch, input_iter):
                 return
             nesting -= 1
 
+
 def get_quantifier(ch, input_iter):
     """
     Parse a quantifier from the input, where "ch" is the first character in the
@@ -278,6 +281,7 @@ def get_quantifier(ch, input_iter):
         ch = None
     return int(values[0]), ch
 
+
 def contains(source, inst):
     """
     Returns True if the "source" contains an instance of "inst". False,
@@ -291,6 +295,7 @@ def contains(source, inst):
                 return True
     return False
 
+
 def flatten_result(source):
     """
     Turns the given source sequence into a list of reg-exp possibilities and
diff --git a/django/utils/safestring.py b/django/utils/safestring.py
index c44726090f..097d31dd0f 100644
--- a/django/utils/safestring.py
+++ b/django/utils/safestring.py
@@ -32,6 +32,7 @@ else:
     # backwards compatibility for Python 2
     EscapeUnicode = EscapeText
 
+
 class SafeData(object):
     def __html__(self):
         """
@@ -41,6 +42,7 @@ class SafeData(object):
         """
         return self
 
+
 class SafeBytes(bytes, SafeData):
     """
     A bytes subclass that has been specifically marked as "safe" (requires no
@@ -75,6 +77,7 @@ class SafeBytes(bytes, SafeData):
 
     decode = curry(_proxy_method, method=bytes.decode)
 
+
 class SafeText(six.text_type, SafeData):
     """
     A unicode (Python 2) / str (Python 3) subclass that has been specifically
@@ -114,6 +117,7 @@ else:
     # backwards compatibility for Python 2
     SafeUnicode = SafeText
 
+
 def mark_safe(s):
     """
     Explicitly mark a string as safe for (HTML) output purposes. The returned
@@ -129,6 +133,7 @@ def mark_safe(s):
         return SafeText(s)
     return SafeString(str(s))
 
+
 def mark_for_escaping(s):
     """
     Explicitly mark a string as requiring HTML escaping upon output. Has no
diff --git a/django/utils/six.py b/django/utils/six.py
index 7abefb2258..b9d311499b 100644
--- a/django/utils/six.py
+++ b/django/utils/six.py
@@ -428,14 +428,17 @@ def iterkeys(d, **kw):
     """Return an iterator over the keys of a dictionary."""
     return iter(getattr(d, _iterkeys)(**kw))
 
+
 def itervalues(d, **kw):
     """Return an iterator over the values of a dictionary."""
     return iter(getattr(d, _itervalues)(**kw))
 
+
 def iteritems(d, **kw):
     """Return an iterator over the (key, value) pairs of a dictionary."""
     return iter(getattr(d, _iteritems)(**kw))
 
+
 def iterlists(d, **kw):
     """Return an iterator over the (key, [values]) pairs of a dictionary."""
     return iter(getattr(d, _iterlists)(**kw))
@@ -565,6 +568,7 @@ def with_metaclass(meta, *bases):
     """Create a base class with a metaclass."""
     return meta("NewBase", bases, {})
 
+
 def add_metaclass(metaclass):
     """Class decorator for creating a class with a metaclass."""
     def wrapper(cls):
diff --git a/django/utils/text.py b/django/utils/text.py
index 8f20e8ed88..bb05afefc4 100644
--- a/django/utils/text.py
+++ b/django/utils/text.py
@@ -209,6 +209,7 @@ class Truncator(SimpleLazyObject):
         # Return string
         return out
 
+
 def get_valid_filename(s):
     """
     Returns the given string converted to a string that can be used for a clean
@@ -222,6 +223,7 @@ def get_valid_filename(s):
     return re.sub(r'(?u)[^-\w.]', '', s)
 get_valid_filename = allow_lazy(get_valid_filename, six.text_type)
 
+
 def get_text_list(list_, last_word=ugettext_lazy('or')):
     """
     >>> get_text_list(['a', 'b', 'c', 'd'])
@@ -245,10 +247,12 @@ def get_text_list(list_, last_word=ugettext_lazy('or')):
         force_text(last_word), force_text(list_[-1]))
 get_text_list = allow_lazy(get_text_list, six.text_type)
 
+
 def normalize_newlines(text):
     return force_text(re.sub(r'\r\n|\r|\n', '\n', text))
 normalize_newlines = allow_lazy(normalize_newlines, six.text_type)
 
+
 def recapitalize(text):
     "Recapitalizes text, placing caps after end-of-sentence punctuation."
     text = force_text(text).lower()
@@ -257,6 +261,7 @@ def recapitalize(text):
     return text
 recapitalize = allow_lazy(recapitalize)
 
+
 def phone2numeric(phone):
     "Converts a phone number with letters into its numeric equivalent."
     char2number = {'a': '2', 'b': '2', 'c': '2', 'd': '3', 'e': '3', 'f': '3',
@@ -267,6 +272,7 @@ def phone2numeric(phone):
     return ''.join(char2number.get(c, c) for c in phone.lower())
 phone2numeric = allow_lazy(phone2numeric)
 
+
 # From http://www.xhaus.com/alan/python/httpcomp.html#gzip
 # Used with permission.
 def compress_string(s):
@@ -276,6 +282,7 @@ def compress_string(s):
     zfile.close()
     return zbuf.getvalue()
 
+
 class StreamingBuffer(object):
     def __init__(self):
         self.vals = []
@@ -294,6 +301,7 @@ class StreamingBuffer(object):
     def close(self):
         return
 
+
 # Like compress_string, but for iterators of strings.
 def compress_sequence(sequence):
     buf = StreamingBuffer()
@@ -309,6 +317,7 @@ def compress_sequence(sequence):
 
 ustring_re = re.compile("([\u0080-\uffff])")
 
+
 def javascript_quote(s, quote_double_quotes=False):
 
     def fix(match):
@@ -340,6 +349,7 @@ smart_split_re = re.compile(r"""
     ) | \S+)
 """, re.VERBOSE)
 
+
 def smart_split(text):
     r"""
     Generator that splits a string by spaces, leaving quoted phrases together.
@@ -359,6 +369,7 @@ def smart_split(text):
     for bit in smart_split_re.finditer(text):
         yield bit.group(0)
 
+
 def _replace_entity(match):
     text = match.group(1)
     if text[0] == '#':
@@ -379,10 +390,12 @@ def _replace_entity(match):
 
 _entity_re = re.compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));")
 
+
 def unescape_entities(text):
     return _entity_re.sub(_replace_entity, text)
 unescape_entities = allow_lazy(unescape_entities, six.text_type)
 
+
 def unescape_string_literal(s):
     r"""
     Convert quoted string literals to unquoted strings with escaped quotes and
@@ -403,6 +416,7 @@ def unescape_string_literal(s):
     return s[1:-1].replace(r'\%s' % quote, quote).replace(r'\\', '\\')
 unescape_string_literal = allow_lazy(unescape_string_literal)
 
+
 def slugify(value):
     """
     Converts to lowercase, removes non-word characters (alphanumerics and
diff --git a/django/utils/timesince.py b/django/utils/timesince.py
index 8fb0f64e09..b39ab203a7 100644
--- a/django/utils/timesince.py
+++ b/django/utils/timesince.py
@@ -6,6 +6,7 @@ from django.utils.html import avoid_wrapping
 from django.utils.timezone import is_aware, utc
 from django.utils.translation import ugettext, ungettext_lazy
 
+
 def timesince(d, now=None, reversed=False):
     """
     Takes two datetime objects and returns the time between d and now
@@ -56,6 +57,7 @@ def timesince(d, now=None, reversed=False):
             result += ugettext(', ') + avoid_wrapping(name2 % count2)
     return result
 
+
 def timeuntil(d, now=None):
     """
     Like timesince, but returns a string measuring the time until
diff --git a/django/utils/timezone.py b/django/utils/timezone.py
index 951c3efcf9..eec554a1ef 100644
--- a/django/utils/timezone.py
+++ b/django/utils/timezone.py
@@ -29,6 +29,7 @@ __all__ = [
 
 ZERO = timedelta(0)
 
+
 class UTC(tzinfo):
     """
     UTC implementation taken from Python's docs.
@@ -48,6 +49,7 @@ class UTC(tzinfo):
     def dst(self, dt):
         return ZERO
 
+
 class FixedOffset(tzinfo):
     """
     Fixed offset in minutes east from UTC. Taken from Python's docs.
@@ -72,6 +74,7 @@ class FixedOffset(tzinfo):
     def dst(self, dt):
         return ZERO
 
+
 class ReferenceLocalTimezone(tzinfo):
     """
     Local time. Taken from Python's docs.
@@ -118,6 +121,7 @@ class ReferenceLocalTimezone(tzinfo):
         tt = _time.localtime(stamp)
         return tt.tm_isdst > 0
 
+
 class LocalTimezone(ReferenceLocalTimezone):
     """
     Slightly improved local time implementation focusing on correctness.
@@ -143,6 +147,7 @@ class LocalTimezone(ReferenceLocalTimezone):
 utc = pytz.utc if pytz else UTC()
 """UTC time zone as a tzinfo instance."""
 
+
 def get_fixed_timezone(offset):
     """
     Returns a tzinfo instance with a fixed offset from UTC.
@@ -158,6 +163,7 @@ def get_fixed_timezone(offset):
 # wrap the expression in a function and cache the result.
 _localtime = None
 
+
 def get_default_timezone():
     """
     Returns the default time zone as a tzinfo instance.
@@ -173,6 +179,7 @@ def get_default_timezone():
             _localtime = LocalTimezone()
     return _localtime
 
+
 # This function exists for consistency with get_current_timezone_name
 def get_default_timezone_name():
     """
@@ -182,18 +189,21 @@ def get_default_timezone_name():
 
 _active = local()
 
+
 def get_current_timezone():
     """
     Returns the currently active time zone as a tzinfo instance.
     """
     return getattr(_active, "value", get_default_timezone())
 
+
 def get_current_timezone_name():
     """
     Returns the name of the currently active time zone.
     """
     return _get_timezone_name(get_current_timezone())
 
+
 def _get_timezone_name(timezone):
     """
     Returns the name of ``timezone``.
@@ -210,6 +220,7 @@ def _get_timezone_name(timezone):
 # These functions don't change os.environ['TZ'] and call time.tzset()
 # because it isn't thread safe.
 
+
 def activate(timezone):
     """
     Sets the time zone for the current thread.
@@ -224,6 +235,7 @@ def activate(timezone):
     else:
         raise ValueError("Invalid timezone: %r" % timezone)
 
+
 def deactivate():
     """
     Unsets the time zone for the current thread.
@@ -233,6 +245,7 @@ def deactivate():
     if hasattr(_active, "value"):
         del _active.value
 
+
 class override(object):
     """
     Temporarily set the time zone for the current thread.
@@ -297,6 +310,7 @@ def localtime(value, timezone=None):
         value = timezone.normalize(value)
     return value
 
+
 def now():
     """
     Returns an aware or naive datetime.datetime, depending on settings.USE_TZ.
@@ -307,6 +321,7 @@ def now():
     else:
         return datetime.now()
 
+
 # By design, these four functions don't perform any checks on their arguments.
 # The caller should ensure that they don't receive an invalid value like None.
 
@@ -319,6 +334,7 @@ def is_aware(value):
     """
     return value.tzinfo is not None and value.tzinfo.utcoffset(value) is not None
 
+
 def is_naive(value):
     """
     Determines if a given datetime.datetime is naive.
@@ -328,6 +344,7 @@ def is_naive(value):
     """
     return value.tzinfo is None or value.tzinfo.utcoffset(value) is None
 
+
 def make_aware(value, timezone):
     """
     Makes a naive datetime.datetime in a given time zone aware.
@@ -339,6 +356,7 @@ def make_aware(value, timezone):
         # may be wrong around DST changes
         return value.replace(tzinfo=timezone)
 
+
 def make_naive(value, timezone):
     """
     Makes an aware datetime.datetime naive in a given time zone.
diff --git a/django/utils/translation/__init__.py b/django/utils/translation/__init__.py
index d99c8bbd78..e4e8c6e1be 100644
--- a/django/utils/translation/__init__.py
+++ b/django/utils/translation/__init__.py
@@ -61,26 +61,33 @@ _trans = Trans()
 # The Trans class is no more needed, so remove it from the namespace.
 del Trans
 
+
 def gettext_noop(message):
     return _trans.gettext_noop(message)
 
 ugettext_noop = gettext_noop
 
+
 def gettext(message):
     return _trans.gettext(message)
 
+
 def ngettext(singular, plural, number):
     return _trans.ngettext(singular, plural, number)
 
+
 def ugettext(message):
     return _trans.ugettext(message)
 
+
 def ungettext(singular, plural, number):
     return _trans.ungettext(singular, plural, number)
 
+
 def pgettext(context, message):
     return _trans.pgettext(context, message)
 
+
 def npgettext(context, singular, plural, number):
     return _trans.npgettext(context, singular, plural, number)
 
@@ -88,6 +95,7 @@ gettext_lazy = lazy(gettext, str)
 ugettext_lazy = lazy(ugettext, six.text_type)
 pgettext_lazy = lazy(pgettext, six.text_type)
 
+
 def lazy_number(func, resultclass, number=None, **kwargs):
     if isinstance(number, int):
         kwargs['number'] = number
@@ -117,21 +125,27 @@ def lazy_number(func, resultclass, number=None, **kwargs):
         proxy = lazy(lambda **kwargs: NumberAwareString(), NumberAwareString)(**kwargs)
     return proxy
 
+
 def ngettext_lazy(singular, plural, number=None):
     return lazy_number(ngettext, str, singular=singular, plural=plural, number=number)
 
+
 def ungettext_lazy(singular, plural, number=None):
     return lazy_number(ungettext, six.text_type, singular=singular, plural=plural, number=number)
 
+
 def npgettext_lazy(context, singular, plural, number=None):
     return lazy_number(npgettext, six.text_type, context=context, singular=singular, plural=plural, number=number)
 
+
 def activate(language):
     return _trans.activate(language)
 
+
 def deactivate():
     return _trans.deactivate()
 
+
 class override(object):
     def __init__(self, language, deactivate=False):
         self.language = language
@@ -150,30 +164,39 @@ class override(object):
         else:
             activate(self.old_language)
 
+
 def get_language():
     return _trans.get_language()
 
+
 def get_language_bidi():
     return _trans.get_language_bidi()
 
+
 def check_for_language(lang_code):
     return _trans.check_for_language(lang_code)
 
+
 def to_locale(language):
     return _trans.to_locale(language)
 
+
 def get_language_from_request(request, check_path=False):
     return _trans.get_language_from_request(request, check_path)
 
+
 def get_language_from_path(path, supported=None):
     return _trans.get_language_from_path(path, supported=supported)
 
+
 def templatize(src, origin=None):
     return _trans.templatize(src, origin)
 
+
 def deactivate_all():
     return _trans.deactivate_all()
 
+
 def _string_concat(*strings):
     """
     Lazy variant of string concatenation, needed for translations that are
@@ -182,6 +205,7 @@ def _string_concat(*strings):
     return ''.join(force_text(s) for s in strings)
 string_concat = lazy(_string_concat, six.text_type)
 
+
 def get_language_info(lang_code):
     from django.conf.locale import LANG_INFO
     try:
diff --git a/django/utils/translation/trans_null.py b/django/utils/translation/trans_null.py
index 88c77a5110..9e3beb0f7d 100644
--- a/django/utils/translation/trans_null.py
+++ b/django/utils/translation/trans_null.py
@@ -6,18 +6,22 @@ from django.conf import settings
 from django.utils.encoding import force_text
 from django.utils.safestring import mark_safe, SafeData
 
+
 def ngettext(singular, plural, number):
     if number == 1:
         return singular
     return plural
 ngettext_lazy = ngettext
 
+
 def ungettext(singular, plural, number):
     return force_text(ngettext(singular, plural, number))
 
+
 def pgettext(context, message):
     return ugettext(message)
 
+
 def npgettext(context, singular, plural, number):
     return ungettext(singular, plural, number)
 
@@ -38,17 +42,20 @@ TECHNICAL_ID_MAP = {
     "MONTH_DAY_FORMAT": settings.MONTH_DAY_FORMAT,
 }
 
+
 def gettext(message):
     result = TECHNICAL_ID_MAP.get(message, message)
     if isinstance(message, SafeData):
         return mark_safe(result)
     return result
 
+
 def ugettext(message):
     return force_text(gettext(message))
 
 gettext_noop = gettext_lazy = _ = gettext
 
+
 def to_locale(language):
     p = language.find('-')
     if p >= 0:
@@ -56,8 +63,10 @@ def to_locale(language):
     else:
         return language.lower()
 
+
 def get_language_from_request(request, check_path=False):
     return settings.LANGUAGE_CODE
 
+
 def get_language_from_path(request, supported=None):
     return None
diff --git a/django/utils/translation/trans_real.py b/django/utils/translation/trans_real.py
index b79af80dd1..d78b6d6412 100644
--- a/django/utils/translation/trans_real.py
+++ b/django/utils/translation/trans_real.py
@@ -64,6 +64,7 @@ def to_locale(language, to_lower=False):
     else:
         return language.lower()
 
+
 def to_language(locale):
     """Turns a locale name (en_US) into a language name (en-us)."""
     p = locale.find('_')
@@ -72,6 +73,7 @@ def to_language(locale):
     else:
         return locale.lower()
 
+
 class DjangoTranslation(gettext_module.GNUTranslations):
     """
     This class sets up the GNUTranslations context with regard to output
@@ -98,6 +100,7 @@ class DjangoTranslation(gettext_module.GNUTranslations):
     def __repr__(self):
         return "<DjangoTranslation lang:%s>" % self.__language
 
+
 def translation(language):
     """
     Returns a translation object.
@@ -179,6 +182,7 @@ def translation(language):
 
     return current_translation
 
+
 def activate(language):
     """
     Fetches the translation object for a given tuple of application name and
@@ -187,6 +191,7 @@ def activate(language):
     """
     _active.value = translation(language)
 
+
 def deactivate():
     """
     Deinstalls the currently active translation object so that further _ calls
@@ -195,6 +200,7 @@ def deactivate():
     if hasattr(_active, "value"):
         del _active.value
 
+
 def deactivate_all():
     """
     Makes the active translation object a NullTranslations() instance. This is
@@ -203,6 +209,7 @@ def deactivate_all():
     """
     _active.value = gettext_module.NullTranslations()
 
+
 def get_language():
     """Returns the currently selected language."""
     t = getattr(_active, "value", None)
@@ -215,6 +222,7 @@ def get_language():
     from django.conf import settings
     return settings.LANGUAGE_CODE
 
+
 def get_language_bidi():
     """
     Returns selected language's BiDi layout.
@@ -227,6 +235,7 @@ def get_language_bidi():
     base_lang = get_language().split('-')[0]
     return base_lang in settings.LANGUAGES_BIDI
 
+
 def catalog():
     """
     Returns the current active catalog for further processing.
@@ -243,6 +252,7 @@ def catalog():
         _default = translation(settings.LANGUAGE_CODE)
     return _default
 
+
 def do_translate(message, translation_function):
     """
     Translates 'message' using the given 'translation_function' name -- which
@@ -266,6 +276,7 @@ def do_translate(message, translation_function):
         return mark_safe(result)
     return result
 
+
 def gettext(message):
     """
     Returns a string of the translation of the message.
@@ -280,6 +291,7 @@ else:
     def ugettext(message):
         return do_translate(message, 'ugettext')
 
+
 def pgettext(context, message):
     msg_with_ctxt = "%s%s%s" % (context, CONTEXT_SEPARATOR, message)
     result = ugettext(msg_with_ctxt)
@@ -288,6 +300,7 @@ def pgettext(context, message):
         result = message
     return result
 
+
 def gettext_noop(message):
     """
     Marks strings for translation but doesn't translate them now. This can be
@@ -297,6 +310,7 @@ def gettext_noop(message):
     """
     return message
 
+
 def do_ntranslate(singular, plural, number, translation_function):
     global _default
 
@@ -308,6 +322,7 @@ def do_ntranslate(singular, plural, number, translation_function):
         _default = translation(settings.LANGUAGE_CODE)
     return getattr(_default, translation_function)(singular, plural, number)
 
+
 def ngettext(singular, plural, number):
     """
     Returns a string of the translation of either the singular or plural,
@@ -327,6 +342,7 @@ else:
         """
         return do_ntranslate(singular, plural, number, 'ungettext')
 
+
 def npgettext(context, singular, plural, number):
     msgs_with_ctxt = ("%s%s%s" % (context, CONTEXT_SEPARATOR, singular),
                       "%s%s%s" % (context, CONTEXT_SEPARATOR, plural),
@@ -337,6 +353,7 @@ def npgettext(context, singular, plural, number):
         result = ungettext(singular, plural, number)
     return result
 
+
 def all_locale_paths():
     """
     Returns a list of paths to user-provides languages files.
@@ -346,6 +363,7 @@ def all_locale_paths():
         os.path.dirname(upath(sys.modules[settings.__module__].__file__)), 'locale')
     return [globalpath] + list(settings.LOCALE_PATHS)
 
+
 def check_for_language(lang_code):
     """
     Checks whether there is a global language file for the given language
@@ -359,6 +377,7 @@ def check_for_language(lang_code):
     return False
 check_for_language = memoize(check_for_language, _checked_languages, 1)
 
+
 def get_supported_language_variant(lang_code, supported=None, strict=False):
     """
     Returns the language-code that's listed in supported languages, possibly
@@ -386,6 +405,7 @@ def get_supported_language_variant(lang_code, supported=None, strict=False):
                     return supported_code
     raise LookupError(lang_code)
 
+
 def get_language_from_path(path, supported=None, strict=False):
     """
     Returns the language-code if there is a valid language-code
@@ -406,6 +426,7 @@ def get_language_from_path(path, supported=None, strict=False):
     except LookupError:
         return None
 
+
 def get_language_from_request(request, check_path=False):
     """
     Analyzes the request to find what language the user wants the system to
@@ -470,6 +491,8 @@ def get_language_from_request(request, check_path=False):
         return settings.LANGUAGE_CODE
 
 dot_re = re.compile(r'\S')
+
+
 def blankout(src, char):
     """
     Changes every non-whitespace character to the given char.
@@ -653,6 +676,7 @@ def templatize(src, origin=None):
                 out.write(blankout(t.contents, 'X'))
     return force_str(out.getvalue())
 
+
 def parse_accept_lang_header(lang_string):
     """
     Parses the lang_string, which is the body of an HTTP Accept-Language
diff --git a/django/views/debug.py b/django/views/debug.py
index 2829ca1443..0ee5d588c7 100644
--- a/django/views/debug.py
+++ b/django/views/debug.py
@@ -21,6 +21,7 @@ HIDDEN_SETTINGS = re.compile('API|TOKEN|KEY|SECRET|PASS|PROFANITIES_LIST|SIGNATU
 
 CLEANSED_SUBSTITUTE = '********************'
 
+
 def linebreak_iter(template_source):
     yield 0
     p = template_source.find('\n')
@@ -29,6 +30,7 @@ def linebreak_iter(template_source):
         p = template_source.find('\n', p+1)
     yield len(template_source) + 1
 
+
 def cleanse_setting(key, value):
     """Cleanse an individual setting key/value of sensitive content.
 
@@ -52,6 +54,7 @@ def cleanse_setting(key, value):
 
     return cleansed
 
+
 def get_safe_settings():
     "Returns a dictionary of the settings module, with sensitive settings blurred out."
     settings_dict = {}
@@ -60,6 +63,7 @@ def get_safe_settings():
             settings_dict[k] = cleanse_setting(k, getattr(settings, k))
     return settings_dict
 
+
 def technical_500_response(request, exc_type, exc_value, tb):
     """
     Create a technical server error response. The last three arguments are
@@ -76,6 +80,7 @@ def technical_500_response(request, exc_type, exc_value, tb):
 # Cache for the default exception reporter filter instance.
 default_exception_reporter_filter = None
 
+
 def get_exception_reporter_filter(request):
     global default_exception_reporter_filter
     if default_exception_reporter_filter is None:
@@ -87,6 +92,7 @@ def get_exception_reporter_filter(request):
     else:
         return default_exception_reporter_filter
 
+
 class ExceptionReporterFilter(object):
     """
     Base for all exception reporter filter classes. All overridable hooks
@@ -108,6 +114,7 @@ class ExceptionReporterFilter(object):
     def get_traceback_frame_variables(self, request, tb_frame):
         return list(six.iteritems(tb_frame.f_locals))
 
+
 class SafeExceptionReporterFilter(ExceptionReporterFilter):
     """
     Use annotations made by the sensitive_post_parameters and
@@ -221,6 +228,7 @@ class SafeExceptionReporterFilter(ExceptionReporterFilter):
 
         return cleansed.items()
 
+
 class ExceptionReporter(object):
     """
     A class to organize and coordinate reporting on exceptions.
@@ -491,6 +499,7 @@ def technical_404_response(request, exception):
     })
     return HttpResponseNotFound(t.render(c), content_type='text/html')
 
+
 def default_urlconf(request):
     "Create an empty URLconf 404 error response."
     t = Template(DEFAULT_URLCONF_TEMPLATE, name='Default URLconf template')
diff --git a/django/views/decorators/http.py b/django/views/decorators/http.py
index a0da002dc9..df4e165066 100644
--- a/django/views/decorators/http.py
+++ b/django/views/decorators/http.py
@@ -51,6 +51,7 @@ require_POST.__doc__ = "Decorator to require that a view only accept the POST me
 require_safe = require_http_methods(["GET", "HEAD"])
 require_safe.__doc__ = "Decorator to require that a view only accept safe methods: GET and HEAD."
 
+
 def condition(etag_func=None, last_modified_func=None):
     """
     Decorator to support conditional retrieval (or change) for a view
@@ -157,9 +158,11 @@ def condition(etag_func=None, last_modified_func=None):
         return inner
     return decorator
 
+
 # Shortcut decorators for common cases based on ETag or Last-Modified only
 def etag(etag_func):
     return condition(etag_func=etag_func)
 
+
 def last_modified(last_modified_func):
     return condition(last_modified_func=last_modified_func)
diff --git a/django/views/decorators/vary.py b/django/views/decorators/vary.py
index cd2f9c0f55..056669278b 100644
--- a/django/views/decorators/vary.py
+++ b/django/views/decorators/vary.py
@@ -2,6 +2,7 @@ from functools import wraps
 from django.utils.cache import patch_vary_headers
 from django.utils.decorators import available_attrs
 
+
 def vary_on_headers(*headers):
     """
     A view decorator that adds the specified headers to the Vary header of the
@@ -22,6 +23,7 @@ def vary_on_headers(*headers):
         return inner_func
     return decorator
 
+
 def vary_on_cookie(func):
     """
     A view decorator that adds "Cookie" to the Vary header of a response. This
diff --git a/django/views/generic/dates.py b/django/views/generic/dates.py
index 370cb32ce7..d221c2c087 100644
--- a/django/views/generic/dates.py
+++ b/django/views/generic/dates.py
@@ -13,6 +13,7 @@ from django.views.generic.base import View
 from django.views.generic.detail import BaseDetailView, SingleObjectTemplateResponseMixin
 from django.views.generic.list import MultipleObjectMixin, MultipleObjectTemplateResponseMixin
 
+
 class YearMixin(object):
     """
     Mixin for views manipulating year-based data.
diff --git a/django/views/i18n.py b/django/views/i18n.py
index 9ede1ed49f..751905efaf 100644
--- a/django/views/i18n.py
+++ b/django/views/i18n.py
@@ -13,6 +13,7 @@ from django.utils._os import upath
 from django.utils.http import is_safe_url
 from django.utils import six
 
+
 def set_language(request):
     """
     Redirect to a given url while setting the chosen language in the
diff --git a/django/views/static.py b/django/views/static.py
index e55f6a1234..11c8734eec 100644
--- a/django/views/static.py
+++ b/django/views/static.py
@@ -17,6 +17,7 @@ from django.utils.http import http_date, parse_http_date
 from django.utils.six.moves.urllib.parse import unquote
 from django.utils.translation import ugettext as _, ugettext_noop
 
+
 def serve(request, path, document_root=None, show_indexes=False):
     """
     Serve static files below a given point in the directory structure.
@@ -95,6 +96,7 @@ DEFAULT_DIRECTORY_INDEX_TEMPLATE = """
 """
 template_translatable = ugettext_noop("Index of %(directory)s")
 
+
 def directory_index(path, fullpath):
     try:
         t = loader.select_template(['static/directory_index.html',
@@ -113,6 +115,7 @@ def directory_index(path, fullpath):
     })
     return HttpResponse(t.render(c))
 
+
 def was_modified_since(header=None, mtime=0, size=0):
     """
     Was something modified since the user last downloaded it?

From 776ee92f00c22c009a4db0fb4ce50284ca29d6fb Mon Sep 17 00:00:00 2001
From: Ray Ashman Jr <ray.ashman.jr@gmail.com>
Date: Sat, 2 Nov 2013 20:11:21 -0400
Subject: [PATCH 5/8] Revert change to django/test/_doctest.py

---
 django/test/_doctest.py | 55 +++++++----------------------------------
 1 file changed, 9 insertions(+), 46 deletions(-)

diff --git a/django/test/_doctest.py b/django/test/_doctest.py
index c5b94c83a0..2b90f1dc2e 100644
--- a/django/test/_doctest.py
+++ b/django/test/_doctest.py
@@ -144,8 +144,6 @@ if sys.platform.startswith('java'):
 # Option constants.
 
 OPTIONFLAGS_BY_NAME = {}
-
-
 def register_optionflag(name):
     # Create a new flag unless `name` is already known.
     return OPTIONFLAGS_BY_NAME.setdefault(name, 1 << len(OPTIONFLAGS_BY_NAME))
@@ -196,7 +194,6 @@ ELLIPSIS_MARKER = '...'
 ## 1. Utility Functions
 ######################################################################
 
-
 def _extract_future_flags(globs):
     """
     Return the compiler-flags associated with the future features that
@@ -209,7 +206,6 @@ def _extract_future_flags(globs):
             flags |= feature.compiler_flag
     return flags
 
-
 def _normalize_module(module, depth=2):
     """
     Return the module specified by `module`.  In particular:
@@ -229,7 +225,6 @@ def _normalize_module(module, depth=2):
     else:
         raise TypeError("Expected a module, string, or None")
 
-
 def _load_testfile(filename, package, module_relative):
     if module_relative:
         package = _normalize_module(package, 3)
@@ -243,7 +238,6 @@ def _load_testfile(filename, package, module_relative):
     with open(filename) as fp:
         return fp.read(), filename
 
-
 def _indent(s, indent=4):
     """
     Add the given number of space characters to the beginning every
@@ -252,7 +246,6 @@ def _indent(s, indent=4):
     # This regexp matches the start of non-blank lines:
     return re.sub('(?m)^(?!$)', indent*' ', s)
 
-
 def _exception_traceback(exc_info):
     """
     Return a string containing a traceback message for the given
@@ -264,7 +257,6 @@ def _exception_traceback(exc_info):
     traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
     return excout.getvalue()
 
-
 # Override some StringIO methods.
 class _SpoofOut(StringIO):
     def getvalue(self):
@@ -285,7 +277,6 @@ class _SpoofOut(StringIO):
         if hasattr(self, "softspace"):
             del self.softspace
 
-
 # Worst-case linear-time ellipsis matching.
 def _ellipsis_match(want, got):
     """
@@ -336,7 +327,6 @@ def _ellipsis_match(want, got):
 
     return True
 
-
 def _comment_line(line):
     "Return a commented form of the given line"
     line = line.rstrip()
@@ -345,7 +335,6 @@ def _comment_line(line):
     else:
         return '#'
 
-
 class _OutputRedirectingPdb(pdb.Pdb):
     """
     A specialized version of the python debugger that redirects stdout
@@ -379,7 +368,6 @@ class _OutputRedirectingPdb(pdb.Pdb):
         finally:
             sys.stdout = save_stdout
 
-
 # [XX] Normalize with respect to os.path.pardir?
 def _module_relative_path(module, path):
     if not inspect.ismodule(module):
@@ -417,7 +405,6 @@ def _module_relative_path(module, path):
 ##   a string (such as an object's docstring).  The DocTest class also
 ##   includes information about where the string was extracted from.
 
-
 class Example:
     """
     A single doctest example, consisting of source code and expected
@@ -471,7 +458,6 @@ class Example:
         self.options = options
         self.exc_msg = exc_msg
 
-
 class DocTest:
     """
     A collection of doctest examples that should be run in a single
@@ -520,10 +506,10 @@ class DocTest:
         return ('<DocTest %s from %s:%s (%s)>' %
                 (self.name, self.filename, self.lineno, examples))
 
+
     # This lets us sort tests by name:
     def _cmpkey(self):
         return (self.name, self.filename, self.lineno, id(self))
-
     def __cmp__(self, other):
         if not isinstance(other, DocTest):
             return -1
@@ -912,7 +898,7 @@ class DocTestFinder:
         elif hasattr(object, '__module__'):
             return module.__name__ == object.__module__
         elif isinstance(object, property):
-            return True  # [XX] no way not be sure.
+            return True # [XX] no way not be sure.
         else:
             raise ValueError("object must be a class or function")
 
@@ -1068,7 +1054,6 @@ class DocTestFinder:
 ## 5. DocTest Runner
 ######################################################################
 
-
 class DocTestRunner:
     """
     A class used to run DocTest test cases, and accumulate statistics.
@@ -1236,7 +1221,7 @@ class DocTestRunner:
         # to modify them).
         original_optionflags = self.optionflags
 
-        SUCCESS, FAILURE, BOOM = range(3)  # `outcome` state
+        SUCCESS, FAILURE, BOOM = range(3) # `outcome` state
 
         check = self._checker.check_output
 
@@ -1289,7 +1274,7 @@ class DocTestRunner:
                     # Strip b"" and u"" prefixes from the repr and expected output
                     # TODO: better way of stripping the prefixes?
                     expected = example.want
-                    expected = expected.strip()  # be wary of newlines
+                    expected = expected.strip() # be wary of newlines
                     s = s.replace("u", "")
                     s = s.replace("b", "")
                     expected = expected.replace("u", "")
@@ -1303,7 +1288,7 @@ class DocTestRunner:
                     lines.append(s)
 
                     # let them match
-                    if s == expected:  # be wary of false positives here
+                    if s == expected: # be wary of false positives here
                         # they should be the same, print expected value
                         sys.stdout.write("%s\n" % example.want.strip())
 
@@ -1329,13 +1314,13 @@ class DocTestRunner:
                 # Don't blink!  This is where the user's code gets run.
                 six.exec_(compile(example.source, filename, "single",
                              compileflags, 1), test.globs)
-                self.debugger.set_continue()  # ==== Example Finished ====
+                self.debugger.set_continue() # ==== Example Finished ====
                 exception = None
             except KeyboardInterrupt:
                 raise
             except:
                 exception = sys.exc_info()
-                self.debugger.set_continue()  # ==== Example Finished ====
+                self.debugger.set_continue() # ==== Example Finished ====
             finally:
                 # restore the original displayhook
                 sys.displayhook = original_displayhook
@@ -1423,7 +1408,6 @@ class DocTestRunner:
     __LINECACHE_FILENAME_RE = re.compile(r'<doctest '
                                          r'(?P<name>[\w\.]+)'
                                          r'\[(?P<examplenum>\d+)\]>$')
-
     def __patched_linecache_getlines(self, filename, module_globals=None):
         m = self.__LINECACHE_FILENAME_RE.match(filename)
         if m and m.group('name') == self.test.name:
@@ -1557,7 +1541,6 @@ class DocTestRunner:
                 t = t + t2
             d[name] = f, t
 
-
 class OutputChecker:
     """
     A class used to check the whether the actual output from a doctest
@@ -1664,11 +1647,11 @@ class OutputChecker:
             # Use difflib to find their differences.
             if optionflags & REPORT_UDIFF:
                 diff = difflib.unified_diff(want_lines, got_lines, n=2)
-                diff = list(diff)[2:]  # strip the diff header
+                diff = list(diff)[2:] # strip the diff header
                 kind = 'unified diff with -expected +actual'
             elif optionflags & REPORT_CDIFF:
                 diff = difflib.context_diff(want_lines, got_lines, n=2)
-                diff = list(diff)[2:]  # strip the diff header
+                diff = list(diff)[2:] # strip the diff header
                 kind = 'context diff with expected followed by actual'
             elif optionflags & REPORT_NDIFF:
                 engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
@@ -1691,7 +1674,6 @@ class OutputChecker:
         else:
             return 'Expected nothing\nGot nothing\n'
 
-
 class DocTestFailure(Exception):
     """A DocTest example has failed in debugging mode.
 
@@ -1711,7 +1693,6 @@ class DocTestFailure(Exception):
     def __str__(self):
         return str(self.test)
 
-
 class UnexpectedException(Exception):
     """A DocTest example has encountered an unexpected exception
 
@@ -1731,7 +1712,6 @@ class UnexpectedException(Exception):
     def __str__(self):
         return str(self.test)
 
-
 class DebugRunner(DocTestRunner):
     r"""Run doc tests but raise an exception as soon as there is a failure.
 
@@ -1844,7 +1824,6 @@ class DebugRunner(DocTestRunner):
 # class, updated by testmod.
 master = None
 
-
 def testmod(m=None, name=None, globs=None, verbose=None,
             report=True, optionflags=0, extraglobs=None,
             raise_on_error=False, exclude_empty=False):
@@ -1949,7 +1928,6 @@ def testmod(m=None, name=None, globs=None, verbose=None,
 
     return runner.failures, runner.tries
 
-
 def testfile(filename, module_relative=True, name=None, package=None,
              globs=None, verbose=None, report=True, optionflags=0,
              extraglobs=None, raise_on_error=False, parser=DocTestParser(),
@@ -2073,7 +2051,6 @@ def testfile(filename, module_relative=True, name=None, package=None,
 
     return runner.failures, runner.tries
 
-
 def run_docstring_examples(f, globs, verbose=False, name="NoName",
                            compileflags=None, optionflags=0):
     """
@@ -2103,7 +2080,6 @@ def run_docstring_examples(f, globs, verbose=False, name="NoName",
 # This is provided only for backwards compatibility.  It's not
 # actually used in any way.
 
-
 class Tester:
     def __init__(self, mod=None, globs=None, verbose=None, optionflags=0):
 
@@ -2169,7 +2145,6 @@ class Tester:
 
 _unittest_reportflags = 0
 
-
 def set_unittest_reportflags(flags):
     """Sets the unittest option flags.
 
@@ -2353,7 +2328,6 @@ class DocTestCase(unittest.TestCase):
     def shortDescription(self):
         return "Doctest: " + self._dt_test.name
 
-
 def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
                  test_class=DocTestCase, **options):
     """
@@ -2417,7 +2391,6 @@ def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
 
     return suite
 
-
 class DocFileCase(DocTestCase):
 
     def id(self):
@@ -2432,7 +2405,6 @@ class DocFileCase(DocTestCase):
                 % (self._dt_test.name, self._dt_test.filename, err)
                 )
 
-
 def DocFileTest(path, module_relative=True, package=None,
                 globs=None, parser=DocTestParser(),
                 encoding=None, **options):
@@ -2462,7 +2434,6 @@ def DocFileTest(path, module_relative=True, package=None,
     test = parser.get_doctest(doc, globs, name, path, 0)
     return DocFileCase(test, **options)
 
-
 def DocFileSuite(*paths, **kw):
     """A unittest suite for one or more doctest files.
 
@@ -2536,7 +2507,6 @@ def DocFileSuite(*paths, **kw):
 ## 9. Debugging Support
 ######################################################################
 
-
 def script_from_examples(s):
     r"""Extract script from text with examples.
 
@@ -2617,7 +2587,6 @@ def script_from_examples(s):
     # Combine the output, and return it.
     return '\n'.join(output)
 
-
 def testsource(module, name):
     """Extract the test sources from a doctest docstring as a script.
 
@@ -2634,13 +2603,11 @@ def testsource(module, name):
     testsrc = script_from_examples(test.docstring)
     return testsrc
 
-
 def debug_src(src, pm=False, globs=None):
     """Debug a single doctest docstring, in argument `src`'"""
     testsrc = script_from_examples(src)
     debug_script(testsrc, pm, globs)
 
-
 def debug_script(src, pm=False, globs=None):
     "Debug a test script.  `src` is the script, as a string."
     import pdb
@@ -2672,7 +2639,6 @@ def debug_script(src, pm=False, globs=None):
     finally:
         os.remove(srcfilename)
 
-
 def debug(module, name, pm=False):
     """Debug a single doctest docstring.
 
@@ -2687,8 +2653,6 @@ def debug(module, name, pm=False):
 ######################################################################
 ## 10. Example Usage
 ######################################################################
-
-
 class _TestClass:
     """
     A pointless class, for sanity-checking of docstring testing.
@@ -2783,7 +2747,6 @@ __test__ = {"_TestClass": _TestClass,
             """,
            }
 
-
 def _test():
     r = unittest.TextTestRunner()
     r.run(DocTestSuite())

From 8f85e734581d3c63905b991fc82fe05e7a1df709 Mon Sep 17 00:00:00 2001
From: Ray Ashman Jr <ray.ashman.jr@gmail.com>
Date: Sat, 2 Nov 2013 20:20:53 -0400
Subject: [PATCH 6/8] Checkout prior commit of _doctest.py

---
 django/test/_doctest.py | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)

diff --git a/django/test/_doctest.py b/django/test/_doctest.py
index 2b90f1dc2e..048d886720 100644
--- a/django/test/_doctest.py
+++ b/django/test/_doctest.py
@@ -898,7 +898,7 @@ class DocTestFinder:
         elif hasattr(object, '__module__'):
             return module.__name__ == object.__module__
         elif isinstance(object, property):
-            return True # [XX] no way not be sure.
+            return True  # [XX] no way not be sure.
         else:
             raise ValueError("object must be a class or function")
 
@@ -1221,7 +1221,7 @@ class DocTestRunner:
         # to modify them).
         original_optionflags = self.optionflags
 
-        SUCCESS, FAILURE, BOOM = range(3) # `outcome` state
+        SUCCESS, FAILURE, BOOM = range(3)  # `outcome` state
 
         check = self._checker.check_output
 
@@ -1274,7 +1274,7 @@ class DocTestRunner:
                     # Strip b"" and u"" prefixes from the repr and expected output
                     # TODO: better way of stripping the prefixes?
                     expected = example.want
-                    expected = expected.strip() # be wary of newlines
+                    expected = expected.strip()  # be wary of newlines
                     s = s.replace("u", "")
                     s = s.replace("b", "")
                     expected = expected.replace("u", "")
@@ -1288,7 +1288,7 @@ class DocTestRunner:
                     lines.append(s)
 
                     # let them match
-                    if s == expected: # be wary of false positives here
+                    if s == expected:  # be wary of false positives here
                         # they should be the same, print expected value
                         sys.stdout.write("%s\n" % example.want.strip())
 
@@ -1314,13 +1314,13 @@ class DocTestRunner:
                 # Don't blink!  This is where the user's code gets run.
                 six.exec_(compile(example.source, filename, "single",
                              compileflags, 1), test.globs)
-                self.debugger.set_continue() # ==== Example Finished ====
+                self.debugger.set_continue()  # ==== Example Finished ====
                 exception = None
             except KeyboardInterrupt:
                 raise
             except:
                 exception = sys.exc_info()
-                self.debugger.set_continue() # ==== Example Finished ====
+                self.debugger.set_continue()  # ==== Example Finished ====
             finally:
                 # restore the original displayhook
                 sys.displayhook = original_displayhook
@@ -1647,11 +1647,11 @@ class OutputChecker:
             # Use difflib to find their differences.
             if optionflags & REPORT_UDIFF:
                 diff = difflib.unified_diff(want_lines, got_lines, n=2)
-                diff = list(diff)[2:] # strip the diff header
+                diff = list(diff)[2:]  # strip the diff header
                 kind = 'unified diff with -expected +actual'
             elif optionflags & REPORT_CDIFF:
                 diff = difflib.context_diff(want_lines, got_lines, n=2)
-                diff = list(diff)[2:] # strip the diff header
+                diff = list(diff)[2:]  # strip the diff header
                 kind = 'context diff with expected followed by actual'
             elif optionflags & REPORT_NDIFF:
                 engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)

From 0fdb692c6c94d912f17a3e2ad12413fb072d38ec Mon Sep 17 00:00:00 2001
From: Alex Gaynor <alex.gaynor@gmail.com>
Date: Sat, 2 Nov 2013 17:37:15 -0700
Subject: [PATCH 7/8] Fixed the remaining E302 violations int eh django package

---
 django/http/multipartparser.py             |  9 ++++
 django/template/base.py                    | 26 ++++++++++
 django/template/context.py                 |  2 +
 django/template/defaultfilters.py          | 56 ++++++++++++++++++++++
 django/template/defaulttags.py             | 44 +++++++++++++++++
 django/template/loader.py                  |  9 ++++
 django/template/loader_tags.py             |  7 +++
 django/template/loaders/app_directories.py |  1 +
 django/template/loaders/cached.py          |  1 +
 django/template/loaders/eggs.py            |  1 +
 django/template/loaders/filesystem.py      |  1 +
 django/templatetags/i18n.py                | 10 ++++
 django/templatetags/l10n.py                |  4 ++
 docs/_ext/applyxrefs.py                    |  4 ++
 docs/_ext/djangodocs.py                    |  2 +
 docs/_ext/literals_to_xrefs.py             |  1 +
 extras/csrf_migration_helper.py            |  7 +++
 scripts/manage_translations.py             |  3 ++
 18 files changed, 188 insertions(+)

diff --git a/django/http/multipartparser.py b/django/http/multipartparser.py
index 28c0195a48..dcf2d1ae0d 100644
--- a/django/http/multipartparser.py
+++ b/django/http/multipartparser.py
@@ -269,6 +269,7 @@ class MultiPartParser(object):
         """Cleanup filename from Internet Explorer full paths."""
         return filename and filename[filename.rfind("\\")+1:].strip()
 
+
 class LazyStream(six.Iterator):
     """
     The LazyStream wrapper allows one to get and "unget" bytes from a stream.
@@ -380,6 +381,7 @@ class LazyStream(six.Iterator):
                 " if there is none, report this to the Django developers."
             )
 
+
 class ChunkIter(six.Iterator):
     """
     An iterable that will yield chunks of data. Given a file-like object as the
@@ -403,6 +405,7 @@ class ChunkIter(six.Iterator):
     def __iter__(self):
         return self
 
+
 class InterBoundaryIter(six.Iterator):
     """
     A Producer that will iterate over boundaries.
@@ -420,6 +423,7 @@ class InterBoundaryIter(six.Iterator):
         except InputStreamExhausted:
             raise StopIteration()
 
+
 class BoundaryIter(six.Iterator):
     """
     A Producer that is sensitive to boundaries.
@@ -516,6 +520,7 @@ class BoundaryIter(six.Iterator):
                 end -= 1
             return end, next
 
+
 def exhaust(stream_or_iterable):
     """
     Completely exhausts an iterator or stream.
@@ -534,6 +539,7 @@ def exhaust(stream_or_iterable):
     for __ in iterator:
         pass
 
+
 def parse_boundary_stream(stream, max_header_size):
     """
     Parses one and exactly one stream that encapsulates a boundary.
@@ -592,6 +598,7 @@ def parse_boundary_stream(stream, max_header_size):
 
     return (TYPE, outdict, stream)
 
+
 class Parser(object):
     def __init__(self, stream, boundary):
         self._stream = stream
@@ -603,6 +610,7 @@ class Parser(object):
             # Iterate over each part
             yield parse_boundary_stream(sub_stream, 1024)
 
+
 def parse_header(line):
     """ Parse the header into a key-value.
         Input (line): bytes, output: unicode for key/name, bytes for value which
@@ -622,6 +630,7 @@ def parse_header(line):
             pdict[name] = value
     return key, pdict
 
+
 def _parse_header_params(s):
     plist = []
     while s[:1] == b';':
diff --git a/django/template/base.py b/django/template/base.py
index ad13108e4e..efeca3ea2a 100644
--- a/django/template/base.py
+++ b/django/template/base.py
@@ -95,9 +95,11 @@ class VariableDoesNotExist(Exception):
         return self.msg % tuple(force_text(p, errors='replace')
                                  for p in self.params)
 
+
 class InvalidTemplateLibrary(Exception):
     pass
 
+
 class Origin(object):
     def __init__(self, name):
         self.name = name
@@ -108,6 +110,7 @@ class Origin(object):
     def __str__(self):
         return self.name
 
+
 class StringOrigin(Origin):
     def __init__(self, source):
         super(StringOrigin, self).__init__(UNKNOWN_SOURCE)
@@ -116,6 +119,7 @@ class StringOrigin(Origin):
     def reload(self):
         return self.source
 
+
 class Template(object):
     def __init__(self, template_string, origin=None,
                  name='<Unknown Template>'):
@@ -146,6 +150,7 @@ class Template(object):
         finally:
             context.render_context.pop()
 
+
 def compile_string(template_string, origin):
     "Compiles template_string into NodeList ready for rendering"
     if settings.TEMPLATE_DEBUG:
@@ -157,6 +162,7 @@ def compile_string(template_string, origin):
     parser = parser_class(lexer.tokenize())
     return parser.parse()
 
+
 class Token(object):
     def __init__(self, token_type, contents):
         # token_type must be TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK or
@@ -184,6 +190,7 @@ class Token(object):
             split.append(bit)
         return split
 
+
 class Lexer(object):
     def __init__(self, template_string, origin):
         self.template_string = template_string
@@ -235,6 +242,7 @@ class Lexer(object):
         self.lineno += token_string.count('\n')
         return token
 
+
 class Parser(object):
     def __init__(self, tokens):
         self.tokens = tokens
@@ -370,6 +378,7 @@ class Parser(object):
         else:
             raise TemplateSyntaxError("Invalid filter: '%s'" % filter_name)
 
+
 class TokenParser(object):
     """
     Subclass this and implement the top() method to parse a template line.
@@ -523,6 +532,7 @@ filter_raw_string = r"""
 
 filter_re = re.compile(filter_raw_string, re.UNICODE | re.VERBOSE)
 
+
 class FilterExpression(object):
     """
     Parses a variable token and its optional filters (all as a single string),
@@ -644,6 +654,7 @@ class FilterExpression(object):
     def __str__(self):
         return self.token
 
+
 def resolve_variable(path, context):
     """
     Returns the resolved variable, which may contain attribute syntax, within
@@ -653,6 +664,7 @@ def resolve_variable(path, context):
     """
     return Variable(path).resolve(context)
 
+
 class Variable(object):
     """
     A template variable, resolvable against a given context. The variable may
@@ -793,6 +805,7 @@ class Variable(object):
 
         return current
 
+
 class Node(object):
     # Set this to True for nodes that must be first in the template (although
     # they can be preceded by text nodes.
@@ -822,6 +835,7 @@ class Node(object):
                 nodes.extend(nodelist.get_nodes_by_type(nodetype))
         return nodes
 
+
 class NodeList(list):
     # Set to True the first time a non-TextNode is inserted by
     # extend_nodelist().
@@ -847,6 +861,7 @@ class NodeList(list):
     def render_node(self, node, context):
         return node.render(context)
 
+
 class TextNode(Node):
     def __init__(self, s):
         self.s = s
@@ -858,6 +873,7 @@ class TextNode(Node):
     def render(self, context):
         return self.s
 
+
 def render_value_in_context(value, context):
     """
     Converts any value to a string to become part of a rendered template. This
@@ -873,6 +889,7 @@ def render_value_in_context(value, context):
     else:
         return value
 
+
 class VariableNode(Node):
     def __init__(self, filter_expression):
         self.filter_expression = filter_expression
@@ -893,6 +910,7 @@ class VariableNode(Node):
 # Regex for token keyword arguments
 kwarg_re = re.compile(r"(?:(\w+)=)?(.+)")
 
+
 def token_kwargs(bits, parser, support_legacy=False):
     """
     A utility method for parsing token keyword arguments.
@@ -942,6 +960,7 @@ def token_kwargs(bits, parser, support_legacy=False):
             del bits[:1]
     return kwargs
 
+
 def parse_bits(parser, bits, params, varargs, varkw, defaults,
                takes_context, name):
     """
@@ -1009,6 +1028,7 @@ def parse_bits(parser, bits, params, varargs, varkw, defaults,
             (name, ", ".join("'%s'" % p for p in unhandled_params)))
     return args, kwargs
 
+
 def generic_tag_compiler(parser, token, params, varargs, varkw, defaults,
                          name, takes_context, node_class):
     """
@@ -1019,6 +1039,7 @@ def generic_tag_compiler(parser, token, params, varargs, varkw, defaults,
                               defaults, takes_context, name)
     return node_class(takes_context, args, kwargs)
 
+
 class TagHelperNode(Node):
     """
     Base class for tag helper nodes such as SimpleNode, InclusionNode and
@@ -1039,6 +1060,7 @@ class TagHelperNode(Node):
                                 for k, v in self.kwargs.items())
         return resolved_args, resolved_kwargs
 
+
 class Library(object):
     def __init__(self):
         self.filters = {}
@@ -1224,6 +1246,7 @@ class Library(object):
             return func
         return dec
 
+
 def is_library_missing(name):
     """Check if library that failed to load cannot be found under any
     templatetags directory or does exist but fails to import.
@@ -1240,6 +1263,7 @@ def is_library_missing(name):
     except ImportError:
         return is_library_missing(path)
 
+
 def import_library(taglib_module):
     """
     Load a template tag library module.
@@ -1268,6 +1292,7 @@ def import_library(taglib_module):
 
 templatetags_modules = []
 
+
 def get_templatetags_modules():
     """
     Return the list of all available template tag modules.
@@ -1290,6 +1315,7 @@ def get_templatetags_modules():
         templatetags_modules = _templatetags_modules
     return templatetags_modules
 
+
 def get_library(library_name):
     """
     Load the template library module with the given name.
diff --git a/django/template/context.py b/django/template/context.py
index d16a0a7533..ba2c3d4d07 100644
--- a/django/template/context.py
+++ b/django/template/context.py
@@ -150,6 +150,7 @@ class RenderContext(BaseContext):
             return d[key]
         return otherwise
 
+
 # This is a function rather than module-level procedural code because we only
 # want it to execute if somebody uses RequestContext.
 def get_standard_processors():
@@ -166,6 +167,7 @@ def get_standard_processors():
         _standard_context_processors = tuple(processors)
     return _standard_context_processors
 
+
 class RequestContext(Context):
     """
     This subclass of template.Context automatically populates itself using
diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py
index eb6f855cad..a4f0a89554 100644
--- a/django/template/defaultfilters.py
+++ b/django/template/defaultfilters.py
@@ -66,18 +66,21 @@ def addslashes(value):
     """
     return value.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'")
 
+
 @register.filter(is_safe=True)
 @stringfilter
 def capfirst(value):
     """Capitalizes the first character of the value."""
     return value and value[0].upper() + value[1:]
 
+
 @register.filter("escapejs")
 @stringfilter
 def escapejs_filter(value):
     """Hex encodes characters for use in JavaScript strings."""
     return escapejs(value)
 
+
 @register.filter("fix_ampersands", is_safe=True)
 @stringfilter
 def fix_ampersands_filter(value):
@@ -96,6 +99,7 @@ neg_inf = -1e200 * 1e200
 nan = (1e200 * 1e200) // (1e200 * 1e200)
 special_floats = [str(pos_inf), str(neg_inf), str(nan)]
 
+
 @register.filter(is_safe=True)
 def floatformat(text, arg=-1):
     """
@@ -179,12 +183,14 @@ def floatformat(text, arg=-1):
     except InvalidOperation:
         return input_val
 
+
 @register.filter(is_safe=True)
 @stringfilter
 def iriencode(value):
     """Escapes an IRI value for use in a URL."""
     return force_text(iri_to_uri(value))
 
+
 @register.filter(is_safe=True, needs_autoescape=True)
 @stringfilter
 def linenumbers(value, autoescape=None):
@@ -201,12 +207,14 @@ def linenumbers(value, autoescape=None):
             lines[i] = ("%0" + width + "d. %s") % (i + 1, escape(line))
     return mark_safe('\n'.join(lines))
 
+
 @register.filter(is_safe=True)
 @stringfilter
 def lower(value):
     """Converts a string into all lowercase."""
     return value.lower()
 
+
 @register.filter(is_safe=False)
 @stringfilter
 def make_list(value):
@@ -218,6 +226,7 @@ def make_list(value):
     """
     return list(value)
 
+
 @register.filter(is_safe=True)
 @stringfilter
 def slugify(value):
@@ -229,6 +238,7 @@ def slugify(value):
     from django.utils.text import slugify
     return slugify(value)
 
+
 @register.filter(is_safe=True)
 def stringformat(value, arg):
     """
@@ -245,6 +255,7 @@ def stringformat(value, arg):
     except (ValueError, TypeError):
         return ""
 
+
 @register.filter(is_safe=True)
 @stringfilter
 def title(value):
@@ -252,6 +263,7 @@ def title(value):
     t = re.sub("([a-z])'([A-Z])", lambda m: m.group(0).lower(), value.title())
     return re.sub("\d([A-Z])", lambda m: m.group(0).lower(), t)
 
+
 @register.filter(is_safe=True)
 @stringfilter
 def truncatechars(value, arg):
@@ -266,6 +278,7 @@ def truncatechars(value, arg):
         return value  # Fail silently.
     return Truncator(value).chars(length)
 
+
 @register.filter(is_safe=True)
 @stringfilter
 def truncatewords(value, arg):
@@ -282,6 +295,7 @@ def truncatewords(value, arg):
         return value  # Fail silently.
     return Truncator(value).words(length, truncate=' ...')
 
+
 @register.filter(is_safe=True)
 @stringfilter
 def truncatewords_html(value, arg):
@@ -298,12 +312,14 @@ def truncatewords_html(value, arg):
         return value  # Fail silently.
     return Truncator(value).words(length, html=True, truncate=' ...')
 
+
 @register.filter(is_safe=False)
 @stringfilter
 def upper(value):
     """Converts a string into all uppercase."""
     return value.upper()
 
+
 @register.filter(is_safe=False)
 @stringfilter
 def urlencode(value, safe=None):
@@ -320,12 +336,14 @@ def urlencode(value, safe=None):
         kwargs['safe'] = safe
     return urlquote(value, **kwargs)
 
+
 @register.filter(is_safe=True, needs_autoescape=True)
 @stringfilter
 def urlize(value, autoescape=None):
     """Converts URLs in plain text into clickable links."""
     return mark_safe(urlize_impl(value, nofollow=True, autoescape=autoescape))
 
+
 @register.filter(is_safe=True, needs_autoescape=True)
 @stringfilter
 def urlizetrunc(value, limit, autoescape=None):
@@ -338,12 +356,14 @@ def urlizetrunc(value, limit, autoescape=None):
     return mark_safe(urlize_impl(value, trim_url_limit=int(limit), nofollow=True,
                             autoescape=autoescape))
 
+
 @register.filter(is_safe=False)
 @stringfilter
 def wordcount(value):
     """Returns the number of words."""
     return len(value.split())
 
+
 @register.filter(is_safe=True)
 @stringfilter
 def wordwrap(value, arg):
@@ -354,6 +374,7 @@ def wordwrap(value, arg):
     """
     return wrap(value, int(arg))
 
+
 @register.filter(is_safe=True)
 @stringfilter
 def ljust(value, arg):
@@ -364,6 +385,7 @@ def ljust(value, arg):
     """
     return value.ljust(int(arg))
 
+
 @register.filter(is_safe=True)
 @stringfilter
 def rjust(value, arg):
@@ -374,12 +396,14 @@ def rjust(value, arg):
     """
     return value.rjust(int(arg))
 
+
 @register.filter(is_safe=True)
 @stringfilter
 def center(value, arg):
     """Centers the value in a field of a given width."""
     return value.center(int(arg))
 
+
 @register.filter
 @stringfilter
 def cut(value, arg):
@@ -392,6 +416,7 @@ def cut(value, arg):
         return mark_safe(value)
     return value
 
+
 ###################
 # HTML STRINGS    #
 ###################
@@ -404,6 +429,7 @@ def escape_filter(value):
     """
     return mark_for_escaping(value)
 
+
 @register.filter(is_safe=True)
 @stringfilter
 def force_escape(value):
@@ -414,6 +440,7 @@ def force_escape(value):
     """
     return escape(value)
 
+
 @register.filter("linebreaks", is_safe=True, needs_autoescape=True)
 @stringfilter
 def linebreaks_filter(value, autoescape=None):
@@ -425,6 +452,7 @@ def linebreaks_filter(value, autoescape=None):
     autoescape = autoescape and not isinstance(value, SafeData)
     return mark_safe(linebreaks(value, autoescape))
 
+
 @register.filter(is_safe=True, needs_autoescape=True)
 @stringfilter
 def linebreaksbr(value, autoescape=None):
@@ -438,6 +466,7 @@ def linebreaksbr(value, autoescape=None):
         value = escape(value)
     return mark_safe(value.replace('\n', '<br />'))
 
+
 @register.filter(is_safe=True)
 @stringfilter
 def safe(value):
@@ -446,6 +475,7 @@ def safe(value):
     """
     return mark_safe(value)
 
+
 @register.filter(is_safe=True)
 def safeseq(value):
     """
@@ -455,6 +485,7 @@ def safeseq(value):
     """
     return [mark_safe(force_text(obj)) for obj in value]
 
+
 @register.filter(is_safe=True)
 @stringfilter
 def removetags(value, tags):
@@ -462,12 +493,14 @@ def removetags(value, tags):
     from django.utils.html import remove_tags
     return remove_tags(value, tags)
 
+
 @register.filter(is_safe=True)
 @stringfilter
 def striptags(value):
     """Strips all [X]HTML tags."""
     return strip_tags(value)
 
+
 ###################
 # LISTS           #
 ###################
@@ -483,6 +516,7 @@ def dictsort(value, arg):
     except (TypeError, VariableDoesNotExist):
         return ''
 
+
 @register.filter(is_safe=False)
 def dictsortreversed(value, arg):
     """
@@ -494,6 +528,7 @@ def dictsortreversed(value, arg):
     except (TypeError, VariableDoesNotExist):
         return ''
 
+
 @register.filter(is_safe=False)
 def first(value):
     """Returns the first item in a list."""
@@ -502,6 +537,7 @@ def first(value):
     except IndexError:
         return ''
 
+
 @register.filter(is_safe=True, needs_autoescape=True)
 def join(value, arg, autoescape=None):
     """
@@ -516,6 +552,7 @@ def join(value, arg, autoescape=None):
         return value
     return mark_safe(data)
 
+
 @register.filter(is_safe=True)
 def last(value):
     "Returns the last item in a list"
@@ -524,6 +561,7 @@ def last(value):
     except IndexError:
         return ''
 
+
 @register.filter(is_safe=True)
 def length(value):
     """Returns the length of the value - useful for lists."""
@@ -532,6 +570,7 @@ def length(value):
     except (ValueError, TypeError):
         return ''
 
+
 @register.filter(is_safe=False)
 def length_is(value, arg):
     """Returns a boolean of whether the value's length is the argument."""
@@ -540,11 +579,13 @@ def length_is(value, arg):
     except (ValueError, TypeError):
         return ''
 
+
 @register.filter(is_safe=True)
 def random(value):
     """Returns a random item from the list."""
     return random_module.choice(value)
 
+
 @register.filter("slice", is_safe=True)
 def slice_filter(value, arg):
     """
@@ -566,6 +607,7 @@ def slice_filter(value, arg):
     except (ValueError, TypeError):
         return value  # Fail silently.
 
+
 @register.filter(is_safe=True, needs_autoescape=True)
 def unordered_list(value, autoescape=None):
     """
@@ -655,6 +697,7 @@ def unordered_list(value, autoescape=None):
     value, converted = convert_old_style_list(value)
     return mark_safe(_helper(value))
 
+
 ###################
 # INTEGERS        #
 ###################
@@ -670,6 +713,7 @@ def add(value, arg):
         except Exception:
             return ''
 
+
 @register.filter(is_safe=False)
 def get_digit(value, arg):
     """
@@ -690,6 +734,7 @@ def get_digit(value, arg):
     except IndexError:
         return 0
 
+
 ###################
 # DATES           #
 ###################
@@ -709,6 +754,7 @@ def date(value, arg=None):
         except AttributeError:
             return ''
 
+
 @register.filter(expects_localtime=True, is_safe=False)
 def time(value, arg=None):
     """Formats a time according to the given format."""
@@ -724,6 +770,7 @@ def time(value, arg=None):
         except AttributeError:
             return ''
 
+
 @register.filter("timesince", is_safe=False)
 def timesince_filter(value, arg=None):
     """Formats a date as the time since that date (i.e. "4 days, 6 hours")."""
@@ -736,6 +783,7 @@ def timesince_filter(value, arg=None):
     except (ValueError, TypeError):
         return ''
 
+
 @register.filter("timeuntil", is_safe=False)
 def timeuntil_filter(value, arg=None):
     """Formats a date as the time until that date (i.e. "4 days, 6 hours")."""
@@ -746,6 +794,7 @@ def timeuntil_filter(value, arg=None):
     except (ValueError, TypeError):
         return ''
 
+
 ###################
 # LOGIC           #
 ###################
@@ -755,6 +804,7 @@ def default(value, arg):
     """If value is unavailable, use given default."""
     return value or arg
 
+
 @register.filter(is_safe=False)
 def default_if_none(value, arg):
     """If value is None, use given default."""
@@ -762,11 +812,13 @@ def default_if_none(value, arg):
         return arg
     return value
 
+
 @register.filter(is_safe=False)
 def divisibleby(value, arg):
     """Returns True if the value is devisible by the argument."""
     return int(value) % int(arg) == 0
 
+
 @register.filter(is_safe=False)
 def yesno(value, arg=None):
     """
@@ -799,6 +851,7 @@ def yesno(value, arg=None):
         return yes
     return no
 
+
 ###################
 # MISC            #
 ###################
@@ -838,6 +891,7 @@ def filesizeformat(bytes):
 
     return avoid_wrapping(value)
 
+
 @register.filter(is_safe=False)
 def pluralize(value, arg='s'):
     """
@@ -882,11 +936,13 @@ def pluralize(value, arg='s'):
             pass
     return singular_suffix
 
+
 @register.filter("phone2numeric", is_safe=True)
 def phone2numeric_filter(value):
     """Takes a phone number and converts it in to its numerical equivalent."""
     return phone2numeric(value)
 
+
 @register.filter(is_safe=True)
 def pprint(value):
     """A wrapper around pprint.pprint -- for debugging, really."""
diff --git a/django/template/defaulttags.py b/django/template/defaulttags.py
index 2822c3d362..77d63ab256 100644
--- a/django/template/defaulttags.py
+++ b/django/template/defaulttags.py
@@ -25,6 +25,7 @@ from django.utils import timezone
 
 register = Library()
 
+
 class AutoEscapeControlNode(Node):
     """Implements the actions of the autoescape tag."""
     def __init__(self, setting, nodelist):
@@ -40,10 +41,12 @@ class AutoEscapeControlNode(Node):
         else:
             return output
 
+
 class CommentNode(Node):
     def render(self, context):
         return ''
 
+
 class CsrfTokenNode(Node):
     def render(self, context):
         csrf_token = context.get('csrf_token', None)
@@ -59,6 +62,7 @@ class CsrfTokenNode(Node):
                 warnings.warn("A {% csrf_token %} was used in a template, but the context did not provide the value.  This is usually caused by not using RequestContext.")
             return ''
 
+
 class CycleNode(Node):
     def __init__(self, cyclevars, variable_name=None, silent=False, escape=False):
         self.cyclevars = cyclevars
@@ -80,6 +84,7 @@ class CycleNode(Node):
             value = mark_safe(value)
         return render_value_in_context(value, context)
 
+
 class DebugNode(Node):
     def render(self, context):
         from pprint import pformat
@@ -88,6 +93,7 @@ class DebugNode(Node):
         output.append(pformat(sys.modules))
         return ''.join(output)
 
+
 class FilterNode(Node):
     def __init__(self, filter_expr, nodelist):
         self.filter_expr, self.nodelist = filter_expr, nodelist
@@ -113,6 +119,7 @@ class FirstOfNode(Node):
                 return render_value_in_context(value, context)
         return ''
 
+
 class ForNode(Node):
     child_nodelists = ('nodelist_loop', 'nodelist_empty')
 
@@ -207,6 +214,7 @@ class ForNode(Node):
                     context.pop()
         return mark_safe(''.join(force_text(n) for n in nodelist))
 
+
 class IfChangedNode(Node):
     child_nodelists = ('nodelist_true', 'nodelist_false')
 
@@ -251,6 +259,7 @@ class IfChangedNode(Node):
             # Using ifchanged outside loops. Effectively this is a no-op because the state is associated with 'self'.
             return context.render_context
 
+
 class IfEqualNode(Node):
     child_nodelists = ('nodelist_true', 'nodelist_false')
 
@@ -269,6 +278,7 @@ class IfEqualNode(Node):
             return self.nodelist_true.render(context)
         return self.nodelist_false.render(context)
 
+
 class IfNode(Node):
 
     def __init__(self, conditions_nodelists):
@@ -302,6 +312,7 @@ class IfNode(Node):
 
         return ''
 
+
 class RegroupNode(Node):
     def __init__(self, target, expression, var_name):
         self.target, self.expression = target, expression
@@ -328,6 +339,7 @@ class RegroupNode(Node):
         ]
         return ''
 
+
 def include_is_allowed(filepath):
     filepath = os.path.abspath(filepath)
     for root in settings.ALLOWED_INCLUDE_ROOTS:
@@ -335,6 +347,7 @@ def include_is_allowed(filepath):
             return True
     return False
 
+
 class SsiNode(Node):
     def __init__(self, filepath, parsed):
         self.filepath = filepath
@@ -364,10 +377,12 @@ class SsiNode(Node):
                     return ''  # Fail silently for invalid included templates.
         return output
 
+
 class LoadNode(Node):
     def render(self, context):
         return ''
 
+
 class NowNode(Node):
     def __init__(self, format_string):
         self.format_string = format_string
@@ -376,6 +391,7 @@ class NowNode(Node):
         tzinfo = timezone.get_current_timezone() if settings.USE_TZ else None
         return date(datetime.now(tz=tzinfo), self.format_string)
 
+
 class SpacelessNode(Node):
     def __init__(self, nodelist):
         self.nodelist = nodelist
@@ -384,6 +400,7 @@ class SpacelessNode(Node):
         from django.utils.html import strip_spaces_between_tags
         return strip_spaces_between_tags(self.nodelist.render(context).strip())
 
+
 class TemplateTagNode(Node):
     mapping = {'openblock': BLOCK_TAG_START,
                'closeblock': BLOCK_TAG_END,
@@ -401,6 +418,7 @@ class TemplateTagNode(Node):
     def render(self, context):
         return self.mapping.get(self.tagtype, '')
 
+
 class URLNode(Node):
     def __init__(self, view_name, args, kwargs, asvar):
         self.view_name = view_name
@@ -451,6 +469,7 @@ class URLNode(Node):
         else:
             return url
 
+
 class VerbatimNode(Node):
     def __init__(self, content):
         self.content = content
@@ -458,6 +477,7 @@ class VerbatimNode(Node):
     def render(self, context):
         return self.content
 
+
 class WidthRatioNode(Node):
     def __init__(self, val_expr, max_expr, max_width, asvar=None):
         self.val_expr = val_expr
@@ -490,6 +510,7 @@ class WidthRatioNode(Node):
         else:
             return result
 
+
 class WithNode(Node):
     def __init__(self, var, name, nodelist, extra_context=None):
         self.nodelist = nodelist
@@ -525,6 +546,7 @@ def autoescape(parser, token):
     parser.delete_first_token()
     return AutoEscapeControlNode((arg == 'on'), nodelist)
 
+
 @register.tag
 def comment(parser, token):
     """
@@ -533,6 +555,7 @@ def comment(parser, token):
     parser.skip_past('endcomment')
     return CommentNode()
 
+
 @register.tag
 def cycle(parser, token, escape=False):
     """
@@ -629,10 +652,12 @@ def cycle(parser, token, escape=False):
         node = CycleNode(values, escape=escape)
     return node
 
+
 @register.tag
 def csrf_token(parser, token):
     return CsrfTokenNode()
 
+
 @register.tag
 def debug(parser, token):
     """
@@ -647,6 +672,7 @@ def debug(parser, token):
     """
     return DebugNode()
 
+
 @register.tag('filter')
 def do_filter(parser, token):
     """
@@ -676,6 +702,7 @@ def do_filter(parser, token):
     parser.delete_first_token()
     return FilterNode(filter_expr, nodelist)
 
+
 @register.tag
 def firstof(parser, token, escape=False):
     """
@@ -723,6 +750,7 @@ def firstof(parser, token, escape=False):
         raise TemplateSyntaxError("'firstof' statement requires at least one argument")
     return FirstOfNode([parser.compile_filter(bit) for bit in bits], escape=escape)
 
+
 @register.tag('for')
 def do_for(parser, token):
     """
@@ -814,6 +842,7 @@ def do_for(parser, token):
         nodelist_empty = None
     return ForNode(loopvars, sequence, is_reversed, nodelist_loop, nodelist_empty)
 
+
 def do_ifequal(parser, token, negate):
     bits = list(token.split_contents())
     if len(bits) != 3:
@@ -830,6 +859,7 @@ def do_ifequal(parser, token, negate):
     val2 = parser.compile_filter(bits[2])
     return IfEqualNode(val1, val2, nodelist_true, nodelist_false, negate)
 
+
 @register.tag
 def ifequal(parser, token):
     """
@@ -849,6 +879,7 @@ def ifequal(parser, token):
     """
     return do_ifequal(parser, token, False)
 
+
 @register.tag
 def ifnotequal(parser, token):
     """
@@ -857,6 +888,7 @@ def ifnotequal(parser, token):
     """
     return do_ifequal(parser, token, True)
 
+
 class TemplateLiteral(Literal):
     def __init__(self, value, text):
         self.value = value
@@ -868,6 +900,7 @@ class TemplateLiteral(Literal):
     def eval(self, context):
         return self.value.resolve(context, ignore_failures=True)
 
+
 class TemplateIfParser(IfParser):
     error_class = TemplateSyntaxError
 
@@ -878,6 +911,7 @@ class TemplateIfParser(IfParser):
     def create_var(self, value):
         return TemplateLiteral(self.template_parser.compile_filter(value), value)
 
+
 @register.tag('if')
 def do_if(parser, token):
     """
@@ -1006,6 +1040,7 @@ def ifchanged(parser, token):
     values = [parser.compile_filter(bit) for bit in bits[1:]]
     return IfChangedNode(nodelist_true, nodelist_false, *values)
 
+
 @register.tag
 def ssi(parser, token):
     """
@@ -1036,6 +1071,7 @@ def ssi(parser, token):
     filepath = parser.compile_filter(bits[1])
     return SsiNode(filepath, parsed)
 
+
 @register.tag
 def load(parser, token):
     """
@@ -1086,6 +1122,7 @@ def load(parser, token):
                                           (taglib, e))
     return LoadNode()
 
+
 @register.tag
 def now(parser, token):
     """
@@ -1104,6 +1141,7 @@ def now(parser, token):
     format_string = bits[1][1:-1]
     return NowNode(format_string)
 
+
 @register.tag
 def regroup(parser, token):
     """
@@ -1172,6 +1210,7 @@ def regroup(parser, token):
                                        bits[3])
     return RegroupNode(target, expression, var_name)
 
+
 @register.tag
 def spaceless(parser, token):
     """
@@ -1202,6 +1241,7 @@ def spaceless(parser, token):
     parser.delete_first_token()
     return SpacelessNode(nodelist)
 
+
 @register.tag
 def templatetag(parser, token):
     """
@@ -1236,6 +1276,7 @@ def templatetag(parser, token):
                                   (tag, list(TemplateTagNode.mapping)))
     return TemplateTagNode(tag)
 
+
 @register.tag
 def url(parser, token):
     """
@@ -1331,6 +1372,7 @@ def url(parser, token):
 
     return URLNode(viewname, args, kwargs, asvar)
 
+
 @register.tag
 def verbatim(parser, token):
     """
@@ -1353,6 +1395,7 @@ def verbatim(parser, token):
     parser.delete_first_token()
     return VerbatimNode(nodelist.render(Context()))
 
+
 @register.tag
 def widthratio(parser, token):
     """
@@ -1390,6 +1433,7 @@ def widthratio(parser, token):
                           parser.compile_filter(max_width),
                           asvar=asvar)
 
+
 @register.tag('with')
 def do_with(parser, token):
     """
diff --git a/django/template/loader.py b/django/template/loader.py
index 410b03726a..3465a7141e 100644
--- a/django/template/loader.py
+++ b/django/template/loader.py
@@ -33,6 +33,7 @@ from django.utils import six
 
 template_source_loaders = None
 
+
 class BaseLoader(object):
     is_usable = False
 
@@ -71,6 +72,7 @@ class BaseLoader(object):
         """
         pass
 
+
 class LoaderOrigin(Origin):
     def __init__(self, display_name, loader, name, dirs):
         super(LoaderOrigin, self).__init__(display_name)
@@ -79,12 +81,14 @@ class LoaderOrigin(Origin):
     def reload(self):
         return self.loader(self.loadname, self.dirs)[0]
 
+
 def make_origin(display_name, loader, name, dirs):
     if settings.TEMPLATE_DEBUG and display_name:
         return LoaderOrigin(display_name, loader, name, dirs)
     else:
         return None
 
+
 def find_template_loader(loader):
     if isinstance(loader, (tuple, list)):
         loader, args = loader[0], loader[1:]
@@ -110,6 +114,7 @@ def find_template_loader(loader):
     else:
         raise ImproperlyConfigured('Loader does not define a "load_template" callable template source loader')
 
+
 def find_template(name, dirs=None):
     # Calculate template_source_loaders the first time the function is executed
     # because putting this logic in the module-level namespace may cause
@@ -130,6 +135,7 @@ def find_template(name, dirs=None):
             pass
     raise TemplateDoesNotExist(name)
 
+
 def get_template(template_name, dirs=None):
     """
     Returns a compiled Template object for the given template name,
@@ -141,6 +147,7 @@ def get_template(template_name, dirs=None):
         template = get_template_from_string(template, origin, template_name)
     return template
 
+
 def get_template_from_string(source, origin=None, name=None):
     """
     Returns a compiled Template object for the given template code,
@@ -148,6 +155,7 @@ def get_template_from_string(source, origin=None, name=None):
     """
     return Template(source, origin, name)
 
+
 def render_to_string(template_name, dictionary=None, context_instance=None,
                      dirs=None):
     """
@@ -168,6 +176,7 @@ def render_to_string(template_name, dictionary=None, context_instance=None,
     with context_instance.push(dictionary):
         return t.render(context_instance)
 
+
 def select_template(template_name_list, dirs=None):
     "Given a list of template names, returns the first that can be loaded."
     if not template_name_list:
diff --git a/django/template/loader_tags.py b/django/template/loader_tags.py
index c6bb3acadf..740b503cc5 100644
--- a/django/template/loader_tags.py
+++ b/django/template/loader_tags.py
@@ -11,9 +11,11 @@ register = Library()
 
 BLOCK_CONTEXT_KEY = 'block_context'
 
+
 class ExtendsError(Exception):
     pass
 
+
 class BlockContext(object):
     def __init__(self):
         # Dictionary of FIFO queues.
@@ -38,6 +40,7 @@ class BlockContext(object):
         except IndexError:
             return None
 
+
 class BlockNode(Node):
     def __init__(self, name, nodelist, parent=None):
         self.name, self.nodelist, self.parent = name, nodelist, parent
@@ -71,6 +74,7 @@ class BlockNode(Node):
             return mark_safe(self.render(self.context))
         return ''
 
+
 class ExtendsNode(Node):
     must_be_first = True
 
@@ -121,6 +125,7 @@ class ExtendsNode(Node):
         # the same.
         return compiled_parent._render(context)
 
+
 class IncludeNode(Node):
     def __init__(self, template, *args, **kwargs):
         self.template = template
@@ -177,6 +182,7 @@ def do_block(parser, token):
 
     return BlockNode(block_name, nodelist)
 
+
 @register.tag('extends')
 def do_extends(parser, token):
     """
@@ -197,6 +203,7 @@ def do_extends(parser, token):
         raise TemplateSyntaxError("'%s' cannot appear more than once in the same template" % bits[0])
     return ExtendsNode(nodelist, parent_name)
 
+
 @register.tag('include')
 def do_include(parser, token):
     """
diff --git a/django/template/loaders/app_directories.py b/django/template/loaders/app_directories.py
index 44983065e4..4f8ddfccac 100644
--- a/django/template/loaders/app_directories.py
+++ b/django/template/loaders/app_directories.py
@@ -32,6 +32,7 @@ for app in settings.INSTALLED_APPS:
 # It won't change, so convert it to a tuple to save memory.
 app_template_dirs = tuple(app_template_dirs)
 
+
 class Loader(BaseLoader):
     is_usable = True
 
diff --git a/django/template/loaders/cached.py b/django/template/loaders/cached.py
index 67cec49c74..646168cd1e 100644
--- a/django/template/loaders/cached.py
+++ b/django/template/loaders/cached.py
@@ -8,6 +8,7 @@ from django.template.base import TemplateDoesNotExist
 from django.template.loader import BaseLoader, get_template_from_string, find_template_loader, make_origin
 from django.utils.encoding import force_bytes
 
+
 class Loader(BaseLoader):
     is_usable = True
 
diff --git a/django/template/loaders/eggs.py b/django/template/loaders/eggs.py
index 7da180323a..04e4f73b7b 100644
--- a/django/template/loaders/eggs.py
+++ b/django/template/loaders/eggs.py
@@ -11,6 +11,7 @@ from django.template.base import TemplateDoesNotExist
 from django.template.loader import BaseLoader
 from django.utils import six
 
+
 class Loader(BaseLoader):
     is_usable = resource_string is not None
 
diff --git a/django/template/loaders/filesystem.py b/django/template/loaders/filesystem.py
index 1a7f0d2cd7..52e41ef0b9 100644
--- a/django/template/loaders/filesystem.py
+++ b/django/template/loaders/filesystem.py
@@ -7,6 +7,7 @@ from django.template.base import TemplateDoesNotExist
 from django.template.loader import BaseLoader
 from django.utils._os import safe_join
 
+
 class Loader(BaseLoader):
     is_usable = True
 
diff --git a/django/templatetags/i18n.py b/django/templatetags/i18n.py
index fc8029d738..7c54ce034c 100644
--- a/django/templatetags/i18n.py
+++ b/django/templatetags/i18n.py
@@ -195,6 +195,7 @@ def do_get_available_languages(parser, token):
         raise TemplateSyntaxError("'get_available_languages' requires 'as variable' (got %r)" % args)
     return GetAvailableLanguagesNode(args[2])
 
+
 @register.tag("get_language_info")
 def do_get_language_info(parser, token):
     """
@@ -214,6 +215,7 @@ def do_get_language_info(parser, token):
         raise TemplateSyntaxError("'%s' requires 'for string as variable' (got %r)" % (args[0], args[1:]))
     return GetLanguageInfoNode(parser.compile_filter(args[2]), args[4])
 
+
 @register.tag("get_language_info_list")
 def do_get_language_info_list(parser, token):
     """
@@ -237,18 +239,22 @@ def do_get_language_info_list(parser, token):
         raise TemplateSyntaxError("'%s' requires 'for sequence as variable' (got %r)" % (args[0], args[1:]))
     return GetLanguageInfoListNode(parser.compile_filter(args[2]), args[4])
 
+
 @register.filter
 def language_name(lang_code):
     return translation.get_language_info(lang_code)['name']
 
+
 @register.filter
 def language_name_local(lang_code):
     return translation.get_language_info(lang_code)['name_local']
 
+
 @register.filter
 def language_bidi(lang_code):
     return translation.get_language_info(lang_code)['bidi']
 
+
 @register.tag("get_current_language")
 def do_get_current_language(parser, token):
     """
@@ -268,6 +274,7 @@ def do_get_current_language(parser, token):
         raise TemplateSyntaxError("'get_current_language' requires 'as variable' (got %r)" % args)
     return GetCurrentLanguageNode(args[2])
 
+
 @register.tag("get_current_language_bidi")
 def do_get_current_language_bidi(parser, token):
     """
@@ -287,6 +294,7 @@ def do_get_current_language_bidi(parser, token):
         raise TemplateSyntaxError("'get_current_language_bidi' requires 'as variable' (got %r)" % args)
     return GetCurrentLanguageBidiNode(args[2])
 
+
 @register.tag("trans")
 def do_translate(parser, token):
     """
@@ -366,6 +374,7 @@ def do_translate(parser, token):
     return TranslateNode(parser.compile_filter(value), noop, asvar,
                          message_context)
 
+
 @register.tag("blocktrans")
 def do_block_translate(parser, token):
     """
@@ -467,6 +476,7 @@ def do_block_translate(parser, token):
     return BlockTranslateNode(extra_context, singular, plural, countervar,
             counter, message_context)
 
+
 @register.tag
 def language(parser, token):
     """
diff --git a/django/templatetags/l10n.py b/django/templatetags/l10n.py
index 667de2470e..31dae9b105 100644
--- a/django/templatetags/l10n.py
+++ b/django/templatetags/l10n.py
@@ -5,6 +5,7 @@ from django.utils.encoding import force_text
 
 register = Library()
 
+
 @register.filter(is_safe=False)
 def localize(value):
     """
@@ -13,6 +14,7 @@ def localize(value):
     """
     return force_text(formats.localize(value, use_l10n=True))
 
+
 @register.filter(is_safe=False)
 def unlocalize(value):
     """
@@ -21,6 +23,7 @@ def unlocalize(value):
     """
     return force_text(value)
 
+
 class LocalizeNode(Node):
     def __init__(self, nodelist, use_l10n):
         self.nodelist = nodelist
@@ -36,6 +39,7 @@ class LocalizeNode(Node):
         context.use_l10n = old_setting
         return output
 
+
 @register.tag('localize')
 def localize_tag(parser, token):
     """
diff --git a/docs/_ext/applyxrefs.py b/docs/_ext/applyxrefs.py
index cf5c3ac750..e9ba0fdd63 100644
--- a/docs/_ext/applyxrefs.py
+++ b/docs/_ext/applyxrefs.py
@@ -9,11 +9,13 @@ DONT_TOUCH = (
     './index.txt',
 )
 
+
 def target_name(fn):
     if fn.endswith('.txt'):
         fn = fn[:-4]
     return '_' + fn.lstrip('./').replace('/', '-')
 
+
 def process_file(fn, lines):
     lines.insert(0, '\n')
     lines.insert(0, '.. %s:\n' % target_name(fn))
@@ -23,6 +25,7 @@ def process_file(fn, lines):
     except IOError:
         print("Can't open %s for writing. Not touching it." % fn)
 
+
 def has_target(fn):
     try:
         with open(fn, 'r') as fp:
@@ -39,6 +42,7 @@ def has_target(fn):
         return (True, None)
     return (False, lines)
 
+
 def main(argv=None):
     if argv is None:
         argv = sys.argv
diff --git a/docs/_ext/djangodocs.py b/docs/_ext/djangodocs.py
index 523c86df52..6a9659171d 100644
--- a/docs/_ext/djangodocs.py
+++ b/docs/_ext/djangodocs.py
@@ -293,6 +293,7 @@ class DjangoHTMLTranslator(SmartyPantsHTMLTranslator):
         SmartyPantsHTMLTranslator.visit_section(self, node)
         node['ids'] = old_ids
 
+
 def parse_django_admin_node(env, sig, signode):
     command = sig.split(' ')[0]
     env._django_curr_admin_command = command
@@ -300,6 +301,7 @@ def parse_django_admin_node(env, sig, signode):
     signode += addnodes.desc_name(title, title)
     return sig
 
+
 def parse_django_adminopt_node(env, sig, signode):
     """A copy of sphinx.directives.CmdoptionDesc.parse_signature()"""
     from sphinx.domains.std import option_desc_re
diff --git a/docs/_ext/literals_to_xrefs.py b/docs/_ext/literals_to_xrefs.py
index 6c12ea43f3..268d084d42 100644
--- a/docs/_ext/literals_to_xrefs.py
+++ b/docs/_ext/literals_to_xrefs.py
@@ -37,6 +37,7 @@ ALWAYS_SKIP = [
     "False",
 ]
 
+
 def fixliterals(fname):
     with open(fname) as fp:
         data = fp.read()
diff --git a/extras/csrf_migration_helper.py b/extras/csrf_migration_helper.py
index ffa8b0b924..818c1263b7 100755
--- a/extras/csrf_migration_helper.py
+++ b/extras/csrf_migration_helper.py
@@ -137,6 +137,7 @@ _POST_FORM_RE = \
 _FORM_CLOSE_RE = re.compile(r'</form\s*>')
 _TOKEN_RE = re.compile('\{% csrf_token')
 
+
 def get_template_dirs():
     """
     Returns a set of all directories that contain project templates.
@@ -153,6 +154,7 @@ def get_template_dirs():
         dirs.update(app_template_dirs)
     return dirs
 
+
 def make_template_info(filename, root_dirs):
     """
     Creates a Template object for a filename, calculating the possible
@@ -241,6 +243,7 @@ class Template(object):
     def __hash__(self):
         return hash(self.absolute_filename)
 
+
 def get_templates(dirs):
     """
     Returns all files in dirs that have template extensions, as Template
@@ -257,6 +260,7 @@ def get_templates(dirs):
                     templates.add(t)
     return templates
 
+
 def get_python_code(paths):
     """
     Returns all Python code, as a list of tuples, each one being:
@@ -275,6 +279,7 @@ def get_python_code(paths):
                     retval.append((fn, content))
     return retval
 
+
 def search_python_list(python_code, template_names):
     """
     Searches python code for a list of template names.
@@ -286,6 +291,7 @@ def search_python_list(python_code, template_names):
         retval.update(search_python(python_code, tn))
     return sorted(retval)
 
+
 def search_python(python_code, template_name):
     """
     Searches Python code for a template name.
@@ -300,6 +306,7 @@ def search_python(python_code, template_name):
                 retval.append((fn, ln + 1))
     return retval
 
+
 def main(pythonpaths):
     template_dirs = get_template_dirs()
     templates = get_templates(template_dirs)
diff --git a/scripts/manage_translations.py b/scripts/manage_translations.py
index 5460eef25e..f256f7a1e7 100644
--- a/scripts/manage_translations.py
+++ b/scripts/manage_translations.py
@@ -27,6 +27,7 @@ from django.core.management import call_command
 
 HAVE_JS = ['admin']
 
+
 def _get_locale_dirs(include_core=True):
     """
     Return a tuple (contrib name, absolute path) for all locale directories,
@@ -44,6 +45,7 @@ def _get_locale_dirs(include_core=True):
         dirs.insert(0, ('core', os.path.join(os.getcwd(), 'django', 'conf', 'locale')))
     return dirs
 
+
 def _tx_resource_for_name(name):
     """ Return the Transifex resource name """
     if name == 'core':
@@ -51,6 +53,7 @@ def _tx_resource_for_name(name):
     else:
         return "django-core.contrib-%s" % name
 
+
 def _check_diff(cat_name, base_path):
     """
     Output the approximate number of changed/added strings in the en catalog.

From 7a61c68c50d3837c50e35c252fd76220f08b5290 Mon Sep 17 00:00:00 2001
From: Jason Myers <jason@jasonamyers.com>
Date: Sat, 2 Nov 2013 23:36:09 -0500
Subject: [PATCH 8/8] PEP8 cleanup

Signed-off-by: Jason Myers <jason@jasonamyers.com>
---
 tests/admin_changelist/models.py              |  15 ++
 tests/admin_custom_urls/models.py             |   2 +
 tests/admin_docs/views.py                     |   2 +
 tests/admin_filters/models.py                 |   1 +
 tests/admin_inlines/admin.py                  |   3 +
 tests/admin_inlines/models.py                 |  21 ++
 tests/admin_inlines/tests.py                  |  24 +--
 tests/admin_ordering/models.py                |   4 +
 tests/admin_ordering/tests.py                 |   1 +
 tests/admin_scripts/tests.py                  |   9 +
 tests/admin_util/models.py                    |   5 +
 tests/admin_util/tests.py                     |   6 +-
 tests/admin_validation/tests.py               |   3 +
 tests/admin_views/models.py                   |  22 +++
 tests/admin_views/tests.py                    |  35 ++--
 tests/admin_views/views.py                    |   1 +
 tests/admin_widgets/models.py                 |  14 ++
 tests/admin_widgets/tests.py                  |  16 +-
 tests/aggregation/models.py                   |   3 +
 tests/aggregation_regress/models.py           |   6 +-
 tests/backends/tests.py                       |  18 +-
 tests/basic/models.py                         |   2 +
 tests/basic/tests.py                          |  48 +++--
 tests/bug639/models.py                        |   2 +
 tests/bulk_create/models.py                   |   5 +
 tests/cache/closeable_cache.py                |   1 +
 tests/cache/liberal_backend.py                |   1 +
 tests/cache/models.py                         |   1 +
 tests/cache/tests.py                          |   6 +
 tests/check/models.py                         |   2 +
 tests/check/tests.py                          |   1 +
 tests/choices/models.py                       |   1 +
 tests/commands_sql/tests.py                   |   1 +
 tests/conditional_processing/tests.py         |   1 +
 tests/conditional_processing/views.py         |   4 +
 tests/contenttypes_tests/models.py            |   2 +
 tests/contenttypes_tests/tests.py             |   1 +
 tests/csrf_tests/tests.py                     |   5 +
 tests/custom_columns/models.py                |   1 +
 tests/custom_columns_regress/models.py        |   1 +
 tests/custom_columns_regress/tests.py         |   1 +
 tests/custom_managers/models.py               |  10 +
 tests/custom_managers_regress/models.py       |   3 +
 tests/custom_pk/fields.py                     |   1 +
 tests/custom_pk/models.py                     |   4 +-
 tests/datatypes/models.py                     |   1 +
 tests/dates/models.py                         |   2 +
 tests/datetimes/models.py                     |   2 +
 tests/db_typecasts/tests.py                   |   1 +
 tests/defer_regress/tests.py                  |   1 +
 tests/delete/models.py                        |   6 +
 tests/delete/tests.py                         |   3 +-
 tests/delete_regress/models.py                |  28 +++
 tests/delete_regress/tests.py                 |   3 +-
 tests/dispatch/tests/test_dispatcher.py       |   8 +-
 tests/dispatch/tests/test_saferef.py          |   4 +
 tests/distinct_on_fields/models.py            |   5 +
 tests/distinct_on_fields/tests.py             |   3 +-
 tests/expressions/models.py                   |   1 +
 tests/expressions_regress/models.py           |   1 +
 tests/expressions_regress/tests.py            |  70 +++----
 tests/extra_regress/models.py                 |   2 +
 tests/field_subclassing/fields.py             |   2 +
 tests/field_subclassing/models.py             |   2 +
 tests/file_storage/models.py                  |   1 +
 tests/file_storage/tests.py                   |   5 +
 tests/file_uploads/tests.py                   |   3 +-
 tests/file_uploads/uploadhandler.py           |   4 +-
 tests/file_uploads/views.py                   |  10 +
 tests/fixtures/models.py                      |   8 +
 .../fixtures_model_package/models/__init__.py |   1 +
 tests/fixtures_regress/models.py              |   1 +
 tests/force_insert_update/models.py           |   4 +
 tests/foreign_object/models.py                |  11 ++
 tests/foreign_object/tests.py                 |   2 +
 tests/forms_tests/models.py                   |   5 +-
 .../forms_tests/tests/test_error_messages.py  |   1 +
 tests/forms_tests/tests/test_extra.py         |   3 +
 tests/forms_tests/tests/test_formsets.py      |   6 +-
 tests/forms_tests/tests/test_input_formats.py |   2 +
 tests/forms_tests/tests/test_widgets.py       |   4 +-
 tests/forms_tests/tests/tests.py              |   1 +
 tests/generic_inline_admin/admin.py           |   1 +
 tests/generic_inline_admin/models.py          |   2 +
 tests/generic_inline_admin/tests.py           |   3 +
 tests/generic_relations/tests.py              |   2 +
 tests/generic_relations_regress/models.py     |  25 +++
 tests/generic_views/models.py                 |   4 +
 tests/generic_views/test_base.py              |   1 +
 tests/generic_views/test_dates.py             |   3 +-
 tests/generic_views/views.py                  |  19 ++
 tests/get_object_or_404/models.py             |   2 +
 tests/get_or_create_regress/models.py         |   2 +
 tests/handlers/views.py                       |   5 +
 tests/httpwrappers/tests.py                   |   5 +
 tests/i18n/forms.py                           |   2 +
 tests/i18n/models.py                          |   1 +
 tests/i18n/test_extraction.py                 |  18 +-
 tests/i18n/tests.py                           |   3 +
 tests/inline_formsets/models.py               |   4 +
 tests/inspectdb/models.py                     |   6 +
 tests/inspectdb/tests.py                      |   3 +-
 tests/known_related_objects/models.py         |   4 +
 tests/known_related_objects/tests.py          |   1 +
 tests/logging_tests/tests.py                  |   2 +
 tests/lookup/models.py                        |   5 +
 tests/m2m_and_m2o/models.py                   |   2 +
 tests/m2m_and_m2o/tests.py                    |   3 +-
 tests/m2m_intermediary/models.py              |   2 +
 tests/m2m_regress/models.py                   |   9 +
 tests/m2m_signals/models.py                   |   3 +
 tests/m2m_through/models.py                   |   6 +
 tests/m2m_through_regress/models.py           |   9 +
 tests/m2o_recursive/models.py                 |   1 +
 tests/m2o_recursive/tests.py                  |   1 +
 tests/many_to_many/models.py                  |   1 +
 tests/many_to_one/models.py                   |   1 +
 tests/many_to_one_null/models.py              |   1 +
 tests/many_to_one_regress/models.py           |  11 +-
 tests/max_lengths/models.py                   |   1 +
 tests/max_lengths/tests.py                    |   1 +
 tests/middleware/tests.py                     |  12 +-
 tests/middleware_exceptions/tests.py          |   2 +
 tests/middleware_exceptions/views.py          |   6 +
 tests/model_fields/tests.py                   |   8 +
 tests/model_forms/models.py                   |  28 +++
 .../models.py                                 |   1 +
 tests/multiple_database/tests.py              | 180 ++++++++++--------
 128 files changed, 739 insertions(+), 206 deletions(-)

diff --git a/tests/admin_changelist/models.py b/tests/admin_changelist/models.py
index 242e4b7b6c..76249b2cd3 100644
--- a/tests/admin_changelist/models.py
+++ b/tests/admin_changelist/models.py
@@ -1,26 +1,32 @@
 from django.db import models
 from django.utils.encoding import python_2_unicode_compatible
 
+
 class Event(models.Model):
     # Oracle can have problems with a column named "date"
     date = models.DateField(db_column="event_date")
 
+
 class Parent(models.Model):
     name = models.CharField(max_length=128)
 
+
 class Child(models.Model):
     parent = models.ForeignKey(Parent, editable=False, null=True)
     name = models.CharField(max_length=30, blank=True)
     age = models.IntegerField(null=True, blank=True)
 
+
 class Genre(models.Model):
     name = models.CharField(max_length=20)
 
+
 class Band(models.Model):
     name = models.CharField(max_length=20)
     nr_of_members = models.PositiveIntegerField()
     genres = models.ManyToManyField(Genre)
 
+
 @python_2_unicode_compatible
 class Musician(models.Model):
     name = models.CharField(max_length=30)
@@ -28,6 +34,7 @@ class Musician(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Group(models.Model):
     name = models.CharField(max_length=30)
@@ -36,26 +43,32 @@ class Group(models.Model):
     def __str__(self):
         return self.name
 
+
 class Membership(models.Model):
     music = models.ForeignKey(Musician)
     group = models.ForeignKey(Group)
     role = models.CharField(max_length=15)
 
+
 class Quartet(Group):
     pass
 
+
 class ChordsMusician(Musician):
     pass
 
+
 class ChordsBand(models.Model):
     name = models.CharField(max_length=30)
     members = models.ManyToManyField(ChordsMusician, through='Invitation')
 
+
 class Invitation(models.Model):
     player = models.ForeignKey(ChordsMusician)
     band = models.ForeignKey(ChordsBand)
     instrument = models.CharField(max_length=15)
 
+
 class Swallow(models.Model):
     origin = models.CharField(max_length=255)
     load = models.FloatField()
@@ -77,6 +90,7 @@ class OrderedObjectManager(models.Manager):
     def get_queryset(self):
         return super(OrderedObjectManager, self).get_queryset().order_by('number')
 
+
 class OrderedObject(models.Model):
     """
     Model with Manager that defines a default order.
@@ -88,5 +102,6 @@ class OrderedObject(models.Model):
 
     objects = OrderedObjectManager()
 
+
 class CustomIdUser(models.Model):
     uuid = models.AutoField(primary_key=True)
diff --git a/tests/admin_custom_urls/models.py b/tests/admin_custom_urls/models.py
index 55fc064835..121e03b860 100644
--- a/tests/admin_custom_urls/models.py
+++ b/tests/admin_custom_urls/models.py
@@ -54,6 +54,7 @@ class ActionAdmin(admin.ModelAdmin):
 class Person(models.Model):
     name = models.CharField(max_length=20)
 
+
 class PersonAdmin(admin.ModelAdmin):
 
     def response_post_save_add(self, request, obj):
@@ -68,6 +69,7 @@ class PersonAdmin(admin.ModelAdmin):
 class Car(models.Model):
     name = models.CharField(max_length=20)
 
+
 class CarAdmin(admin.ModelAdmin):
 
     def response_add(self, request, obj, post_url_continue=None):
diff --git a/tests/admin_docs/views.py b/tests/admin_docs/views.py
index e47177c37f..9a2f81d45c 100644
--- a/tests/admin_docs/views.py
+++ b/tests/admin_docs/views.py
@@ -5,9 +5,11 @@ from django.contrib.admindocs.middleware import XViewMiddleware
 
 xview_dec = decorator_from_middleware(XViewMiddleware)
 
+
 def xview(request):
     return HttpResponse()
 
+
 class XViewClass(View):
     def get(self, request):
         return HttpResponse()
diff --git a/tests/admin_filters/models.py b/tests/admin_filters/models.py
index bd2e4e5e98..4634ebb535 100644
--- a/tests/admin_filters/models.py
+++ b/tests/admin_filters/models.py
@@ -27,6 +27,7 @@ class Department(models.Model):
     def __str__(self):
         return self.description
 
+
 @python_2_unicode_compatible
 class Employee(models.Model):
     department = models.ForeignKey(Department, to_field="code")
diff --git a/tests/admin_inlines/admin.py b/tests/admin_inlines/admin.py
index da5ddc03b3..b46a045052 100644
--- a/tests/admin_inlines/admin.py
+++ b/tests/admin_inlines/admin.py
@@ -153,6 +153,7 @@ class ChildModel1Inline(admin.TabularInline):
 class ChildModel2Inline(admin.StackedInline):
     model = ChildModel2
 
+
 # admin for #19425 and #18388
 class BinaryTreeAdmin(admin.TabularInline):
     model = BinaryTree
@@ -169,10 +170,12 @@ class BinaryTreeAdmin(admin.TabularInline):
             return max_num - obj.binarytree_set.count()
         return max_num
 
+
 # admin for #19524
 class SightingInline(admin.TabularInline):
     model = Sighting
 
+
 # admin and form for #18263
 class SomeChildModelForm(forms.ModelForm):
 
diff --git a/tests/admin_inlines/models.py b/tests/admin_inlines/models.py
index 36e9e8e54d..d4374ec14b 100644
--- a/tests/admin_inlines/models.py
+++ b/tests/admin_inlines/models.py
@@ -89,6 +89,7 @@ class Inner2(models.Model):
     dummy = models.IntegerField()
     holder = models.ForeignKey(Holder2)
 
+
 class Holder3(models.Model):
     dummy = models.IntegerField()
 
@@ -99,38 +100,47 @@ class Inner3(models.Model):
 
 # Models for ticket #8190
 
+
 class Holder4(models.Model):
     dummy = models.IntegerField()
 
+
 class Inner4Stacked(models.Model):
     dummy = models.IntegerField(help_text="Awesome stacked help text is awesome.")
     holder = models.ForeignKey(Holder4)
 
+
 class Inner4Tabular(models.Model):
     dummy = models.IntegerField(help_text="Awesome tabular help text is awesome.")
     holder = models.ForeignKey(Holder4)
 
 # Models for #12749
 
+
 class Person(models.Model):
     firstname = models.CharField(max_length=15)
 
+
 class OutfitItem(models.Model):
     name = models.CharField(max_length=15)
 
+
 class Fashionista(models.Model):
     person = models.OneToOneField(Person, primary_key=True)
     weaknesses = models.ManyToManyField(OutfitItem, through='ShoppingWeakness', blank=True)
 
+
 class ShoppingWeakness(models.Model):
     fashionista = models.ForeignKey(Fashionista)
     item = models.ForeignKey(OutfitItem)
 
 # Models for #13510
 
+
 class TitleCollection(models.Model):
     pass
 
+
 class Title(models.Model):
     collection = models.ForeignKey(TitleCollection, blank=True, null=True)
     title1 = models.CharField(max_length=100)
@@ -138,19 +148,24 @@ class Title(models.Model):
 
 # Models for #15424
 
+
 class Poll(models.Model):
     name = models.CharField(max_length=40)
 
+
 class Question(models.Model):
     poll = models.ForeignKey(Poll)
 
+
 class Novel(models.Model):
     name = models.CharField(max_length=40)
 
+
 class Chapter(models.Model):
     name = models.CharField(max_length=40)
     novel = models.ForeignKey(Novel)
 
+
 class FootNote(models.Model):
     """
     Model added for ticket 19838
@@ -160,6 +175,7 @@ class FootNote(models.Model):
 
 # Models for #16838
 
+
 class CapoFamiglia(models.Model):
     name = models.CharField(max_length=100)
 
@@ -211,12 +227,15 @@ class BinaryTree(models.Model):
 
 # Models for #19524
 
+
 class LifeForm(models.Model):
     pass
 
+
 class ExtraTerrestrial(LifeForm):
     name = models.CharField(max_length=100)
 
+
 class Sighting(models.Model):
     et = models.ForeignKey(ExtraTerrestrial)
     place = models.CharField(max_length=100)
@@ -234,9 +253,11 @@ class SomeChildModel(models.Model):
 
 # Other models
 
+
 class ProfileCollection(models.Model):
     pass
 
+
 class Profile(models.Model):
     collection = models.ForeignKey(ProfileCollection, blank=True, null=True)
     first_name = models.CharField(max_length=100)
diff --git a/tests/admin_inlines/tests.py b/tests/admin_inlines/tests.py
index 2d0a7edd10..8d6fc97426 100644
--- a/tests/admin_inlines/tests.py
+++ b/tests/admin_inlines/tests.py
@@ -279,6 +279,7 @@ class TestInlineMedia(TestCase):
         self.assertContains(response, 'my_awesome_admin_scripts.js')
         self.assertContains(response, 'my_awesome_inline_scripts.js')
 
+
 class TestInlineAdminForm(TestCase):
     urls = "admin_inlines.urls"
 
@@ -465,9 +466,9 @@ class TestInlinePermissions(TestCase):
         self.assertContains(response, 'Add another Inner2')
         # 3 extra forms only, not the existing instance form
         self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" '
-                                'value="3" name="inner2_set-TOTAL_FORMS" />', html=True)
+            'value="3" name="inner2_set-TOTAL_FORMS" />', html=True)
         self.assertNotContains(response, '<input type="hidden" id="id_inner2_set-0-id" '
-                            'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
+            'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
 
     def test_inline_change_fk_change_perm(self):
         permission = Permission.objects.get(codename='change_inner2', content_type=self.inner_ct)
@@ -477,12 +478,12 @@ class TestInlinePermissions(TestCase):
         self.assertContains(response, '<h2>Inner2s</h2>')
         # Just the one form for existing instances
         self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" '
-                                'value="1" name="inner2_set-TOTAL_FORMS" />', html=True)
+            'value="1" name="inner2_set-TOTAL_FORMS" />', html=True)
         self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" '
-                            'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
+            'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
         # max-num 0 means we can't add new ones
         self.assertContains(response, '<input type="hidden" id="id_inner2_set-MAX_NUM_FORMS" '
-                                'value="0" name="inner2_set-MAX_NUM_FORMS" />', html=True)
+            'value="0" name="inner2_set-MAX_NUM_FORMS" />', html=True)
 
     def test_inline_change_fk_add_change_perm(self):
         permission = Permission.objects.get(codename='add_inner2', content_type=self.inner_ct)
@@ -494,9 +495,9 @@ class TestInlinePermissions(TestCase):
         self.assertContains(response, '<h2>Inner2s</h2>')
         # One form for existing instance and three extra for new
         self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" '
-                                'value="4" name="inner2_set-TOTAL_FORMS" />', html=True)
+            'value="4" name="inner2_set-TOTAL_FORMS" />', html=True)
         self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" '
-                            'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
+            'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
 
     def test_inline_change_fk_change_del_perm(self):
         permission = Permission.objects.get(codename='change_inner2', content_type=self.inner_ct)
@@ -508,9 +509,9 @@ class TestInlinePermissions(TestCase):
         self.assertContains(response, '<h2>Inner2s</h2>')
         # One form for existing instance only, no new
         self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" '
-                                'value="1" name="inner2_set-TOTAL_FORMS" />', html=True)
+            'value="1" name="inner2_set-TOTAL_FORMS" />', html=True)
         self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" '
-                            'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
+            'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
         self.assertContains(response, 'id="id_inner2_set-0-DELETE"')
 
     def test_inline_change_fk_all_perms(self):
@@ -525,9 +526,9 @@ class TestInlinePermissions(TestCase):
         self.assertContains(response, '<h2>Inner2s</h2>')
         # One form for existing instance only, three for new
         self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" '
-                                'value="4" name="inner2_set-TOTAL_FORMS" />', html=True)
+            'value="4" name="inner2_set-TOTAL_FORMS" />', html=True)
         self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" '
-                            'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
+            'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
         self.assertContains(response, 'id="id_inner2_set-0-DELETE"')
 
 
@@ -698,5 +699,6 @@ class SeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
 class SeleniumChromeTests(SeleniumFirefoxTests):
     webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
 
+
 class SeleniumIETests(SeleniumFirefoxTests):
     webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
diff --git a/tests/admin_ordering/models.py b/tests/admin_ordering/models.py
index 3da52b1b00..fb99d2dac5 100644
--- a/tests/admin_ordering/models.py
+++ b/tests/admin_ordering/models.py
@@ -11,6 +11,7 @@ class Band(models.Model):
     class Meta:
         ordering = ('name',)
 
+
 class Song(models.Model):
     band = models.ForeignKey(Band)
     name = models.CharField(max_length=100)
@@ -20,13 +21,16 @@ class Song(models.Model):
     class Meta:
         ordering = ('name',)
 
+
 class SongInlineDefaultOrdering(admin.StackedInline):
     model = Song
 
+
 class SongInlineNewOrdering(admin.StackedInline):
     model = Song
     ordering = ('duration', )
 
+
 class DynOrderingBandAdmin(admin.ModelAdmin):
 
     def get_ordering(self, request):
diff --git a/tests/admin_ordering/tests.py b/tests/admin_ordering/tests.py
index 0085b35586..e58e3b5abf 100644
--- a/tests/admin_ordering/tests.py
+++ b/tests/admin_ordering/tests.py
@@ -12,6 +12,7 @@ from .models import (Band, Song, SongInlineDefaultOrdering,
 class MockRequest(object):
     pass
 
+
 class MockSuperUser(object):
     def has_perm(self, perm):
         return True
diff --git a/tests/admin_scripts/tests.py b/tests/admin_scripts/tests.py
index dae1314982..73a91b6e7b 100644
--- a/tests/admin_scripts/tests.py
+++ b/tests/admin_scripts/tests.py
@@ -289,6 +289,7 @@ class DjangoAdminDefaultSettings(AdminScriptTestCase):
         self.assertNoOutput(err)
         self.assertOutput(out, "EXECUTE:NoArgsCommand")
 
+
 class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase):
     """A series of tests for django-admin.py when using a settings.py file that
     contains the test application specified using a full path.
@@ -355,6 +356,7 @@ class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase):
         self.assertNoOutput(err)
         self.assertOutput(out, "EXECUTE:NoArgsCommand")
 
+
 class DjangoAdminMinimalSettings(AdminScriptTestCase):
     """A series of tests for django-admin.py when using a settings.py file that
     doesn't contain the test application.
@@ -421,6 +423,7 @@ class DjangoAdminMinimalSettings(AdminScriptTestCase):
         self.assertNoOutput(out)
         self.assertOutput(err, "Unknown command: 'noargs_command'")
 
+
 class DjangoAdminAlternateSettings(AdminScriptTestCase):
     """A series of tests for django-admin.py when using a settings file
     with a name other than 'settings.py'.
@@ -796,6 +799,7 @@ class ManageFullPathDefaultSettings(AdminScriptTestCase):
         self.assertNoOutput(err)
         self.assertOutput(out, "EXECUTE:NoArgsCommand")
 
+
 class ManageMinimalSettings(AdminScriptTestCase):
     """A series of tests for manage.py when using a settings.py file that
     doesn't contain the test application.
@@ -862,6 +866,7 @@ class ManageMinimalSettings(AdminScriptTestCase):
         self.assertNoOutput(out)
         self.assertOutput(err, "Unknown command: 'noargs_command'")
 
+
 class ManageAlternateSettings(AdminScriptTestCase):
     """A series of tests for manage.py when using a settings file
     with a name other than 'settings.py'.
@@ -1121,6 +1126,7 @@ class CustomTestRunner(DiscoverRunner):
     def run_tests(self, test_labels, extra_tests=None, **kwargs):
         pass
 
+
 class ManageTestCommand(AdminScriptTestCase):
     def setUp(self):
         from django.core.management.commands.test import Command as TestCommand
@@ -1214,6 +1220,7 @@ class ManageRunserver(AdminScriptTestCase):
         self.cmd.handle(addrport="deadbeef:7654")
         self.assertServerSettings('deadbeef', '7654')
 
+
 class ManageRunserverEmptyAllowedHosts(AdminScriptTestCase):
     def setUp(self):
         self.write_settings('settings.py', sdict={
@@ -1464,6 +1471,7 @@ class CommandTypes(AdminScriptTestCase):
         self.assertOutput(out, str_prefix("EXECUTE:LabelCommand label=testlabel, options=[('no_color', False), ('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', %(_)s'1')]"))
         self.assertOutput(out, str_prefix("EXECUTE:LabelCommand label=anotherlabel, options=[('no_color', False), ('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', %(_)s'1')]"))
 
+
 class ArgumentOrder(AdminScriptTestCase):
     """Tests for 2-stage argument parsing scheme.
 
@@ -1751,6 +1759,7 @@ class DiffSettings(AdminScriptTestCase):
         self.assertNoOutput(err)
         self.assertOutput(out, "### STATIC_URL = None")
 
+
 class Dumpdata(AdminScriptTestCase):
     """Tests for dumpdata management command."""
 
diff --git a/tests/admin_util/models.py b/tests/admin_util/models.py
index 32a6cd6291..5e86f55a3a 100644
--- a/tests/admin_util/models.py
+++ b/tests/admin_util/models.py
@@ -19,6 +19,7 @@ class Article(models.Model):
         return "nothing"
     test_from_model_with_override.short_description = "not What you Expect"
 
+
 @python_2_unicode_compatible
 class Count(models.Model):
     num = models.PositiveSmallIntegerField()
@@ -27,12 +28,15 @@ class Count(models.Model):
     def __str__(self):
         return six.text_type(self.num)
 
+
 class Event(models.Model):
     date = models.DateTimeField(auto_now_add=True)
 
+
 class Location(models.Model):
     event = models.OneToOneField(Event, verbose_name='awesome event')
 
+
 class Guest(models.Model):
     event = models.OneToOneField(Event)
     name = models.CharField(max_length=255)
@@ -40,5 +44,6 @@ class Guest(models.Model):
     class Meta:
         verbose_name = "awesome guest"
 
+
 class EventGuide(models.Model):
     event = models.ForeignKey(Event, on_delete=models.DO_NOTHING)
diff --git a/tests/admin_util/tests.py b/tests/admin_util/tests.py
index 915dfced08..b978a4ab05 100644
--- a/tests/admin_util/tests.py
+++ b/tests/admin_util/tests.py
@@ -80,6 +80,7 @@ class NestedObjectsTests(TestCase):
             # One for Location, one for Guest, and no query for EventGuide
             n.collect(objs)
 
+
 class UtilTests(SimpleTestCase):
     def test_values_from_lookup_field(self):
         """
@@ -228,9 +229,8 @@ class UtilTests(SimpleTestCase):
         )
         self.assertEqual(
             label_for_field("test_from_model", Article,
-                model_admin = MockModelAdmin,
-                return_attr = True
-            ),
+                model_admin=MockModelAdmin,
+                return_attr=True),
             ("not Really the Model", MockModelAdmin.test_from_model)
         )
 
diff --git a/tests/admin_validation/tests.py b/tests/admin_validation/tests.py
index f1346647ee..5e38af82f0 100644
--- a/tests/admin_validation/tests.py
+++ b/tests/admin_validation/tests.py
@@ -12,10 +12,12 @@ from .models import Song, Book, Album, TwoAlbumFKAndAnE, City
 class SongForm(forms.ModelForm):
     pass
 
+
 class ValidFields(admin.ModelAdmin):
     form = SongForm
     fields = ['title']
 
+
 class ValidFormFieldsets(admin.ModelAdmin):
     def get_form(self, request, obj=None, **kwargs):
         class ExtraFieldForm(SongForm):
@@ -28,6 +30,7 @@ class ValidFormFieldsets(admin.ModelAdmin):
         }),
     )
 
+
 class ValidationTestCase(TestCase):
 
     def test_readonly_and_editable(self):
diff --git a/tests/admin_views/models.py b/tests/admin_views/models.py
index 4dcca9a4cb..e2b6a00261 100644
--- a/tests/admin_views/models.py
+++ b/tests/admin_views/models.py
@@ -120,11 +120,13 @@ class Color(models.Model):
     def __str__(self):
         return self.value
 
+
 # we replicate Color to register with another ModelAdmin
 class Color2(Color):
     class Meta:
         proxy = True
 
+
 @python_2_unicode_compatible
 class Thing(models.Model):
     title = models.CharField(max_length=20)
@@ -613,10 +615,12 @@ class PrePopulatedPostLargeSlug(models.Model):
     published = models.BooleanField(default=False)
     slug = models.SlugField(max_length=1000)
 
+
 class AdminOrderedField(models.Model):
     order = models.IntegerField()
     stuff = models.CharField(max_length=200)
 
+
 class AdminOrderedModelMethod(models.Model):
     order = models.IntegerField()
     stuff = models.CharField(max_length=200)
@@ -625,14 +629,17 @@ class AdminOrderedModelMethod(models.Model):
         return self.order
     some_order.admin_order_field = 'order'
 
+
 class AdminOrderedAdminMethod(models.Model):
     order = models.IntegerField()
     stuff = models.CharField(max_length=200)
 
+
 class AdminOrderedCallable(models.Model):
     order = models.IntegerField()
     stuff = models.CharField(max_length=200)
 
+
 @python_2_unicode_compatible
 class Report(models.Model):
     title = models.CharField(max_length=100)
@@ -651,6 +658,7 @@ class MainPrepopulated(models.Model):
     slug1 = models.SlugField(blank=True)
     slug2 = models.SlugField(blank=True)
 
+
 class RelatedPrepopulated(models.Model):
     parent = models.ForeignKey(MainPrepopulated)
     name = models.CharField(max_length=75)
@@ -671,6 +679,7 @@ class UnorderedObject(models.Model):
     name = models.CharField(max_length=255)
     bool = models.BooleanField(default=True)
 
+
 class UndeletableObject(models.Model):
     """
     Model whose show_delete in admin change_view has been disabled
@@ -678,30 +687,36 @@ class UndeletableObject(models.Model):
     """
     name = models.CharField(max_length=255)
 
+
 class UnchangeableObject(models.Model):
     """
     Model whose change_view is disabled in admin
     Refs #20640.
     """
 
+
 class UserMessenger(models.Model):
     """
     Dummy class for testing message_user functions on ModelAdmin
     """
 
+
 class Simple(models.Model):
     """
     Simple model with nothing on it for use in testing
     """
 
+
 class Choice(models.Model):
     choice = models.IntegerField(blank=True, null=True,
         choices=((1, 'Yes'), (0, 'No'), (None, 'No opinion')))
 
+
 class _Manager(models.Manager):
     def get_queryset(self):
         return super(_Manager, self).get_queryset().filter(pk__gt=1)
 
+
 class FilteredManager(models.Model):
     def __str__(self):
         return "PK=%d" % self.pk
@@ -709,26 +724,33 @@ class FilteredManager(models.Model):
     pk_gt_1 = _Manager()
     objects = models.Manager()
 
+
 class EmptyModelVisible(models.Model):
     """ See ticket #11277. """
 
+
 class EmptyModelHidden(models.Model):
     """ See ticket #11277. """
 
+
 class EmptyModelMixin(models.Model):
     """ See ticket #11277. """
 
+
 class State(models.Model):
     name = models.CharField(max_length=100)
 
+
 class City(models.Model):
     state = models.ForeignKey(State)
     name = models.CharField(max_length=100)
 
+
 class Restaurant(models.Model):
     city = models.ForeignKey(City)
     name = models.CharField(max_length=100)
 
+
 class Worker(models.Model):
     work_at = models.ForeignKey(Restaurant)
     name = models.CharField(max_length=50)
diff --git a/tests/admin_views/tests.py b/tests/admin_views/tests.py
index 91af9521a3..0ec9f25479 100644
--- a/tests/admin_views/tests.py
+++ b/tests/admin_views/tests.py
@@ -84,8 +84,8 @@ class AdminViewBasicTestCase(TestCase):
         """
         self.assertEqual(response.status_code, 200)
         self.assertTrue(response.content.index(force_bytes(text1)) < response.content.index(force_bytes(text2)),
-            failing_msg
-        )
+            failing_msg)
+
 
 class AdminViewBasicTest(AdminViewBasicTestCase):
     def testTrailingSlashRequired(self):
@@ -94,8 +94,8 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
         """
         response = self.client.get('/test_admin/%s/admin_views/article/add' % self.urlbit)
         self.assertRedirects(response,
-            '/test_admin/%s/admin_views/article/add/' % self.urlbit, status_code=301
-        )
+            '/test_admin/%s/admin_views/article/add/' % self.urlbit,
+            status_code=301)
 
     def testBasicAddGet(self):
         """
@@ -109,8 +109,7 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
         response = self.client.get('/test_admin/%s/admin_views/section/add/' % self.urlbit, {'name': 'My Section'})
         self.assertEqual(response.status_code, 200)
         self.assertContains(response, 'value="My Section"',
-            msg_prefix="Couldn't find an input with the right value in the response"
-        )
+            msg_prefix="Couldn't find an input with the right value in the response")
 
     def testBasicEditGet(self):
         """
@@ -394,11 +393,9 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
         response = self.client.get('/test_admin/%s/admin_views/thing/' % self.urlbit)
         self.assertEqual(response.status_code, 200)
         self.assertContains(response, '<div id="changelist-filter">',
-            msg_prefix="Expected filter not found in changelist view"
-        )
+            msg_prefix="Expected filter not found in changelist view")
         self.assertNotContains(response, '<a href="?color__id__exact=3">Blue</a>',
-            msg_prefix="Changelist filter not correctly limited by limit_choices_to"
-        )
+            msg_prefix="Changelist filter not correctly limited by limit_choices_to")
 
     def testRelationSpanningFilters(self):
         response = self.client.get('/test_admin/%s/admin_views/chapterxtra1/' %
@@ -1557,7 +1554,7 @@ class AdminViewStringPrimaryKeyTest(TestCase):
         response = self.client.get('/test_admin/admin/')
         counted_presence_after = response.content.count(force_bytes(should_contain))
         self.assertEqual(counted_presence_before - 1,
-                          counted_presence_after)
+            counted_presence_after)
 
     def test_logentry_get_admin_url(self):
         "LogEntry.get_admin_url returns a URL to edit the entry's object or None for non-existent (possibly deleted) models"
@@ -1612,13 +1609,13 @@ class AdminViewStringPrimaryKeyTest(TestCase):
     def test_change_view_history_link(self):
         """Object history button link should work and contain the pk value quoted."""
         url = reverse('admin:%s_modelwithstringprimarykey_change' %
-                          ModelWithStringPrimaryKey._meta.app_label,
-                      args=(quote(self.pk),))
+            ModelWithStringPrimaryKey._meta.app_label,
+            args=(quote(self.pk),))
         response = self.client.get(url)
         self.assertEqual(response.status_code, 200)
         expected_link = reverse('admin:%s_modelwithstringprimarykey_history' %
-                                    ModelWithStringPrimaryKey._meta.app_label,
-                                args=(quote(self.pk),))
+            ModelWithStringPrimaryKey._meta.app_label,
+            args=(quote(self.pk),))
         self.assertContains(response, '<a href="%s" class="historylink"' % expected_link)
 
 
@@ -2553,8 +2550,7 @@ action)</option>
         response = self.client.get('/test_admin/admin/admin_views/oldsubscriber/')
         self.assertEqual(response.context["action_form"], None)
         self.assertContains(response, 'jquery.min.js',
-            msg_prefix="jQuery missing from admin pages for model with no admin actions"
-        )
+            msg_prefix="jQuery missing from admin pages for model with no admin actions")
 
     def test_action_column_class(self):
         "Tests that the checkbox column class is present in the response"
@@ -3631,8 +3627,7 @@ class ReadonlyTest(TestCase):
         self.assertContains(response, "InlineMultiline<br />test<br />string")
 
         self.assertContains(response,
-            formats.localize(datetime.date.today() - datetime.timedelta(days=7))
-        )
+            formats.localize(datetime.date.today() - datetime.timedelta(days=7)))
 
         self.assertContains(response, '<div class="form-row field-coolness">')
         self.assertContains(response, '<div class="form-row field-awesomeness_level">')
@@ -3829,7 +3824,7 @@ class UserAdminTest(TestCase):
         adminform = response.context['adminform']
         self.assertTrue('password' not in adminform.form.errors)
         self.assertEqual(adminform.form.errors['password2'],
-                          ["The two password fields didn't match."])
+            ["The two password fields didn't match."])
 
     def test_user_fk_popup(self):
         """Quick user addition in a FK popup shouldn't invoke view for further user customization"""
diff --git a/tests/admin_views/views.py b/tests/admin_views/views.py
index bb5f24ebfe..cfae496aba 100644
--- a/tests/admin_views/views.py
+++ b/tests/admin_views/views.py
@@ -1,6 +1,7 @@
 from django.contrib.admin.views.decorators import staff_member_required
 from django.http import HttpResponse
 
+
 @staff_member_required
 def secure_view(request):
     return HttpResponse('%s' % request.POST)
diff --git a/tests/admin_widgets/models.py b/tests/admin_widgets/models.py
index 6a6c6e096b..5d295f0c9b 100644
--- a/tests/admin_widgets/models.py
+++ b/tests/admin_widgets/models.py
@@ -8,6 +8,7 @@ from django.utils.encoding import python_2_unicode_compatible
 class MyFileField(models.FileField):
     pass
 
+
 @python_2_unicode_compatible
 class Member(models.Model):
     name = models.CharField(max_length=100)
@@ -18,6 +19,7 @@ class Member(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Band(models.Model):
     name = models.CharField(max_length=100)
@@ -27,6 +29,7 @@ class Band(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Album(models.Model):
     band = models.ForeignKey(Band)
@@ -37,10 +40,12 @@ class Album(models.Model):
     def __str__(self):
         return self.name
 
+
 class HiddenInventoryManager(models.Manager):
     def get_queryset(self):
         return super(HiddenInventoryManager, self).get_queryset().filter(hidden=False)
 
+
 @python_2_unicode_compatible
 class Inventory(models.Model):
     barcode = models.PositiveIntegerField(unique=True)
@@ -55,6 +60,7 @@ class Inventory(models.Model):
     def __str__(self):
         return self.name
 
+
 class Event(models.Model):
     main_band = models.ForeignKey(Band, limit_choices_to=models.Q(pk__gt=0), related_name='events_main_band_at')
     supporting_bands = models.ManyToManyField(Band, null=True, blank=True, related_name='events_supporting_band_at')
@@ -64,6 +70,7 @@ class Event(models.Model):
     link = models.URLField(blank=True)
     min_age = models.IntegerField(blank=True, null=True)
 
+
 @python_2_unicode_compatible
 class Car(models.Model):
     owner = models.ForeignKey(User)
@@ -73,15 +80,18 @@ class Car(models.Model):
     def __str__(self):
         return "%s %s" % (self.make, self.model)
 
+
 class CarTire(models.Model):
     """
     A single car tire. This to test that a user can only select their own cars.
     """
     car = models.ForeignKey(Car)
 
+
 class Honeycomb(models.Model):
     location = models.CharField(max_length=20)
 
+
 class Bee(models.Model):
     """
     A model with a FK to a model that won't be registered with the admin
@@ -90,6 +100,7 @@ class Bee(models.Model):
     """
     honeycomb = models.ForeignKey(Honeycomb)
 
+
 class Individual(models.Model):
     """
     A model with a FK to itself. It won't be registered with the admin, so the
@@ -99,9 +110,11 @@ class Individual(models.Model):
     name = models.CharField(max_length=20)
     parent = models.ForeignKey('self', null=True)
 
+
 class Company(models.Model):
     name = models.CharField(max_length=20)
 
+
 class Advisor(models.Model):
     """
     A model with a m2m to a model that won't be registered with the admin
@@ -122,6 +135,7 @@ class Student(models.Model):
     class Meta:
         ordering = ('name',)
 
+
 @python_2_unicode_compatible
 class School(models.Model):
     name = models.CharField(max_length=255)
diff --git a/tests/admin_widgets/tests.py b/tests/admin_widgets/tests.py
index 4b36f8bd32..0dec3a2cfa 100644
--- a/tests/admin_widgets/tests.py
+++ b/tests/admin_widgets/tests.py
@@ -25,6 +25,7 @@ admin_static_prefix = lambda: {
     'ADMIN_STATIC_PREFIX': "%sadmin/" % settings.STATIC_URL,
 }
 
+
 class AdminFormfieldForDBFieldTests(TestCase):
     """
     Tests for correct behavior of ModelAdmin.formfield_for_dbfield
@@ -269,6 +270,7 @@ class FilteredSelectMultipleWidgetTest(DjangoTestCase):
             '<select multiple="multiple" name="test" class="selectfilterstacked">\n</select><script type="text/javascript">addEvent(window, "load", function(e) {SelectFilter.init("id_test", "test", 1, "%(ADMIN_STATIC_PREFIX)s"); });</script>\n' % admin_static_prefix()
         )
 
+
 class AdminDateWidgetTest(DjangoTestCase):
     def test_attrs(self):
         """
@@ -287,6 +289,7 @@ class AdminDateWidgetTest(DjangoTestCase):
             '<input value="2007-12-01" type="text" class="myDateField" name="test" size="20" />',
         )
 
+
 class AdminTimeWidgetTest(DjangoTestCase):
     def test_attrs(self):
         """
@@ -305,6 +308,7 @@ class AdminTimeWidgetTest(DjangoTestCase):
             '<input value="09:30:00" type="text" class="myTimeField" name="test" size="20" />',
         )
 
+
 class AdminSplitDateTimeWidgetTest(DjangoTestCase):
     def test_render(self):
         w = widgets.AdminSplitDateTime()
@@ -495,6 +499,7 @@ class ManyToManyRawIdWidgetTest(DjangoTestCase):
             '<input type="text" name="company_widget2" value="%(c1pk)s" />' % {'c1pk': c1.pk}
         )
 
+
 class RelatedFieldWidgetWrapperTests(DjangoTestCase):
     def test_no_can_add_related(self):
         rel = models.Individual._meta.get_field('parent').rel
@@ -631,6 +636,7 @@ class DateTimePickerSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
 class DateTimePickerSeleniumChromeTests(DateTimePickerSeleniumFirefoxTests):
     webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
 
+
 class DateTimePickerSeleniumIETests(DateTimePickerSeleniumFirefoxTests):
     webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
 
@@ -686,9 +692,11 @@ class DateTimePickerShortcutsSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase
         self.assertGreater(member.birthdate, now - error_margin)
         self.assertLess(member.birthdate, now + error_margin)
 
+
 class DateTimePickerShortcutsSeleniumChromeTests(DateTimePickerShortcutsSeleniumFirefoxTests):
     webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
 
+
 class DateTimePickerShortcutsSeleniumIETests(DateTimePickerShortcutsSeleniumFirefoxTests):
     webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
 
@@ -714,7 +722,7 @@ class HorizontalVerticalFilterSeleniumFirefoxTests(AdminSeleniumWebDriverTestCas
         super(HorizontalVerticalFilterSeleniumFirefoxTests, self).setUp()
 
     def assertActiveButtons(self, mode, field_name, choose, remove,
-                             choose_all=None, remove_all=None):
+            choose_all=None, remove_all=None):
         choose_link = '#id_%s_add_link' % field_name
         choose_all_link = '#id_%s_add_all_link' % field_name
         remove_link = '#id_%s_remove_link' % field_name
@@ -928,9 +936,11 @@ class HorizontalVerticalFilterSeleniumFirefoxTests(AdminSeleniumWebDriverTestCas
         self.assertEqual(list(self.school.alumni.all()),
                          [self.jason, self.peter])
 
+
 class HorizontalVerticalFilterSeleniumChromeTests(HorizontalVerticalFilterSeleniumFirefoxTests):
     webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
 
+
 class HorizontalVerticalFilterSeleniumIETests(HorizontalVerticalFilterSeleniumFirefoxTests):
     webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
 
@@ -1025,9 +1035,11 @@ class AdminRawIdWidgetSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
             self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'),
             '42,98')
 
+
 class AdminRawIdWidgetSeleniumChromeTests(AdminRawIdWidgetSeleniumFirefoxTests):
     webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
 
+
 class AdminRawIdWidgetSeleniumIETests(AdminRawIdWidgetSeleniumFirefoxTests):
     webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
 
@@ -1072,8 +1084,10 @@ class RelatedFieldWidgetSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
         self.assertEqual(len(profiles), 1)
         self.assertEqual(profiles[0].user.username, username_value)
 
+
 class RelatedFieldWidgetSeleniumChromeTests(RelatedFieldWidgetSeleniumFirefoxTests):
     webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
 
+
 class RelatedFieldWidgetSeleniumIETests(RelatedFieldWidgetSeleniumFirefoxTests):
     webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
diff --git a/tests/aggregation/models.py b/tests/aggregation/models.py
index 9710afaf11..691737c17e 100644
--- a/tests/aggregation/models.py
+++ b/tests/aggregation/models.py
@@ -12,6 +12,7 @@ class Author(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Publisher(models.Model):
     name = models.CharField(max_length=255)
@@ -20,6 +21,7 @@ class Publisher(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Book(models.Model):
     isbn = models.CharField(max_length=9)
@@ -35,6 +37,7 @@ class Book(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Store(models.Model):
     name = models.CharField(max_length=255)
diff --git a/tests/aggregation_regress/models.py b/tests/aggregation_regress/models.py
index a2dc060640..275e37c036 100644
--- a/tests/aggregation_regress/models.py
+++ b/tests/aggregation_regress/models.py
@@ -61,6 +61,7 @@ class Store(models.Model):
     def __str__(self):
         return self.name
 
+
 class Entries(models.Model):
     EntryID = models.AutoField(primary_key=True, db_column='Entry ID')
     Entry = models.CharField(unique=True, max_length=50)
@@ -69,7 +70,7 @@ class Entries(models.Model):
 
 class Clues(models.Model):
     ID = models.AutoField(primary_key=True)
-    EntryID = models.ForeignKey(Entries, verbose_name='Entry', db_column = 'Entry ID')
+    EntryID = models.ForeignKey(Entries, verbose_name='Entry', db_column='Entry ID')
     Clue = models.CharField(max_length=150)
 
 
@@ -88,13 +89,16 @@ class HardbackBook(Book):
     def __str__(self):
         return "%s (hardback): %s" % (self.name, self.weight)
 
+
 # Models for ticket #21150
 class Alfa(models.Model):
     name = models.CharField(max_length=10, null=True)
 
+
 class Bravo(models.Model):
     pass
 
+
 class Charlie(models.Model):
     alfa = models.ForeignKey(Alfa, null=True)
     bravo = models.ForeignKey(Bravo, null=True)
diff --git a/tests/backends/tests.py b/tests/backends/tests.py
index 3c0cc67ea2..3a79b79411 100644
--- a/tests/backends/tests.py
+++ b/tests/backends/tests.py
@@ -432,6 +432,7 @@ class EscapingChecks(TestCase):
         # response should be an non-zero integer
         self.assertTrue(int(response))
 
+
 @override_settings(DEBUG=True)
 class EscapingChecksDebug(EscapingChecks):
     pass
@@ -509,12 +510,12 @@ class BackendTestCase(TestCase):
 
     def test_cursor_executemany(self):
         #4896: Test cursor.executemany
-        args = [(i, i**2) for i in range(-5, 6)]
+        args = [(i, i ** 2) for i in range(-5, 6)]
         self.create_squares_with_executemany(args)
         self.assertEqual(models.Square.objects.count(), 11)
         for i in range(-5, 6):
             square = models.Square.objects.get(root=i)
-            self.assertEqual(square.square, i**2)
+            self.assertEqual(square.square, i ** 2)
 
     def test_cursor_executemany_with_empty_params_list(self):
         #4765: executemany with params=[] does nothing
@@ -524,11 +525,11 @@ class BackendTestCase(TestCase):
 
     def test_cursor_executemany_with_iterator(self):
         #10320: executemany accepts iterators
-        args = iter((i, i**2) for i in range(-3, 2))
+        args = iter((i, i ** 2) for i in range(-3, 2))
         self.create_squares_with_executemany(args)
         self.assertEqual(models.Square.objects.count(), 5)
 
-        args = iter((i, i**2) for i in range(3, 7))
+        args = iter((i, i ** 2) for i in range(3, 7))
         with override_settings(DEBUG=True):
             # same test for DebugCursorWrapper
             self.create_squares_with_executemany(args)
@@ -544,20 +545,20 @@ class BackendTestCase(TestCase):
     @skipUnlessDBFeature('supports_paramstyle_pyformat')
     def test_cursor_executemany_with_pyformat(self):
         #10070: Support pyformat style passing of paramters
-        args = [{'root': i, 'square': i**2} for i in range(-5, 6)]
+        args = [{'root': i, 'square': i ** 2} for i in range(-5, 6)]
         self.create_squares(args, 'pyformat', multiple=True)
         self.assertEqual(models.Square.objects.count(), 11)
         for i in range(-5, 6):
             square = models.Square.objects.get(root=i)
-            self.assertEqual(square.square, i**2)
+            self.assertEqual(square.square, i ** 2)
 
     @skipUnlessDBFeature('supports_paramstyle_pyformat')
     def test_cursor_executemany_with_pyformat_iterator(self):
-        args = iter({'root': i, 'square': i**2} for i in range(-3, 2))
+        args = iter({'root': i, 'square': i ** 2} for i in range(-3, 2))
         self.create_squares(args, 'pyformat', multiple=True)
         self.assertEqual(models.Square.objects.count(), 5)
 
-        args = iter({'root': i, 'square': i**2} for i in range(3, 7))
+        args = iter({'root': i, 'square': i ** 2} for i in range(3, 7))
         with override_settings(DEBUG=True):
             # same test for DebugCursorWrapper
             self.create_squares(args, 'pyformat', multiple=True)
@@ -987,6 +988,7 @@ class BackendUtilTests(TestCase):
         equal('0.1234567890', 12, 0,
               '0')
 
+
 @unittest.skipUnless(
     connection.vendor == 'postgresql',
     "This test applies only to PostgreSQL")
diff --git a/tests/basic/models.py b/tests/basic/models.py
index 38cb813d42..5e67b0dca9 100644
--- a/tests/basic/models.py
+++ b/tests/basic/models.py
@@ -19,11 +19,13 @@ class Article(models.Model):
     def __str__(self):
         return self.headline
 
+
 class ArticleSelectOnSave(Article):
     class Meta:
         proxy = True
         select_on_save = True
 
+
 @python_2_unicode_compatible
 class SelfRef(models.Model):
     selfref = models.ForeignKey('self', null=True, blank=True,
diff --git a/tests/basic/tests.py b/tests/basic/tests.py
index e4559dc7d7..976fb1124d 100644
--- a/tests/basic/tests.py
+++ b/tests/basic/tests.py
@@ -87,7 +87,8 @@ class ModelTest(TestCase):
 
         # Django raises an Article.DoesNotExist exception for get() if the
         # parameters don't match any object.
-        six.assertRaisesRegex(self,
+        six.assertRaisesRegex(
+            self,
             ObjectDoesNotExist,
             "Article matching query does not exist.",
             Article.objects.get,
@@ -102,7 +103,8 @@ class ModelTest(TestCase):
             pub_date__month=8,
         )
 
-        six.assertRaisesRegex(self,
+        six.assertRaisesRegex(
+            self,
             ObjectDoesNotExist,
             "Article matching query does not exist.",
             Article.objects.get,
@@ -135,21 +137,24 @@ class ModelTest(TestCase):
 
         # Django raises an Article.MultipleObjectsReturned exception if the
         # lookup matches more than one object
-        six.assertRaisesRegex(self,
+        six.assertRaisesRegex(
+            self,
             MultipleObjectsReturned,
             "get\(\) returned more than one Article -- it returned 2!",
             Article.objects.get,
             headline__startswith='Area',
         )
 
-        six.assertRaisesRegex(self,
+        six.assertRaisesRegex(
+            self,
             MultipleObjectsReturned,
             "get\(\) returned more than one Article -- it returned 2!",
             Article.objects.get,
             pub_date__year=2005,
         )
 
-        six.assertRaisesRegex(self,
+        six.assertRaisesRegex(
+            self,
             MultipleObjectsReturned,
             "get\(\) returned more than one Article -- it returned 2!",
             Article.objects.get,
@@ -165,14 +170,16 @@ class ModelTest(TestCase):
             Article(headline='Area %s' % i, pub_date=datetime(2005, 7, 28))
             for i in range(MAX_GET_RESULTS)
         )
-        six.assertRaisesRegex(self,
+        six.assertRaisesRegex(
+            self,
             MultipleObjectsReturned,
             "get\(\) returned more than one Article -- it returned %d!" % MAX_GET_RESULTS,
             Article.objects.get,
             headline__startswith='Area',
         )
         Article.objects.create(headline='Area %s' % MAX_GET_RESULTS, pub_date=datetime(2005, 7, 28))
-        six.assertRaisesRegex(self,
+        six.assertRaisesRegex(
+            self,
             MultipleObjectsReturned,
             "get\(\) returned more than one Article -- it returned more than %d!" % MAX_GET_RESULTS,
             Article.objects.get,
@@ -219,7 +226,8 @@ class ModelTest(TestCase):
         self.assertEqual(a4.headline, 'Fourth article')
 
         # Don't use invalid keyword arguments.
-        six.assertRaisesRegex(self,
+        six.assertRaisesRegex(
+            self,
             TypeError,
             "'foo' is an invalid keyword argument for this function",
             Article,
@@ -315,7 +323,8 @@ class ModelTest(TestCase):
             Article.objects.dates,
         )
 
-        six.assertRaisesRegex(self,
+        six.assertRaisesRegex(
+            self,
             FieldDoesNotExist,
             "Article has no field named 'invalid_field'",
             Article.objects.dates,
@@ -323,7 +332,8 @@ class ModelTest(TestCase):
             "year",
         )
 
-        six.assertRaisesRegex(self,
+        six.assertRaisesRegex(
+            self,
             AssertionError,
             "'kind' must be one of 'year', 'month' or 'day'.",
             Article.objects.dates,
@@ -331,7 +341,8 @@ class ModelTest(TestCase):
             "bad_kind",
         )
 
-        six.assertRaisesRegex(self,
+        six.assertRaisesRegex(
+            self,
             AssertionError,
             "'order' must be either 'ASC' or 'DESC'.",
             Article.objects.dates,
@@ -419,14 +430,16 @@ class ModelTest(TestCase):
              "<Article: Updated article 8>"])
 
         # Also, once you have sliced you can't filter, re-order or combine
-        six.assertRaisesRegex(self,
+        six.assertRaisesRegex(
+            self,
             AssertionError,
             "Cannot filter a query once a slice has been taken.",
             Article.objects.all()[0:5].filter,
             id=a.id,
         )
 
-        six.assertRaisesRegex(self,
+        six.assertRaisesRegex(
+            self,
             AssertionError,
             "Cannot reorder a query once a slice has been taken.",
             Article.objects.all()[0:5].order_by,
@@ -461,7 +474,8 @@ class ModelTest(TestCase):
 
         # An Article instance doesn't have access to the "objects" attribute.
         # That's only available on the class.
-        six.assertRaisesRegex(self,
+        six.assertRaisesRegex(
+            self,
             AttributeError,
             "Manager isn't accessible via Article instances",
             getattr,
@@ -605,8 +619,8 @@ class ModelTest(TestCase):
         )
 
         dicts = Article.objects.filter(
-            pub_date__year=2008).extra(select={'dashed-value': '1'}
-        ).values('headline', 'dashed-value')
+            pub_date__year=2008).extra(
+            select={'dashed-value': '1'}).values('headline', 'dashed-value')
         self.assertEqual([sorted(d.items()) for d in dicts],
             [[('dashed-value', 1), ('headline', 'Article 11')], [('dashed-value', 1), ('headline', 'Article 12')]])
 
@@ -723,6 +737,7 @@ class ModelTest(TestCase):
             # hash)
             hash(Article())
 
+
 class ConcurrentSaveTests(TransactionTestCase):
 
     available_apps = ['basic']
@@ -808,6 +823,7 @@ class ManagerTest(TestCase):
             sorted(self.QUERYSET_PROXY_METHODS),
         )
 
+
 class SelectOnSaveTests(TestCase):
     def test_select_on_save(self):
         a1 = Article.objects.create(pub_date=datetime.now())
diff --git a/tests/bug639/models.py b/tests/bug639/models.py
index fa8e7d2c07..3b6a007f6b 100644
--- a/tests/bug639/models.py
+++ b/tests/bug639/models.py
@@ -8,6 +8,7 @@ from django.forms import ModelForm
 temp_storage_dir = tempfile.mkdtemp()
 temp_storage = FileSystemStorage(temp_storage_dir)
 
+
 class Photo(models.Model):
     title = models.CharField(max_length=30)
     image = models.FileField(storage=temp_storage, upload_to='tests')
@@ -22,6 +23,7 @@ class Photo(models.Model):
         super(Photo, self).save(force_insert, force_update)
         self._savecount += 1
 
+
 class PhotoForm(ModelForm):
     class Meta:
         model = Photo
diff --git a/tests/bulk_create/models.py b/tests/bulk_create/models.py
index bc685bbbe4..fcc4b4177e 100644
--- a/tests/bulk_create/models.py
+++ b/tests/bulk_create/models.py
@@ -5,21 +5,26 @@ class Country(models.Model):
     name = models.CharField(max_length=255)
     iso_two_letter = models.CharField(max_length=2)
 
+
 class Place(models.Model):
     name = models.CharField(max_length=100)
 
     class Meta:
         abstract = True
 
+
 class Restaurant(Place):
     pass
 
+
 class Pizzeria(Restaurant):
     pass
 
+
 class State(models.Model):
     two_letter_code = models.CharField(max_length=2, primary_key=True)
 
+
 class TwoFields(models.Model):
     f1 = models.IntegerField(unique=True)
     f2 = models.IntegerField(unique=True)
diff --git a/tests/cache/closeable_cache.py b/tests/cache/closeable_cache.py
index 83073850b7..1ac868dde9 100644
--- a/tests/cache/closeable_cache.py
+++ b/tests/cache/closeable_cache.py
@@ -7,5 +7,6 @@ class CloseHookMixin(object):
     def close(self, **kwargs):
         self.closed = True
 
+
 class CacheClass(CloseHookMixin, LocMemCache):
     pass
diff --git a/tests/cache/liberal_backend.py b/tests/cache/liberal_backend.py
index 3e3ce3beeb..339066b0ff 100644
--- a/tests/cache/liberal_backend.py
+++ b/tests/cache/liberal_backend.py
@@ -5,5 +5,6 @@ class LiberalKeyValidationMixin(object):
     def validate_key(self, key):
         pass
 
+
 class CacheClass(LiberalKeyValidationMixin, LocMemCache):
     pass
diff --git a/tests/cache/models.py b/tests/cache/models.py
index 2cd648b780..4fccbb664b 100644
--- a/tests/cache/models.py
+++ b/tests/cache/models.py
@@ -7,6 +7,7 @@ def expensive_calculation():
     expensive_calculation.num_runs += 1
     return timezone.now()
 
+
 class Poll(models.Model):
     question = models.CharField(max_length=200)
     answer = models.CharField(max_length=200)
diff --git a/tests/cache/tests.py b/tests/cache/tests.py
index a79d4d9fac..a93ed4418a 100644
--- a/tests/cache/tests.py
+++ b/tests/cache/tests.py
@@ -40,10 +40,12 @@ from django.views.decorators.cache import cache_page
 
 from .models import Poll, expensive_calculation
 
+
 # functions/classes for complex data type tests
 def f():
     return 42
 
+
 class C:
     def m(n):
         return 24
@@ -823,6 +825,7 @@ class BaseCacheTests(object):
         self.assertEqual(get_cache_data.content, content.encode('utf-8'))
         self.assertEqual(get_cache_data.cookies, response.cookies)
 
+
 def custom_key_func(key, key_prefix, version):
     "A customized cache key function"
     return 'CUSTOM-' + '-'.join([key_prefix, str(version), key])
@@ -1004,6 +1007,7 @@ class LocMemCacheTests(unittest.TestCase, BaseCacheTests):
         self.cache.decr(key)
         self.assertEqual(expire, self.cache._expire_info[_key])
 
+
 # memcached backend isn't guaranteed to be available.
 # To check the memcached backend, the test settings file will
 # need to contain at least one cache backend setting that points at
@@ -1581,6 +1585,7 @@ class CacheI18nTest(TestCase):
         get_cache_data = FetchFromCacheMiddleware().process_request(request)
         self.assertIsNone(get_cache_data)
 
+
 @override_settings(
     CACHES={
         'default': {
@@ -1816,6 +1821,7 @@ class CacheMiddlewareTest(IgnoreDeprecationWarningsMixin, TestCase):
         response = other_with_prefix_view(request, '16')
         self.assertEqual(response.content, b'Hello World 16')
 
+
 @override_settings(
     CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix',
     CACHE_MIDDLEWARE_SECONDS=1,
diff --git a/tests/check/models.py b/tests/check/models.py
index 212b01bdd2..ddeed23982 100644
--- a/tests/check/models.py
+++ b/tests/check/models.py
@@ -1,9 +1,11 @@
 from django.db import models
 
+
 class Book(models.Model):
     title = models.CharField(max_length=250)
     is_published = models.BooleanField(default=False)
 
+
 class BlogPost(models.Model):
     title = models.CharField(max_length=250)
     is_published = models.BooleanField(default=False)
diff --git a/tests/check/tests.py b/tests/check/tests.py
index 19b3840a9a..577dcd610b 100644
--- a/tests/check/tests.py
+++ b/tests/check/tests.py
@@ -7,6 +7,7 @@ from django.test import TestCase
 
 from .models import Book
 
+
 class StubCheckModule(object):
     # Has no ``run_checks`` attribute & will trigger a warning.
     __name__ = 'StubCheckModule'
diff --git a/tests/choices/models.py b/tests/choices/models.py
index 2fa33a9680..4fcef6f48f 100644
--- a/tests/choices/models.py
+++ b/tests/choices/models.py
@@ -18,6 +18,7 @@ GENDER_CHOICES = (
     ('F', 'Female'),
 )
 
+
 @python_2_unicode_compatible
 class Person(models.Model):
     name = models.CharField(max_length=20)
diff --git a/tests/commands_sql/tests.py b/tests/commands_sql/tests.py
index 1a1a190ec5..3a0b5527f4 100644
--- a/tests/commands_sql/tests.py
+++ b/tests/commands_sql/tests.py
@@ -58,6 +58,7 @@ class TestRouter(object):
     def allow_migrate(self, db, model):
         return False
 
+
 class SQLCommandsRouterTestCase(TestCase):
     def setUp(self):
         self._old_routers = router.routers
diff --git a/tests/conditional_processing/tests.py b/tests/conditional_processing/tests.py
index 77f1ff54ed..2c832e527c 100644
--- a/tests/conditional_processing/tests.py
+++ b/tests/conditional_processing/tests.py
@@ -15,6 +15,7 @@ EXPIRED_LAST_MODIFIED_STR = 'Sat, 20 Oct 2007 23:21:47 GMT'
 ETAG = 'b4246ffc4f62314ca13147c9d4f76974'
 EXPIRED_ETAG = '7fae4cd4b0f81e7d2914700043aa8ed6'
 
+
 class ConditionalGet(TestCase):
     urls = 'conditional_processing.urls'
 
diff --git a/tests/conditional_processing/views.py b/tests/conditional_processing/views.py
index 2960e0533d..496e79fd34 100644
--- a/tests/conditional_processing/views.py
+++ b/tests/conditional_processing/views.py
@@ -8,18 +8,22 @@ def index(request):
     return HttpResponse(FULL_RESPONSE)
 index = condition(lambda r: ETAG, lambda r: LAST_MODIFIED)(index)
 
+
 def last_modified_view1(request):
     return HttpResponse(FULL_RESPONSE)
 last_modified_view1 = condition(last_modified_func=lambda r: LAST_MODIFIED)(last_modified_view1)
 
+
 def last_modified_view2(request):
     return HttpResponse(FULL_RESPONSE)
 last_modified_view2 = last_modified(lambda r: LAST_MODIFIED)(last_modified_view2)
 
+
 def etag_view1(request):
     return HttpResponse(FULL_RESPONSE)
 etag_view1 = condition(etag_func=lambda r: ETAG)(etag_view1)
 
+
 def etag_view2(request):
     return HttpResponse(FULL_RESPONSE)
 etag_view2 = etag(lambda r: ETAG)(etag_view2)
diff --git a/tests/contenttypes_tests/models.py b/tests/contenttypes_tests/models.py
index 5d21ad5b96..b2669367eb 100644
--- a/tests/contenttypes_tests/models.py
+++ b/tests/contenttypes_tests/models.py
@@ -3,6 +3,7 @@ from __future__ import unicode_literals
 from django.db import models
 from django.utils.encoding import python_2_unicode_compatible
 
+
 @python_2_unicode_compatible
 class Author(models.Model):
     name = models.CharField(max_length=100)
@@ -13,6 +14,7 @@ class Author(models.Model):
     def get_absolute_url(self):
         return '/views/authors/%s/' % self.id
 
+
 @python_2_unicode_compatible
 class Article(models.Model):
     title = models.CharField(max_length=100)
diff --git a/tests/contenttypes_tests/tests.py b/tests/contenttypes_tests/tests.py
index 63f02697df..29ae6c5336 100644
--- a/tests/contenttypes_tests/tests.py
+++ b/tests/contenttypes_tests/tests.py
@@ -5,6 +5,7 @@ from django.test import TestCase
 
 from .models import Author, Article
 
+
 class ContentTypesViewsTests(TestCase):
     fixtures = ['testdata.json']
     urls = 'contenttypes_tests.urls'
diff --git a/tests/csrf_tests/tests.py b/tests/csrf_tests/tests.py
index 57f8359cc7..ac48c17af6 100644
--- a/tests/csrf_tests/tests.py
+++ b/tests/csrf_tests/tests.py
@@ -19,10 +19,12 @@ def post_form_response():
 """, mimetype="text/html")
     return resp
 
+
 def post_form_view(request):
     """A view that returns a POST form (without a token)"""
     return post_form_response()
 
+
 # Response/views used for template tag tests
 
 def token_view(request):
@@ -31,6 +33,7 @@ def token_view(request):
     template = Template("{% csrf_token %}")
     return HttpResponse(template.render(context))
 
+
 def non_token_view_using_request_processor(request):
     """
     A view that doesn't use the token, but does use the csrf view processor.
@@ -39,6 +42,7 @@ def non_token_view_using_request_processor(request):
     template = Template("")
     return HttpResponse(template.render(context))
 
+
 class TestingHttpRequest(HttpRequest):
     """
     A version of HttpRequest that allows us to change some things
@@ -47,6 +51,7 @@ class TestingHttpRequest(HttpRequest):
     def is_secure(self):
         return getattr(self, '_is_secure_override', False)
 
+
 class CsrfViewMiddlewareTest(TestCase):
     # The csrf token is potentially from an untrusted source, so could have
     # characters that need dealing with.
diff --git a/tests/custom_columns/models.py b/tests/custom_columns/models.py
index 2549dde749..df1e743be9 100644
--- a/tests/custom_columns/models.py
+++ b/tests/custom_columns/models.py
@@ -33,6 +33,7 @@ class Author(models.Model):
         db_table = 'my_author_table'
         ordering = ('last_name', 'first_name')
 
+
 @python_2_unicode_compatible
 class Article(models.Model):
     headline = models.CharField(max_length=100)
diff --git a/tests/custom_columns_regress/models.py b/tests/custom_columns_regress/models.py
index e848b8ec23..1c026a44c0 100644
--- a/tests/custom_columns_regress/models.py
+++ b/tests/custom_columns_regress/models.py
@@ -24,6 +24,7 @@ class Article(models.Model):
     class Meta:
         ordering = ('headline',)
 
+
 @python_2_unicode_compatible
 class Author(models.Model):
     Author_ID = models.AutoField(primary_key=True, db_column='Author ID')
diff --git a/tests/custom_columns_regress/tests.py b/tests/custom_columns_regress/tests.py
index 034de08d45..24297b9fa5 100644
--- a/tests/custom_columns_regress/tests.py
+++ b/tests/custom_columns_regress/tests.py
@@ -10,6 +10,7 @@ def pks(objects):
     """ Return pks to be able to compare lists"""
     return [o.pk for o in objects]
 
+
 class CustomColumnRegression(TestCase):
 
     def setUp(self):
diff --git a/tests/custom_managers/models.py b/tests/custom_managers/models.py
index 26d848b7c0..c6a99620e9 100644
--- a/tests/custom_managers/models.py
+++ b/tests/custom_managers/models.py
@@ -17,18 +17,21 @@ from django.utils.encoding import python_2_unicode_compatible
 
 # An example of a custom manager called "objects".
 
+
 class PersonManager(models.Manager):
     def get_fun_people(self):
         return self.filter(fun=True)
 
 # An example of a custom manager that sets get_queryset().
 
+
 class PublishedBookManager(models.Manager):
     def get_queryset(self):
         return super(PublishedBookManager, self).get_queryset().filter(is_published=True)
 
 # An example of a custom queryset that copies its methods onto the manager.
 
+
 class CustomQuerySet(models.QuerySet):
     def filter(self, *args, **kwargs):
         queryset = super(CustomQuerySet, self).filter(fun=True)
@@ -49,6 +52,7 @@ class CustomQuerySet(models.QuerySet):
         return self.all()
     _optin_private_method.queryset_only = False
 
+
 class BaseCustomManager(models.Manager):
     def __init__(self, arg):
         super(BaseCustomManager, self).__init__()
@@ -64,14 +68,17 @@ class BaseCustomManager(models.Manager):
 
 CustomManager = BaseCustomManager.from_queryset(CustomQuerySet)
 
+
 class FunPeopleManager(models.Manager):
     def get_queryset(self):
         return super(FunPeopleManager, self).get_queryset().filter(fun=True)
 
+
 class BoringPeopleManager(models.Manager):
     def get_queryset(self):
         return super(BoringPeopleManager, self).get_queryset().filter(fun=False)
 
+
 @python_2_unicode_compatible
 class Person(models.Model):
     first_name = models.CharField(max_length=30)
@@ -93,6 +100,7 @@ class Person(models.Model):
     def __str__(self):
         return "%s %s" % (self.first_name, self.last_name)
 
+
 @python_2_unicode_compatible
 class Book(models.Model):
     title = models.CharField(max_length=50)
@@ -109,10 +117,12 @@ class Book(models.Model):
 
 # An example of providing multiple custom managers.
 
+
 class FastCarManager(models.Manager):
     def get_queryset(self):
         return super(FastCarManager, self).get_queryset().filter(top_speed__gt=150)
 
+
 @python_2_unicode_compatible
 class Car(models.Model):
     name = models.CharField(max_length=10)
diff --git a/tests/custom_managers_regress/models.py b/tests/custom_managers_regress/models.py
index 95cf6e8ca1..eda711f8d7 100644
--- a/tests/custom_managers_regress/models.py
+++ b/tests/custom_managers_regress/models.py
@@ -13,6 +13,7 @@ class RestrictedManager(models.Manager):
     def get_queryset(self):
         return super(RestrictedManager, self).get_queryset().filter(is_public=True)
 
+
 @python_2_unicode_compatible
 class RelatedModel(models.Model):
     name = models.CharField(max_length=50)
@@ -20,6 +21,7 @@ class RelatedModel(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class RestrictedModel(models.Model):
     name = models.CharField(max_length=50)
@@ -32,6 +34,7 @@ class RestrictedModel(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class OneToOneRestrictedModel(models.Model):
     name = models.CharField(max_length=50)
diff --git a/tests/custom_pk/fields.py b/tests/custom_pk/fields.py
index 92096a0ff7..2aa3bad963 100644
--- a/tests/custom_pk/fields.py
+++ b/tests/custom_pk/fields.py
@@ -22,6 +22,7 @@ class MyWrapper(object):
             return self.value == other.value
         return self.value == other
 
+
 class MyAutoField(six.with_metaclass(models.SubfieldBase, models.CharField)):
 
     def __init__(self, *args, **kwargs):
diff --git a/tests/custom_pk/models.py b/tests/custom_pk/models.py
index 5fffb84641..bfa6777b10 100644
--- a/tests/custom_pk/models.py
+++ b/tests/custom_pk/models.py
@@ -16,7 +16,7 @@ from django.utils.encoding import python_2_unicode_compatible
 
 @python_2_unicode_compatible
 class Employee(models.Model):
-    employee_code = models.IntegerField(primary_key=True, db_column = 'code')
+    employee_code = models.IntegerField(primary_key=True, db_column='code')
     first_name = models.CharField(max_length=20)
     last_name = models.CharField(max_length=20)
 
@@ -26,6 +26,7 @@ class Employee(models.Model):
     def __str__(self):
         return "%s %s" % (self.first_name, self.last_name)
 
+
 @python_2_unicode_compatible
 class Business(models.Model):
     name = models.CharField(max_length=20, primary_key=True)
@@ -37,6 +38,7 @@ class Business(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Bar(models.Model):
     id = MyAutoField(primary_key=True, db_index=True)
diff --git a/tests/datatypes/models.py b/tests/datatypes/models.py
index 8e6027dd0f..cabe5297bd 100644
--- a/tests/datatypes/models.py
+++ b/tests/datatypes/models.py
@@ -23,6 +23,7 @@ class Donut(models.Model):
     def __str__(self):
         return self.name
 
+
 class RumBaba(models.Model):
     baked_date = models.DateField(auto_now_add=True)
     baked_timestamp = models.DateTimeField(auto_now_add=True)
diff --git a/tests/dates/models.py b/tests/dates/models.py
index 23350755e7..d27c22ff67 100644
--- a/tests/dates/models.py
+++ b/tests/dates/models.py
@@ -14,6 +14,7 @@ class Article(models.Model):
     def __str__(self):
         return self.title
 
+
 @python_2_unicode_compatible
 class Comment(models.Model):
     article = models.ForeignKey(Article, related_name="comments")
@@ -24,5 +25,6 @@ class Comment(models.Model):
     def __str__(self):
         return 'Comment to %s (%s)' % (self.article.title, self.pub_date)
 
+
 class Category(models.Model):
     name = models.CharField(max_length=255)
diff --git a/tests/datetimes/models.py b/tests/datetimes/models.py
index f21376aa1c..cfdd521b53 100644
--- a/tests/datetimes/models.py
+++ b/tests/datetimes/models.py
@@ -14,6 +14,7 @@ class Article(models.Model):
     def __str__(self):
         return self.title
 
+
 @python_2_unicode_compatible
 class Comment(models.Model):
     article = models.ForeignKey(Article, related_name="comments")
@@ -24,5 +25,6 @@ class Comment(models.Model):
     def __str__(self):
         return 'Comment to %s (%s)' % (self.article.title, self.pub_date)
 
+
 class Category(models.Model):
     name = models.CharField(max_length=255)
diff --git a/tests/db_typecasts/tests.py b/tests/db_typecasts/tests.py
index 27b89c0c8c..e391743028 100644
--- a/tests/db_typecasts/tests.py
+++ b/tests/db_typecasts/tests.py
@@ -48,6 +48,7 @@ TEST_CASES = {
     ),
 }
 
+
 class DBTypeCasts(unittest.TestCase):
     def test_typeCasts(self):
         for k, v in six.iteritems(TEST_CASES):
diff --git a/tests/defer_regress/tests.py b/tests/defer_regress/tests.py
index ffb47a8133..c03388b50e 100644
--- a/tests/defer_regress/tests.py
+++ b/tests/defer_regress/tests.py
@@ -245,6 +245,7 @@ class DeferRegressionTest(TestCase):
             new_class.__name__,
             'Item_Deferred_this_is_some_very_long_attribute_nac34b1f495507dad6b02e2cb235c875e')
 
+
 class DeferAnnotateSelectRelatedTest(TestCase):
     def test_defer_annotate_select_related(self):
         location = Location.objects.create()
diff --git a/tests/delete/models.py b/tests/delete/models.py
index 65d4e6f725..408b6b83f8 100644
--- a/tests/delete/models.py
+++ b/tests/delete/models.py
@@ -109,20 +109,26 @@ class HiddenUser(models.Model):
 class HiddenUserProfile(models.Model):
     user = models.ForeignKey(HiddenUser)
 
+
 class M2MTo(models.Model):
     pass
 
+
 class M2MFrom(models.Model):
     m2m = models.ManyToManyField(M2MTo)
 
+
 class Parent(models.Model):
     pass
 
+
 class Child(Parent):
     pass
 
+
 class Base(models.Model):
     pass
 
+
 class RelToBase(models.Model):
     base = models.ForeignKey(Base, on_delete=models.DO_NOTHING)
diff --git a/tests/delete/tests.py b/tests/delete/tests.py
index 7bef83a670..6ecdb01e65 100644
--- a/tests/delete/tests.py
+++ b/tests/delete/tests.py
@@ -167,7 +167,7 @@ class DeletionTests(TestCase):
     def test_bulk(self):
         from django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE
         s = S.objects.create(r=R.objects.create())
-        for i in xrange(2*GET_ITERATOR_CHUNK_SIZE):
+        for i in xrange(2 * GET_ITERATOR_CHUNK_SIZE):
             T.objects.create(s=s)
         #   1 (select related `T` instances)
         # + 1 (select related `U` instances)
@@ -311,6 +311,7 @@ class DeletionTests(TestCase):
         r.delete()
         self.assertEqual(HiddenUserProfile.objects.count(), 0)
 
+
 class FastDeleteTests(TestCase):
 
     def test_fast_delete_fk(self):
diff --git a/tests/delete_regress/models.py b/tests/delete_regress/models.py
index 3632a7dbc1..033689519a 100644
--- a/tests/delete_regress/models.py
+++ b/tests/delete_regress/models.py
@@ -2,51 +2,64 @@ from django.contrib.contenttypes import generic
 from django.contrib.contenttypes.models import ContentType
 from django.db import models
 
+
 class Award(models.Model):
     name = models.CharField(max_length=25)
     object_id = models.PositiveIntegerField()
     content_type = models.ForeignKey(ContentType)
     content_object = generic.GenericForeignKey()
 
+
 class AwardNote(models.Model):
     award = models.ForeignKey(Award)
     note = models.CharField(max_length=100)
 
+
 class Person(models.Model):
     name = models.CharField(max_length=25)
     awards = generic.GenericRelation(Award)
 
+
 class Book(models.Model):
     pagecount = models.IntegerField()
 
+
 class Toy(models.Model):
     name = models.CharField(max_length=50)
 
+
 class Child(models.Model):
     name = models.CharField(max_length=50)
     toys = models.ManyToManyField(Toy, through='PlayedWith')
 
+
 class PlayedWith(models.Model):
     child = models.ForeignKey(Child)
     toy = models.ForeignKey(Toy)
     date = models.DateField(db_column='date_col')
 
+
 class PlayedWithNote(models.Model):
     played = models.ForeignKey(PlayedWith)
     note = models.TextField()
 
+
 class Contact(models.Model):
     label = models.CharField(max_length=100)
 
+
 class Email(Contact):
     email_address = models.EmailField(max_length=100)
 
+
 class Researcher(models.Model):
     contacts = models.ManyToManyField(Contact, related_name="research_contacts")
 
+
 class Food(models.Model):
     name = models.CharField(max_length=20, unique=True)
 
+
 class Eaten(models.Model):
     food = models.ForeignKey(Food, to_field="name")
     meal = models.CharField(max_length=20)
@@ -54,55 +67,70 @@ class Eaten(models.Model):
 
 # Models for #15776
 
+
 class Policy(models.Model):
     policy_number = models.CharField(max_length=10)
 
+
 class Version(models.Model):
     policy = models.ForeignKey(Policy)
 
+
 class Location(models.Model):
     version = models.ForeignKey(Version, blank=True, null=True)
 
+
 class Item(models.Model):
     version = models.ForeignKey(Version)
     location = models.ForeignKey(Location, blank=True, null=True)
 
 # Models for #16128
 
+
 class File(models.Model):
     pass
 
+
 class Image(File):
     class Meta:
         proxy = True
 
+
 class Photo(Image):
     class Meta:
         proxy = True
 
+
 class FooImage(models.Model):
     my_image = models.ForeignKey(Image)
 
+
 class FooFile(models.Model):
     my_file = models.ForeignKey(File)
 
+
 class FooPhoto(models.Model):
     my_photo = models.ForeignKey(Photo)
 
+
 class FooFileProxy(FooFile):
     class Meta:
         proxy = True
 
+
 class OrgUnit(models.Model):
     name = models.CharField(max_length=64, unique=True)
 
+
 class Login(models.Model):
     description = models.CharField(max_length=32)
     orgunit = models.ForeignKey(OrgUnit)
 
+
 class House(models.Model):
     address = models.CharField(max_length=32)
 
+
 class OrderedPerson(models.Model):
     name = models.CharField(max_length=32)
     lives_in = models.ForeignKey(House)
diff --git a/tests/delete_regress/tests.py b/tests/delete_regress/tests.py
index ecc754920c..e1cbe7070f 100644
--- a/tests/delete_regress/tests.py
+++ b/tests/delete_regress/tests.py
@@ -146,7 +146,7 @@ class LargeDeleteTests(TestCase):
     def test_large_deletes(self):
         "Regression for #13309 -- if the number of objects > chunk size, deletion still occurs"
         for x in range(300):
-            Book.objects.create(pagecount=x+100)
+            Book.objects.create(pagecount=x + 100)
         # attach a signal to make sure we will not fast-delete
 
         def noop(*args, **kwargs):
@@ -268,6 +268,7 @@ class ProxyDeleteTest(TestCase):
         with self.assertRaises(TypeError):
             Image.objects.values_list().delete()
 
+
 class Ticket19102Tests(TestCase):
     """
     Test different queries which alter the SELECT clause of the query. We
diff --git a/tests/dispatch/tests/test_dispatcher.py b/tests/dispatch/tests/test_dispatcher.py
index 9a8d7146cf..1ab4a69d33 100644
--- a/tests/dispatch/tests/test_dispatcher.py
+++ b/tests/dispatch/tests/test_dispatcher.py
@@ -23,9 +23,11 @@ else:
     def garbage_collect():
         gc.collect()
 
+
 def receiver_1_arg(val, **kwargs):
     return val
 
+
 class Callable(object):
     def __call__(self, val, **kwargs):
         return val
@@ -116,10 +118,10 @@ class DispatcherTests(unittest.TestCase):
         def uid_based_receiver_2(**kwargs):
             pass
 
-        a_signal.connect(uid_based_receiver_1, dispatch_uid = "uid")
-        a_signal.connect(uid_based_receiver_2, dispatch_uid = "uid")
+        a_signal.connect(uid_based_receiver_1, dispatch_uid="uid")
+        a_signal.connect(uid_based_receiver_2, dispatch_uid="uid")
         self.assertEqual(len(a_signal.receivers), 1)
-        a_signal.disconnect(dispatch_uid = "uid")
+        a_signal.disconnect(dispatch_uid="uid")
         self._testIsClean(a_signal)
 
     def testRobust(self):
diff --git a/tests/dispatch/tests/test_saferef.py b/tests/dispatch/tests/test_saferef.py
index 531e8f43de..6da756362a 100644
--- a/tests/dispatch/tests/test_saferef.py
+++ b/tests/dispatch/tests/test_saferef.py
@@ -3,17 +3,21 @@ import unittest
 from django.dispatch.saferef import safeRef
 from django.utils.six.moves import xrange
 
+
 class Test1(object):
     def x(self):
         pass
 
+
 def test2(obj):
     pass
 
+
 class Test2(object):
     def __call__(self, obj):
         pass
 
+
 class SaferefTests(unittest.TestCase):
     def setUp(self):
         ts = []
diff --git a/tests/distinct_on_fields/models.py b/tests/distinct_on_fields/models.py
index 7982f435d0..053fd9cc5f 100644
--- a/tests/distinct_on_fields/models.py
+++ b/tests/distinct_on_fields/models.py
@@ -3,6 +3,7 @@ from __future__ import unicode_literals
 from django.db import models
 from django.utils.encoding import python_2_unicode_compatible
 
+
 @python_2_unicode_compatible
 class Tag(models.Model):
     name = models.CharField(max_length=10)
@@ -15,6 +16,7 @@ class Tag(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Celebrity(models.Model):
     name = models.CharField("Name", max_length=20)
@@ -23,9 +25,11 @@ class Celebrity(models.Model):
     def __str__(self):
         return self.name
 
+
 class Fan(models.Model):
     fan_of = models.ForeignKey(Celebrity)
 
+
 @python_2_unicode_compatible
 class Staff(models.Model):
     id = models.IntegerField(primary_key=True)
@@ -37,6 +41,7 @@ class Staff(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class StaffTag(models.Model):
     staff = models.ForeignKey(Staff)
diff --git a/tests/distinct_on_fields/tests.py b/tests/distinct_on_fields/tests.py
index e14f06f2ed..9dedd98f81 100644
--- a/tests/distinct_on_fields/tests.py
+++ b/tests/distinct_on_fields/tests.py
@@ -6,6 +6,7 @@ from django.test.utils import str_prefix
 
 from .models import Tag, Celebrity, Fan, Staff, StaffTag
 
+
 @skipUnlessDBFeature('can_distinct_on_fields')
 class DistinctOnTests(TestCase):
     def setUp(self):
@@ -77,7 +78,7 @@ class DistinctOnTests(TestCase):
             # Fetch the alphabetically first coworker for each worker
             (
                 (Staff.objects.distinct('id').order_by('id', 'coworkers__name').
-                               values_list('id', 'coworkers__name')),
+                    values_list('id', 'coworkers__name')),
                 [str_prefix("(1, %(_)s'p2')"), str_prefix("(2, %(_)s'p1')"),
                  str_prefix("(3, %(_)s'p1')"), "(4, None)"]
             ),
diff --git a/tests/expressions/models.py b/tests/expressions/models.py
index f592a0eb13..e66bb0a135 100644
--- a/tests/expressions/models.py
+++ b/tests/expressions/models.py
@@ -15,6 +15,7 @@ class Employee(models.Model):
     def __str__(self):
         return '%s %s' % (self.firstname, self.lastname)
 
+
 @python_2_unicode_compatible
 class Company(models.Model):
     name = models.CharField(max_length=100)
diff --git a/tests/expressions_regress/models.py b/tests/expressions_regress/models.py
index bd3e52f54d..c70338933a 100644
--- a/tests/expressions_regress/models.py
+++ b/tests/expressions_regress/models.py
@@ -14,6 +14,7 @@ class Number(models.Model):
     def __str__(self):
         return '%i, %.3f' % (self.integer, self.float)
 
+
 class Experiment(models.Model):
     name = models.CharField(max_length=24)
     assigned = models.DateField()
diff --git a/tests/expressions_regress/tests.py b/tests/expressions_regress/tests.py
index 0e168e924a..e603c410ac 100644
--- a/tests/expressions_regress/tests.py
+++ b/tests/expressions_regress/tests.py
@@ -79,12 +79,12 @@ class ExpressionsRegressTests(TestCase):
         """
         n = Number.objects.create(integer=10, float=123.45)
         self.assertEqual(Number.objects.filter(pk=n.pk)
-                                .update(float=F('integer') + F('float') * 2),
-                          1)
+            .update(float=F('integer') + F('float') * 2), 1)
 
         self.assertEqual(Number.objects.get(pk=n.pk).integer, 10)
         self.assertEqual(Number.objects.get(pk=n.pk).float, Approximate(256.900, places=3))
 
+
 class ExpressionOperatorTests(TestCase):
     def setUp(self):
         self.n = Number.objects.create(integer=42, float=15.5)
@@ -220,13 +220,13 @@ class FTimeDeltaTests(TestCase):
         self.days_long = []
 
         # e0: started same day as assigned, zero duration
-        end = stime+delta0
+        end = stime + delta0
         e0 = Experiment.objects.create(name='e0', assigned=sday, start=stime,
             end=end, completed=end.date())
         self.deltas.append(delta0)
         self.delays.append(e0.start -
             datetime.datetime.combine(e0.assigned, midnight))
-        self.days_long.append(e0.completed-e0.assigned)
+        self.days_long.append(e0.completed - e0.assigned)
 
         # e1: started one day after assigned, tiny duration, data
         # set so that end time has no fractional seconds, which
@@ -237,86 +237,86 @@ class FTimeDeltaTests(TestCase):
             delay = datetime.timedelta(1)
             end = stime + delay + delta1
             e1 = Experiment.objects.create(name='e1', assigned=sday,
-                start=stime+delay, end=end, completed=end.date())
+                start=stime + delay, end=end, completed=end.date())
             self.deltas.append(delta1)
             self.delays.append(e1.start -
                 datetime.datetime.combine(e1.assigned, midnight))
-            self.days_long.append(e1.completed-e1.assigned)
+            self.days_long.append(e1.completed - e1.assigned)
 
         # e2: started three days after assigned, small duration
-        end = stime+delta2
+        end = stime + delta2
         e2 = Experiment.objects.create(name='e2',
-            assigned=sday-datetime.timedelta(3), start=stime, end=end,
+            assigned=sday - datetime.timedelta(3), start=stime, end=end,
             completed=end.date())
         self.deltas.append(delta2)
         self.delays.append(e2.start -
             datetime.datetime.combine(e2.assigned, midnight))
-        self.days_long.append(e2.completed-e2.assigned)
+        self.days_long.append(e2.completed - e2.assigned)
 
         # e3: started four days after assigned, medium duration
         delay = datetime.timedelta(4)
         end = stime + delay + delta3
         e3 = Experiment.objects.create(name='e3',
-            assigned=sday, start=stime+delay, end=end, completed=end.date())
+            assigned=sday, start=stime + delay, end=end, completed=end.date())
         self.deltas.append(delta3)
         self.delays.append(e3.start -
             datetime.datetime.combine(e3.assigned, midnight))
-        self.days_long.append(e3.completed-e3.assigned)
+        self.days_long.append(e3.completed - e3.assigned)
 
         # e4: started 10 days after assignment, long duration
         end = stime + delta4
         e4 = Experiment.objects.create(name='e4',
-            assigned=sday-datetime.timedelta(10), start=stime, end=end,
+            assigned=sday - datetime.timedelta(10), start=stime, end=end,
             completed=end.date())
         self.deltas.append(delta4)
         self.delays.append(e4.start -
             datetime.datetime.combine(e4.assigned, midnight))
-        self.days_long.append(e4.completed-e4.assigned)
+        self.days_long.append(e4.completed - e4.assigned)
         self.expnames = [e.name for e in Experiment.objects.all()]
 
     def test_delta_add(self):
         for i in range(len(self.deltas)):
             delta = self.deltas[i]
             test_set = [e.name for e in
-                Experiment.objects.filter(end__lt=F('start')+delta)]
+                Experiment.objects.filter(end__lt=F('start') + delta)]
             self.assertEqual(test_set, self.expnames[:i])
 
             test_set = [e.name for e in
-                Experiment.objects.filter(end__lte=F('start')+delta)]
-            self.assertEqual(test_set, self.expnames[:i+1])
+                Experiment.objects.filter(end__lte=F('start') + delta)]
+            self.assertEqual(test_set, self.expnames[:i + 1])
 
     def test_delta_subtract(self):
         for i in range(len(self.deltas)):
             delta = self.deltas[i]
             test_set = [e.name for e in
-                Experiment.objects.filter(start__gt=F('end')-delta)]
+                Experiment.objects.filter(start__gt=F('end') - delta)]
             self.assertEqual(test_set, self.expnames[:i])
 
             test_set = [e.name for e in
-                Experiment.objects.filter(start__gte=F('end')-delta)]
-            self.assertEqual(test_set, self.expnames[:i+1])
+                Experiment.objects.filter(start__gte=F('end') - delta)]
+            self.assertEqual(test_set, self.expnames[:i + 1])
 
     def test_exclude(self):
         for i in range(len(self.deltas)):
             delta = self.deltas[i]
             test_set = [e.name for e in
-                Experiment.objects.exclude(end__lt=F('start')+delta)]
+                Experiment.objects.exclude(end__lt=F('start') + delta)]
             self.assertEqual(test_set, self.expnames[i:])
 
             test_set = [e.name for e in
-                Experiment.objects.exclude(end__lte=F('start')+delta)]
-            self.assertEqual(test_set, self.expnames[i+1:])
+                Experiment.objects.exclude(end__lte=F('start') + delta)]
+            self.assertEqual(test_set, self.expnames[i + 1:])
 
     def test_date_comparison(self):
         for i in range(len(self.days_long)):
             days = self.days_long[i]
             test_set = [e.name for e in
-                Experiment.objects.filter(completed__lt=F('assigned')+days)]
+                Experiment.objects.filter(completed__lt=F('assigned') + days)]
             self.assertEqual(test_set, self.expnames[:i])
 
             test_set = [e.name for e in
-                Experiment.objects.filter(completed__lte=F('assigned')+days)]
-            self.assertEqual(test_set, self.expnames[:i+1])
+                Experiment.objects.filter(completed__lte=F('assigned') + days)]
+            self.assertEqual(test_set, self.expnames[:i + 1])
 
     @skipUnlessDBFeature("supports_mixed_date_datetime_comparisons")
     def test_mixed_comparisons1(self):
@@ -325,35 +325,35 @@ class FTimeDeltaTests(TestCase):
             if not connection.features.supports_microsecond_precision:
                 delay = datetime.timedelta(delay.days, delay.seconds)
             test_set = [e.name for e in
-                Experiment.objects.filter(assigned__gt=F('start')-delay)]
+                Experiment.objects.filter(assigned__gt=F('start') - delay)]
             self.assertEqual(test_set, self.expnames[:i])
 
             test_set = [e.name for e in
-                Experiment.objects.filter(assigned__gte=F('start')-delay)]
-            self.assertEqual(test_set, self.expnames[:i+1])
+                Experiment.objects.filter(assigned__gte=F('start') - delay)]
+            self.assertEqual(test_set, self.expnames[:i + 1])
 
     def test_mixed_comparisons2(self):
         delays = [datetime.timedelta(delay.days) for delay in self.delays]
         for i in range(len(delays)):
             delay = delays[i]
             test_set = [e.name for e in
-                Experiment.objects.filter(start__lt=F('assigned')+delay)]
+                Experiment.objects.filter(start__lt=F('assigned') + delay)]
             self.assertEqual(test_set, self.expnames[:i])
 
             test_set = [e.name for e in
                 Experiment.objects.filter(start__lte=F('assigned') + delay +
                     datetime.timedelta(1))]
-            self.assertEqual(test_set, self.expnames[:i+1])
+            self.assertEqual(test_set, self.expnames[:i + 1])
 
     def test_delta_update(self):
         for i in range(len(self.deltas)):
             delta = self.deltas[i]
             exps = Experiment.objects.all()
             expected_durations = [e.duration() for e in exps]
-            expected_starts = [e.start+delta for e in exps]
-            expected_ends = [e.end+delta for e in exps]
+            expected_starts = [e.start + delta for e in exps]
+            expected_ends = [e.end + delta for e in exps]
 
-            Experiment.objects.update(start=F('start')+delta, end=F('end')+delta)
+            Experiment.objects.update(start=F('start') + delta, end=F('end') + delta)
             exps = Experiment.objects.all()
             new_starts = [e.start for e in exps]
             new_ends = [e.end for e in exps]
@@ -365,7 +365,7 @@ class FTimeDeltaTests(TestCase):
     def test_delta_invalid_op_mult(self):
         raised = False
         try:
-            repr(Experiment.objects.filter(end__lt=F('start')*self.deltas[0]))
+            repr(Experiment.objects.filter(end__lt=F('start') * self.deltas[0]))
         except TypeError:
             raised = True
         self.assertTrue(raised, "TypeError not raised on attempt to multiply datetime by timedelta.")
@@ -373,7 +373,7 @@ class FTimeDeltaTests(TestCase):
     def test_delta_invalid_op_div(self):
         raised = False
         try:
-            repr(Experiment.objects.filter(end__lt=F('start')/self.deltas[0]))
+            repr(Experiment.objects.filter(end__lt=F('start') / self.deltas[0]))
         except TypeError:
             raised = True
         self.assertTrue(raised, "TypeError not raised on attempt to divide datetime by timedelta.")
diff --git a/tests/extra_regress/models.py b/tests/extra_regress/models.py
index 5523a06a8a..432aa02963 100644
--- a/tests/extra_regress/models.py
+++ b/tests/extra_regress/models.py
@@ -30,10 +30,12 @@ class RevisionableModel(models.Model):
         new_revision.pk = None
         return new_revision
 
+
 class Order(models.Model):
     created_by = models.ForeignKey(User)
     text = models.TextField()
 
+
 @python_2_unicode_compatible
 class TestObject(models.Model):
     first = models.CharField(max_length=20)
diff --git a/tests/field_subclassing/fields.py b/tests/field_subclassing/fields.py
index a3867e3671..e9c7a982e8 100644
--- a/tests/field_subclassing/fields.py
+++ b/tests/field_subclassing/fields.py
@@ -20,6 +20,7 @@ class Small(object):
     def __str__(self):
         return '%s%s' % (force_text(self.first), force_text(self.second))
 
+
 class SmallField(six.with_metaclass(models.SubfieldBase, models.Field)):
     """
     Turns the "Small" class into a Django field. Because of the similarities
@@ -51,6 +52,7 @@ class SmallField(six.with_metaclass(models.SubfieldBase, models.Field)):
             return []
         raise TypeError('Invalid lookup type: %r' % lookup_type)
 
+
 class SmallerField(SmallField):
     pass
 
diff --git a/tests/field_subclassing/models.py b/tests/field_subclassing/models.py
index 67a95b02f2..c2f7e4f66b 100644
--- a/tests/field_subclassing/models.py
+++ b/tests/field_subclassing/models.py
@@ -17,8 +17,10 @@ class MyModel(models.Model):
     def __str__(self):
         return force_text(self.name)
 
+
 class OtherModel(models.Model):
     data = SmallerField()
 
+
 class DataModel(models.Model):
     data = JSONField()
diff --git a/tests/file_storage/models.py b/tests/file_storage/models.py
index eea3ddaf09..738a3a1772 100644
--- a/tests/file_storage/models.py
+++ b/tests/file_storage/models.py
@@ -15,6 +15,7 @@ from django.core.files.storage import FileSystemStorage
 temp_storage_location = tempfile.mkdtemp()
 temp_storage = FileSystemStorage(location=temp_storage_location)
 
+
 class Storage(models.Model):
     def custom_upload_to(self, filename):
         return 'foo'
diff --git a/tests/file_storage/tests.py b/tests/file_storage/tests.py
index 1f676d04b1..20eaf4c89c 100644
--- a/tests/file_storage/tests.py
+++ b/tests/file_storage/tests.py
@@ -69,6 +69,7 @@ class GetStorageClassTests(SimpleTestCase):
             get_storage_class(
                 'django.core.files.non_existing_storage.NonExistingStorage')
 
+
 class FileStorageTests(unittest.TestCase):
     storage_class = FileSystemStorage
 
@@ -379,6 +380,7 @@ class CustomStorage(FileSystemStorage):
 
         return name
 
+
 class CustomStorageTests(FileStorageTests):
     storage_class = CustomStorage
 
@@ -531,6 +533,7 @@ class SlowFile(ContentFile):
         time.sleep(1)
         return super(ContentFile, self).chunks()
 
+
 class FileSaveRaceConditionTest(unittest.TestCase):
     def setUp(self):
         self.storage_dir = tempfile.mkdtemp()
@@ -552,6 +555,7 @@ class FileSaveRaceConditionTest(unittest.TestCase):
         self.storage.delete('conflict')
         self.storage.delete('conflict_1')
 
+
 @unittest.skipIf(sys.platform.startswith('win'), "Windows only partially supports umasks and chmod.")
 class FileStoragePermissions(unittest.TestCase):
     def setUp(self):
@@ -591,6 +595,7 @@ class FileStoragePermissions(unittest.TestCase):
         dir_mode = os.stat(os.path.dirname(self.storage.path(name)))[0] & 0o777
         self.assertEqual(dir_mode, 0o777 & ~self.umask)
 
+
 class FileStoragePathParsing(unittest.TestCase):
     def setUp(self):
         self.storage_dir = tempfile.mkdtemp()
diff --git a/tests/file_uploads/tests.py b/tests/file_uploads/tests.py
index 72f9d7a77c..7aa6797630 100644
--- a/tests/file_uploads/tests.py
+++ b/tests/file_uploads/tests.py
@@ -397,6 +397,7 @@ class FileUploadTests(TestCase):
         # shouldn't differ.
         self.assertEqual(os.path.basename(obj.testfile.path), 'MiXeD_cAsE.txt')
 
+
 @override_settings(MEDIA_ROOT=MEDIA_ROOT)
 class DirectoryCreationTests(TestCase):
     """
@@ -436,7 +437,7 @@ class DirectoryCreationTests(TestCase):
         # The test needs to be done on a specific string as IOError
         # is raised even without the patch (just not early enough)
         self.assertEqual(exc_info.exception.args[0],
-                          "%s exists and is not a directory." % UPLOAD_TO)
+            "%s exists and is not a directory." % UPLOAD_TO)
 
 
 class MultiParserTests(unittest.TestCase):
diff --git a/tests/file_uploads/uploadhandler.py b/tests/file_uploads/uploadhandler.py
index 2d4e52e4d5..b69cc751cb 100644
--- a/tests/file_uploads/uploadhandler.py
+++ b/tests/file_uploads/uploadhandler.py
@@ -11,7 +11,7 @@ class QuotaUploadHandler(FileUploadHandler):
     (5MB) is uploaded.
     """
 
-    QUOTA = 5 * 2**20  # 5 MB
+    QUOTA = 5 * 2 ** 20  # 5 MB
 
     def __init__(self, request=None):
         super(QuotaUploadHandler, self).__init__(request)
@@ -26,9 +26,11 @@ class QuotaUploadHandler(FileUploadHandler):
     def file_complete(self, file_size):
         return None
 
+
 class CustomUploadError(Exception):
     pass
 
+
 class ErroringUploadHandler(FileUploadHandler):
     """A handler that raises an exception."""
     def receive_data_chunk(self, raw_data, start):
diff --git a/tests/file_uploads/views.py b/tests/file_uploads/views.py
index 1940987815..a29391af6e 100644
--- a/tests/file_uploads/views.py
+++ b/tests/file_uploads/views.py
@@ -30,6 +30,7 @@ def file_upload_view(request):
     else:
         return HttpResponseServerError()
 
+
 def file_upload_view_verify(request):
     """
     Use the sha digest hash to verify the uploaded contents.
@@ -57,6 +58,7 @@ def file_upload_view_verify(request):
 
     return HttpResponse('')
 
+
 def file_upload_unicode_name(request):
 
     # Check to see if unicode name came through properly.
@@ -85,6 +87,7 @@ def file_upload_unicode_name(request):
     else:
         return HttpResponse('')
 
+
 def file_upload_echo(request):
     """
     Simple view to echo back info about uploaded files for tests.
@@ -92,6 +95,7 @@ def file_upload_echo(request):
     r = dict((k, f.name) for k, f in request.FILES.items())
     return HttpResponse(json.dumps(r))
 
+
 def file_upload_echo_content(request):
     """
     Simple view to echo back the content of uploaded files for tests.
@@ -99,6 +103,7 @@ def file_upload_echo_content(request):
     r = dict((k, f.read().decode('utf-8')) for k, f in request.FILES.items())
     return HttpResponse(json.dumps(r))
 
+
 def file_upload_quota(request):
     """
     Dynamically add in an upload handler.
@@ -106,6 +111,7 @@ def file_upload_quota(request):
     request.upload_handlers.insert(0, QuotaUploadHandler())
     return file_upload_echo(request)
 
+
 def file_upload_quota_broken(request):
     """
     You can't change handlers after reading FILES; this view shouldn't work.
@@ -114,6 +120,7 @@ def file_upload_quota_broken(request):
     request.upload_handlers.insert(0, QuotaUploadHandler())
     return response
 
+
 def file_upload_getlist_count(request):
     """
     Check the .getlist() function to ensure we receive the correct number of files.
@@ -124,10 +131,12 @@ def file_upload_getlist_count(request):
         file_counts[key] = len(request.FILES.getlist(key))
     return HttpResponse(json.dumps(file_counts))
 
+
 def file_upload_errors(request):
     request.upload_handlers.insert(0, ErroringUploadHandler())
     return file_upload_echo(request)
 
+
 def file_upload_filename_case_view(request):
     """
     Check adding the file to the database will preserve the filename case.
@@ -137,6 +146,7 @@ def file_upload_filename_case_view(request):
     obj.testfile.save(file.name, file)
     return HttpResponse('%d' % obj.pk)
 
+
 def file_upload_content_type_extra(request):
     """
     Simple view to echo back extra content-type parameters.
diff --git a/tests/fixtures/models.py b/tests/fixtures/models.py
index 56bb601c27..08cb02ce72 100644
--- a/tests/fixtures/models.py
+++ b/tests/fixtures/models.py
@@ -26,6 +26,7 @@ class Category(models.Model):
     class Meta:
         ordering = ('title',)
 
+
 @python_2_unicode_compatible
 class Article(models.Model):
     headline = models.CharField(max_length=100, default='Default headline')
@@ -37,6 +38,7 @@ class Article(models.Model):
     class Meta:
         ordering = ('-pub_date', 'headline')
 
+
 @python_2_unicode_compatible
 class Blog(models.Model):
     name = models.CharField(max_length=100)
@@ -60,10 +62,12 @@ class Tag(models.Model):
         return '<%s: %s> tagged "%s"' % (self.tagged.__class__.__name__,
                                          self.tagged, self.name)
 
+
 class PersonManager(models.Manager):
     def get_by_natural_key(self, name):
         return self.get(name=name)
 
+
 @python_2_unicode_compatible
 class Person(models.Model):
     objects = PersonManager()
@@ -78,14 +82,17 @@ class Person(models.Model):
     def natural_key(self):
         return (self.name,)
 
+
 class SpyManager(PersonManager):
     def get_queryset(self):
         return super(SpyManager, self).get_queryset().filter(cover_blown=False)
 
+
 class Spy(Person):
     objects = SpyManager()
     cover_blown = models.BooleanField(default=False)
 
+
 @python_2_unicode_compatible
 class Visa(models.Model):
     person = models.ForeignKey(Person)
@@ -95,6 +102,7 @@ class Visa(models.Model):
         return '%s %s' % (self.person.name,
                           ', '.join(p.name for p in self.permissions.all()))
 
+
 @python_2_unicode_compatible
 class Book(models.Model):
     name = models.CharField(max_length=100)
diff --git a/tests/fixtures_model_package/models/__init__.py b/tests/fixtures_model_package/models/__init__.py
index deeba48aa9..c48cfd451d 100644
--- a/tests/fixtures_model_package/models/__init__.py
+++ b/tests/fixtures_model_package/models/__init__.py
@@ -14,6 +14,7 @@ class Article(models.Model):
         app_label = 'fixtures_model_package'
         ordering = ('-pub_date', 'headline')
 
+
 class Book(models.Model):
     name = models.CharField(max_length=100)
 
diff --git a/tests/fixtures_regress/models.py b/tests/fixtures_regress/models.py
index 4b33cef09b..95f9488ab7 100644
--- a/tests/fixtures_regress/models.py
+++ b/tests/fixtures_regress/models.py
@@ -27,6 +27,7 @@ class Plant(models.Model):
         # For testing when upper case letter in app name; regression for #4057
         db_table = "Fixtures_regress_plant"
 
+
 @python_2_unicode_compatible
 class Stuff(models.Model):
     name = models.CharField(max_length=20, null=True)
diff --git a/tests/force_insert_update/models.py b/tests/force_insert_update/models.py
index 56d6624e0d..7067613ccd 100644
--- a/tests/force_insert_update/models.py
+++ b/tests/force_insert_update/models.py
@@ -9,16 +9,20 @@ class Counter(models.Model):
     name = models.CharField(max_length = 10)
     value = models.IntegerField()
 
+
 class InheritedCounter(Counter):
     tag = models.CharField(max_length=10)
 
+
 class ProxyCounter(Counter):
     class Meta:
         proxy = True
 
+
 class SubCounter(Counter):
     pass
 
+
 class WithCustomPK(models.Model):
     name = models.IntegerField(primary_key=True)
     value = models.IntegerField()
diff --git a/tests/foreign_object/models.py b/tests/foreign_object/models.py
index d8c3bc10d4..7673d27af6 100644
--- a/tests/foreign_object/models.py
+++ b/tests/foreign_object/models.py
@@ -5,6 +5,7 @@ from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor
 from django.utils.encoding import python_2_unicode_compatible
 from django.utils.translation import get_language
 
+
 @python_2_unicode_compatible
 class Country(models.Model):
     # Table Column Fields
@@ -13,6 +14,7 @@ class Country(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Person(models.Model):
     # Table Column Fields
@@ -30,6 +32,7 @@ class Person(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Group(models.Model):
     # Table Column Fields
@@ -96,6 +99,7 @@ class Friendship(models.Model):
         to_fields=['person_country_id', 'id'],
         related_name='to_friend')
 
+
 class ArticleTranslationDescriptor(ReverseSingleRelatedObjectDescriptor):
     """
     The set of articletranslation should not set any local fields.
@@ -107,6 +111,7 @@ class ArticleTranslationDescriptor(ReverseSingleRelatedObjectDescriptor):
         if value is not None and not self.field.rel.multiple:
             setattr(value, self.field.related.get_cache_name(), instance)
 
+
 class ColConstraint(object):
     # Antyhing with as_sql() method works in get_extra_restriction().
     def __init__(self, alias, col, value):
@@ -115,6 +120,7 @@ class ColConstraint(object):
     def as_sql(self, qn, connection):
         return '%s.%s = %%s' % (qn(self.alias), qn(self.col)), [self.value]
 
+
 class ActiveTranslationField(models.ForeignObject):
     """
     This field will allow querying and fetching the currently active translation
@@ -132,6 +138,7 @@ class ActiveTranslationField(models.ForeignObject):
         super(ActiveTranslationField, self).contribute_to_class(cls, name)
         setattr(cls, self.name, ArticleTranslationDescriptor(self))
 
+
 @python_2_unicode_compatible
 class Article(models.Model):
     active_translation = ActiveTranslationField(
@@ -148,9 +155,11 @@ class Article(models.Model):
         except ArticleTranslation.DoesNotExist:
             return '[No translation found]'
 
+
 class NewsArticle(Article):
     pass
 
+
 class ArticleTranslation(models.Model):
     article = models.ForeignKey(Article)
     lang = models.CharField(max_length='2')
@@ -162,10 +171,12 @@ class ArticleTranslation(models.Model):
         unique_together = ('article', 'lang')
         ordering = ('active_translation__title',)
 
+
 class ArticleTag(models.Model):
     article = models.ForeignKey(Article, related_name="tags", related_query_name="tag")
     name = models.CharField(max_length=255)
 
+
 class ArticleIdea(models.Model):
     articles = models.ManyToManyField(Article, related_name="ideas",
                                       related_query_name="idea_things")
diff --git a/tests/foreign_object/tests.py b/tests/foreign_object/tests.py
index 77582162a8..66f57b6f3c 100644
--- a/tests/foreign_object/tests.py
+++ b/tests/foreign_object/tests.py
@@ -12,6 +12,7 @@ from django import forms
 # Note that these tests are testing internal implementation details.
 # ForeignObject is not part of public API.
 
+
 class MultiColumnFKTests(TestCase):
     def setUp(self):
         # Creating countries
@@ -379,6 +380,7 @@ class MultiColumnFKTests(TestCase):
                     'active_translation')[0].active_translation.title,
                 "foo")
 
+
 class FormsTests(TestCase):
     # ForeignObjects should not have any form fields, currently the user needs
     # to manually deal with the foreignobject relation.
diff --git a/tests/forms_tests/models.py b/tests/forms_tests/models.py
index 33898ffbb8..8ade923a91 100644
--- a/tests/forms_tests/models.py
+++ b/tests/forms_tests/models.py
@@ -19,6 +19,8 @@ class BoundaryModel(models.Model):
 
 
 callable_default_value = 0
+
+
 def callable_default():
     global callable_default_value
     callable_default_value = callable_default_value + 1
@@ -27,7 +29,7 @@ def callable_default():
 
 class Defaults(models.Model):
     name = models.CharField(max_length=255, default='class default value')
-    def_date = models.DateField(default = datetime.date(1980, 1, 1))
+    def_date = models.DateField(default=datetime.date(1980, 1, 1))
     value = models.IntegerField(default=42)
     callable_default = models.IntegerField(default=callable_default)
 
@@ -86,6 +88,7 @@ class ChoiceFieldModel(models.Model):
     multi_choice_int = models.ManyToManyField(ChoiceOptionModel, blank=False, related_name='multi_choice_int',
                                               default=lambda: [1])
 
+
 class OptionalMultiChoiceModel(models.Model):
     multi_choice = models.ManyToManyField(ChoiceOptionModel, blank=False, related_name='not_relevant',
                                           default=lambda: ChoiceOptionModel.objects.filter(name='default'))
diff --git a/tests/forms_tests/tests/test_error_messages.py b/tests/forms_tests/tests/test_error_messages.py
index 2d532c7cf9..86f26df3bc 100644
--- a/tests/forms_tests/tests/test_error_messages.py
+++ b/tests/forms_tests/tests/test_error_messages.py
@@ -24,6 +24,7 @@ class AssertFormErrorsMixin(object):
         except ValidationError as e:
             self.assertEqual(e.messages, expected)
 
+
 class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin):
     def test_charfield(self):
         e = {
diff --git a/tests/forms_tests/tests/test_extra.py b/tests/forms_tests/tests/test_extra.py
index 183b5dabdf..4585a4e6ef 100644
--- a/tests/forms_tests/tests/test_extra.py
+++ b/tests/forms_tests/tests/test_extra.py
@@ -25,12 +25,15 @@ from .test_error_messages import AssertFormErrorsMixin
 class GetDate(Form):
     mydate = DateField(widget=SelectDateWidget)
 
+
 class GetNotRequiredDate(Form):
     mydate = DateField(widget=SelectDateWidget, required=False)
 
+
 class GetDateShowHiddenInitial(Form):
     mydate = DateField(widget=SelectDateWidget, show_hidden_initial=True)
 
+
 class FormsExtraTestCase(TestCase, AssertFormErrorsMixin):
     ###############
     # Extra stuff #
diff --git a/tests/forms_tests/tests/test_formsets.py b/tests/forms_tests/tests/test_formsets.py
index cf721b5510..52dfdf4044 100644
--- a/tests/forms_tests/tests/test_formsets.py
+++ b/tests/forms_tests/tests/test_formsets.py
@@ -57,7 +57,7 @@ SplitDateTimeFormSet = formset_factory(SplitDateTimeForm)
 class FormsFormsetTestCase(TestCase):
 
     def make_choiceformset(self, formset_data=None, formset_class=ChoiceFormSet,
-        total_forms=None, initial_forms=0, max_num_forms=0, min_num_forms=0, **kwargs):
+            total_forms=None, initial_forms=0, max_num_forms=0, min_num_forms=0, **kwargs):
         """
         Make a ChoiceFormset from the given formset_data.
         The data should be given as a list of (choice, votes) tuples.
@@ -1097,12 +1097,14 @@ data = {
     'choices-0-votes': '100',
 }
 
+
 class Choice(Form):
     choice = CharField()
     votes = IntegerField()
 
 ChoiceFormSet = formset_factory(Choice)
 
+
 class FormsetAsFooTests(TestCase):
     def test_as_table(self):
         formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
@@ -1130,6 +1132,7 @@ class ArticleForm(Form):
 
 ArticleFormSet = formset_factory(ArticleForm)
 
+
 class TestIsBoundBehavior(TestCase):
     def test_no_data_raises_validation_error(self):
         with self.assertRaises(ValidationError):
@@ -1184,6 +1187,7 @@ class TestIsBoundBehavior(TestCase):
         # The empty forms should be equal.
         self.assertHTMLEqual(empty_forms[0].as_p(), empty_forms[1].as_p())
 
+
 class TestEmptyFormSet(TestCase):
     def test_empty_formset_is_valid(self):
         """Test that an empty formset still calls clean()"""
diff --git a/tests/forms_tests/tests/test_input_formats.py b/tests/forms_tests/tests/test_input_formats.py
index 25b491a499..b9c29c7609 100644
--- a/tests/forms_tests/tests/test_input_formats.py
+++ b/tests/forms_tests/tests/test_input_formats.py
@@ -490,6 +490,7 @@ class CustomDateInputFormatsTests(SimpleTestCase):
         text = f.widget._format_value(result)
         self.assertEqual(text, "21.12.2010")
 
+
 class SimpleDateFormatTests(SimpleTestCase):
     def test_dateField(self):
         "DateFields can parse dates in the default format"
@@ -776,6 +777,7 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
         text = f.widget._format_value(result)
         self.assertEqual(text, "01:30:00 PM 21/12/2010")
 
+
 class SimpleDateTimeFormatTests(SimpleTestCase):
     def test_dateTimeField(self):
         "DateTimeFields can parse dates in the default format"
diff --git a/tests/forms_tests/tests/test_widgets.py b/tests/forms_tests/tests/test_widgets.py
index c601a3ad58..21134d1a24 100644
--- a/tests/forms_tests/tests/test_widgets.py
+++ b/tests/forms_tests/tests/test_widgets.py
@@ -286,7 +286,7 @@ class FormsWidgetTestCase(TestCase):
         things = ({'id': 1, 'name': 'And Boom'}, {'id': 2, 'name': 'One More Thing!'})
 
         class SomeForm(Form):
-            somechoice = ChoiceField(choices=chain((('', '-'*9),), [(thing['id'], thing['name']) for thing in things]))
+            somechoice = ChoiceField(choices=chain((('', '-' * 9),), [(thing['id'], thing['name']) for thing in things]))
         f = SomeForm()
         self.assertHTMLEqual(f.as_table(), '<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="" selected="selected">---------</option>\n<option value="1">And Boom</option>\n<option value="2">One More Thing!</option>\n</select></td></tr>')
         self.assertHTMLEqual(f.as_table(), '<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="" selected="selected">---------</option>\n<option value="1">And Boom</option>\n<option value="2">One More Thing!</option>\n</select></td></tr>')
@@ -1003,6 +1003,7 @@ class NullBooleanSelectLazyForm(Form):
     """Form to test for lazy evaluation. Refs #17190"""
     bool = BooleanField(widget=NullBooleanSelect())
 
+
 @override_settings(USE_L10N=True)
 class FormsI18NWidgetsTestCase(TestCase):
     def setUp(self):
@@ -1136,6 +1137,7 @@ class FakeFieldFile(object):
     def __str__(self):
         return self.url
 
+
 class ClearableFileInputTests(TestCase):
     def test_clear_input_renders(self):
         """
diff --git a/tests/forms_tests/tests/tests.py b/tests/forms_tests/tests/tests.py
index 8212d4ee5c..622b6386e9 100644
--- a/tests/forms_tests/tests/tests.py
+++ b/tests/forms_tests/tests/tests.py
@@ -217,6 +217,7 @@ class FormsModelTestCase(TestCase):
         self.assertEqual(obj.value, 99)
         self.assertEqual(obj.def_date, datetime.date(1999, 3, 2))
 
+
 class RelatedModelFormTests(TestCase):
     def test_invalid_loading_order(self):
         """
diff --git a/tests/generic_inline_admin/admin.py b/tests/generic_inline_admin/admin.py
index 1917024fa5..c701e4a9eb 100644
--- a/tests/generic_inline_admin/admin.py
+++ b/tests/generic_inline_admin/admin.py
@@ -7,6 +7,7 @@ from .models import (Media, PhoneNumber, Episode, EpisodeExtra, Contact,
 
 site = admin.AdminSite(name="admin")
 
+
 class MediaInline(generic.GenericTabularInline):
     model = Media
 
diff --git a/tests/generic_inline_admin/models.py b/tests/generic_inline_admin/models.py
index cc7de62454..af3a474cdf 100644
--- a/tests/generic_inline_admin/models.py
+++ b/tests/generic_inline_admin/models.py
@@ -34,6 +34,7 @@ class Media(models.Model):
 # Generic inline with extra = 0
 #
 
+
 class EpisodeExtra(Episode):
     pass
 
@@ -67,6 +68,7 @@ class Contact(models.Model):
     name = models.CharField(max_length=50)
     phone_numbers = generic.GenericRelation(PhoneNumber)
 
+
 #
 # Generic inline with can_delete=False
 #
diff --git a/tests/generic_inline_admin/tests.py b/tests/generic_inline_admin/tests.py
index 23f17f7b22..09a802a1bc 100644
--- a/tests/generic_inline_admin/tests.py
+++ b/tests/generic_inline_admin/tests.py
@@ -129,6 +129,7 @@ class GenericAdminViewTest(TestCase):
         formset = inline_formset(instance=e)
         self.assertTrue(formset.get_queryset().ordered)
 
+
 @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
 class GenericInlineAdminParametersTest(TestCase):
     urls = "generic_inline_admin.urls"
@@ -210,6 +211,7 @@ class GenericInlineAdminWithUniqueTogetherTest(TestCase):
         response = self.client.post('/generic_inline_admin/admin/generic_inline_admin/contact/add/', post_data)
         self.assertEqual(response.status_code, 302)  # redirect somewhere
 
+
 class NoInlineDeletionTest(TestCase):
     urls = "generic_inline_admin.urls"
 
@@ -224,6 +226,7 @@ class NoInlineDeletionTest(TestCase):
 class MockRequest(object):
     pass
 
+
 class MockSuperUser(object):
     def has_perm(self, perm):
         return True
diff --git a/tests/generic_relations/tests.py b/tests/generic_relations/tests.py
index 60821903d9..8cd319bf03 100644
--- a/tests/generic_relations/tests.py
+++ b/tests/generic_relations/tests.py
@@ -290,12 +290,14 @@ class GenericRelationsTests(TestCase):
 class CustomWidget(forms.TextInput):
     pass
 
+
 class TaggedItemForm(forms.ModelForm):
     class Meta:
         model = TaggedItem
         fields = '__all__'
         widgets = {'tag': CustomWidget}
 
+
 class GenericInlineFormsetTest(TestCase):
     def test_generic_inlineformset_factory(self):
         """
diff --git a/tests/generic_relations_regress/models.py b/tests/generic_relations_regress/models.py
index d716f09058..300ed9d54a 100644
--- a/tests/generic_relations_regress/models.py
+++ b/tests/generic_relations_regress/models.py
@@ -8,6 +8,7 @@ __all__ = ('Link', 'Place', 'Restaurant', 'Person', 'Address',
            'CharLink', 'TextLink', 'OddRelation1', 'OddRelation2',
            'Contact', 'Organization', 'Note', 'Company')
 
+
 @python_2_unicode_compatible
 class Link(models.Model):
     content_type = models.ForeignKey(ContentType)
@@ -17,6 +18,7 @@ class Link(models.Model):
     def __str__(self):
         return "Link to %s id=%s" % (self.content_type, self.object_id)
 
+
 @python_2_unicode_compatible
 class Place(models.Model):
     name = models.CharField(max_length=100)
@@ -25,11 +27,13 @@ class Place(models.Model):
     def __str__(self):
         return "Place: %s" % self.name
 
+
 @python_2_unicode_compatible
 class Restaurant(Place):
     def __str__(self):
         return "Restaurant: %s" % self.name
 
+
 @python_2_unicode_compatible
 class Address(models.Model):
     street = models.CharField(max_length=80)
@@ -43,6 +47,7 @@ class Address(models.Model):
     def __str__(self):
         return '%s %s, %s %s' % (self.street, self.city, self.state, self.zipcode)
 
+
 @python_2_unicode_compatible
 class Person(models.Model):
     account = models.IntegerField(primary_key=True)
@@ -52,24 +57,29 @@ class Person(models.Model):
     def __str__(self):
         return self.name
 
+
 class CharLink(models.Model):
     content_type = models.ForeignKey(ContentType)
     object_id = models.CharField(max_length=100)
     content_object = generic.GenericForeignKey()
 
+
 class TextLink(models.Model):
     content_type = models.ForeignKey(ContentType)
     object_id = models.TextField()
     content_object = generic.GenericForeignKey()
 
+
 class OddRelation1(models.Model):
     name = models.CharField(max_length=100)
     clinks = generic.GenericRelation(CharLink)
 
+
 class OddRelation2(models.Model):
     name = models.CharField(max_length=100)
     tlinks = generic.GenericRelation(TextLink)
 
+
 # models for test_q_object_or:
 class Note(models.Model):
     content_type = models.ForeignKey(ContentType)
@@ -77,13 +87,16 @@ class Note(models.Model):
     content_object = generic.GenericForeignKey()
     note = models.TextField()
 
+
 class Contact(models.Model):
     notes = generic.GenericRelation(Note)
 
+
 class Organization(models.Model):
     name = models.CharField(max_length=255)
     contacts = models.ManyToManyField(Contact, related_name='organizations')
 
+
 @python_2_unicode_compatible
 class Company(models.Model):
     name = models.CharField(max_length=100)
@@ -92,10 +105,12 @@ class Company(models.Model):
     def __str__(self):
         return "Company: %s" % self.name
 
+
 # For testing #13085 fix, we also use Note model defined above
 class Developer(models.Model):
     name = models.CharField(max_length=15)
 
+
 @python_2_unicode_compatible
 class Team(models.Model):
     name = models.CharField(max_length=15)
@@ -107,49 +122,59 @@ class Team(models.Model):
     def __len__(self):
         return self.members.count()
 
+
 class Guild(models.Model):
     name = models.CharField(max_length=15)
     members = models.ManyToManyField(Developer)
 
     def __nonzero__(self):
+
         return self.members.count()
 
+
 class Tag(models.Model):
     content_type = models.ForeignKey(ContentType, related_name='g_r_r_tags')
     object_id = models.CharField(max_length=15)
     content_object = generic.GenericForeignKey()
     label = models.CharField(max_length=15)
 
+
 class Board(models.Model):
     name = models.CharField(primary_key=True, max_length=15)
 
+
 class HasLinks(models.Model):
     links = generic.GenericRelation(Link)
 
     class Meta:
         abstract = True
 
+
 class HasLinkThing(HasLinks):
     pass
 
+
 class A(models.Model):
     flag = models.NullBooleanField()
     content_type = models.ForeignKey(ContentType)
     object_id = models.PositiveIntegerField()
     content_object = generic.GenericForeignKey('content_type', 'object_id')
 
+
 class B(models.Model):
     a = generic.GenericRelation(A)
 
     class Meta:
         ordering = ('id',)
 
+
 class C(models.Model):
     b = models.ForeignKey(B)
 
     class Meta:
         ordering = ('id',)
 
+
 class D(models.Model):
     b = models.ForeignKey(B, null=True)
 
diff --git a/tests/generic_views/models.py b/tests/generic_views/models.py
index 30c73d67ca..f5554d1a20 100644
--- a/tests/generic_views/models.py
+++ b/tests/generic_views/models.py
@@ -18,6 +18,7 @@ class Artist(models.Model):
     def get_absolute_url(self):
         return reverse('artist_detail', kwargs={'pk': self.id})
 
+
 @python_2_unicode_compatible
 class Author(models.Model):
     name = models.CharField(max_length=100)
@@ -29,6 +30,7 @@ class Author(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Book(models.Model):
     name = models.CharField(max_length=300)
@@ -43,9 +45,11 @@ class Book(models.Model):
     def __str__(self):
         return self.name
 
+
 class Page(models.Model):
     content = models.TextField()
     template = models.CharField(max_length=300)
 
+
 class BookSigning(models.Model):
     event_date = models.DateTimeField()
diff --git a/tests/generic_views/test_base.py b/tests/generic_views/test_base.py
index eafa61a271..66ce224162 100644
--- a/tests/generic_views/test_base.py
+++ b/tests/generic_views/test_base.py
@@ -10,6 +10,7 @@ from django.views.generic import View, TemplateView, RedirectView
 
 from . import views
 
+
 class SimpleView(View):
     """
     A simple view with a docstring.
diff --git a/tests/generic_views/test_dates.py b/tests/generic_views/test_dates.py
index 58ee0dfcbe..944a3dcfe3 100644
--- a/tests/generic_views/test_dates.py
+++ b/tests/generic_views/test_dates.py
@@ -15,9 +15,10 @@ def _make_books(n, base_date):
         Book.objects.create(
             name='Book %d' % i,
             slug='book-%d' % i,
-            pages=100+i,
+            pages=100 + i,
             pubdate=base_date - datetime.timedelta(days=i))
 
+
 class ArchiveIndexViewTests(TestCase):
     fixtures = ['generic-views-test-data.json']
     urls = 'generic_views.urls'
diff --git a/tests/generic_views/views.py b/tests/generic_views/views.py
index fd88debc0f..00e74d4708 100644
--- a/tests/generic_views/views.py
+++ b/tests/generic_views/views.py
@@ -65,6 +65,7 @@ class CustomPaginator(Paginator):
             orphans=2,
             allow_empty_first_page=allow_empty_first_page)
 
+
 class AuthorListCustomPaginator(AuthorList):
     paginate_by = 5
 
@@ -176,33 +177,42 @@ class BookConfig(object):
     queryset = Book.objects.all()
     date_field = 'pubdate'
 
+
 class BookArchive(BookConfig, generic.ArchiveIndexView):
     pass
 
+
 class BookYearArchive(BookConfig, generic.YearArchiveView):
     pass
 
+
 class BookMonthArchive(BookConfig, generic.MonthArchiveView):
     pass
 
+
 class BookWeekArchive(BookConfig, generic.WeekArchiveView):
     pass
 
+
 class BookDayArchive(BookConfig, generic.DayArchiveView):
     pass
 
+
 class BookTodayArchive(BookConfig, generic.TodayArchiveView):
     pass
 
+
 class BookDetail(BookConfig, generic.DateDetailView):
     pass
 
+
 class AuthorGetQuerySetFormView(generic.edit.ModelFormMixin):
     fields = '__all__'
 
     def get_queryset(self):
         return Author.objects.all()
 
+
 class BookDetailGetObjectCustomQueryset(BookDetail):
     def get_object(self, queryset=None):
         return super(BookDetailGetObjectCustomQueryset, self).get_object(
@@ -234,10 +244,12 @@ class CustomContextView(generic.detail.SingleObjectMixin, generic.View):
     def get_context_object_name(self, obj):
         return "test_name"
 
+
 class CustomSingleObjectView(generic.detail.SingleObjectMixin, generic.View):
     model = Book
     object = Book(name="dummy")
 
+
 class BookSigningConfig(object):
     model = BookSigning
     date_field = 'event_date'
@@ -246,24 +258,31 @@ class BookSigningConfig(object):
     def get_template_names(self):
         return ['generic_views/book%s.html' % self.template_name_suffix]
 
+
 class BookSigningArchive(BookSigningConfig, generic.ArchiveIndexView):
     pass
 
+
 class BookSigningYearArchive(BookSigningConfig, generic.YearArchiveView):
     pass
 
+
 class BookSigningMonthArchive(BookSigningConfig, generic.MonthArchiveView):
     pass
 
+
 class BookSigningWeekArchive(BookSigningConfig, generic.WeekArchiveView):
     pass
 
+
 class BookSigningDayArchive(BookSigningConfig, generic.DayArchiveView):
     pass
 
+
 class BookSigningTodayArchive(BookSigningConfig, generic.TodayArchiveView):
     pass
 
+
 class BookSigningDetail(BookSigningConfig, generic.DateDetailView):
     context_object_name = 'book'
 
diff --git a/tests/get_object_or_404/models.py b/tests/get_object_or_404/models.py
index bb9aa60383..ea6e3e40d5 100644
--- a/tests/get_object_or_404/models.py
+++ b/tests/get_object_or_404/models.py
@@ -21,10 +21,12 @@ class Author(models.Model):
     def __str__(self):
         return self.name
 
+
 class ArticleManager(models.Manager):
     def get_queryset(self):
         return super(ArticleManager, self).get_queryset().filter(authors__name__icontains='sir')
 
+
 @python_2_unicode_compatible
 class Article(models.Model):
     authors = models.ManyToManyField(Author)
diff --git a/tests/get_or_create_regress/models.py b/tests/get_or_create_regress/models.py
index 637bbf62af..2ffc5c93ac 100644
--- a/tests/get_or_create_regress/models.py
+++ b/tests/get_or_create_regress/models.py
@@ -4,9 +4,11 @@ from django.db import models
 class Publisher(models.Model):
     name = models.CharField(max_length=100)
 
+
 class Author(models.Model):
     name = models.CharField(max_length=100)
 
+
 class Book(models.Model):
     name = models.CharField(max_length=100)
     authors = models.ManyToManyField(Author, related_name='books')
diff --git a/tests/handlers/views.py b/tests/handlers/views.py
index 1b75b27043..84cac97e62 100644
--- a/tests/handlers/views.py
+++ b/tests/handlers/views.py
@@ -4,18 +4,23 @@ from django.core.exceptions import SuspiciousOperation
 from django.db import connection, transaction
 from django.http import HttpResponse, StreamingHttpResponse
 
+
 def regular(request):
     return HttpResponse(b"regular content")
 
+
 def streaming(request):
     return StreamingHttpResponse([b"streaming", b" ", b"content"])
 
+
 def in_transaction(request):
     return HttpResponse(str(connection.in_atomic_block))
 
+
 @transaction.non_atomic_requests
 def not_in_transaction(request):
     return HttpResponse(str(connection.in_atomic_block))
 
+
 def suspicious(request):
     raise SuspiciousOperation('dubious')
diff --git a/tests/httpwrappers/tests.py b/tests/httpwrappers/tests.py
index 820aecf1f7..ccea20f9c5 100644
--- a/tests/httpwrappers/tests.py
+++ b/tests/httpwrappers/tests.py
@@ -239,6 +239,7 @@ class QueryDictTests(unittest.TestCase):
         self.assertEqual(copy.copy(q).encoding, 'iso-8859-15')
         self.assertEqual(copy.deepcopy(q).encoding, 'iso-8859-15')
 
+
 class HttpResponseTests(unittest.TestCase):
 
     def test_headers_type(self):
@@ -414,6 +415,7 @@ class HttpResponseTests(unittest.TestCase):
             self.assertRaises(SuspiciousOperation,
                               HttpResponsePermanentRedirect, url)
 
+
 class HttpResponseSubclassesTests(TestCase):
     def test_redirect(self):
         response = HttpResponseRedirect('/redirected/')
@@ -448,6 +450,7 @@ class HttpResponseSubclassesTests(TestCase):
             content_type='text/html')
         self.assertContains(response, 'Only the GET method is allowed', status_code=405)
 
+
 class StreamingHttpResponseTests(TestCase):
     def test_streaming_response(self):
         r = StreamingHttpResponse(iter(['hello', 'world']))
@@ -501,6 +504,7 @@ class StreamingHttpResponseTests(TestCase):
         with self.assertRaises(Exception):
             r.tell()
 
+
 class FileCloseTests(TestCase):
 
     def setUp(self):
@@ -566,6 +570,7 @@ class FileCloseTests(TestCase):
         self.assertTrue(file1.closed)
         self.assertTrue(file2.closed)
 
+
 class CookieTests(unittest.TestCase):
     def test_encode(self):
         """
diff --git a/tests/i18n/forms.py b/tests/i18n/forms.py
index 07b015d590..e06ed4b18d 100644
--- a/tests/i18n/forms.py
+++ b/tests/i18n/forms.py
@@ -12,9 +12,11 @@ class I18nForm(forms.Form):
     time_field = forms.TimeField(localize=True)
     integer_field = forms.IntegerField(localize=True)
 
+
 class SelectDateForm(forms.Form):
     date_field = forms.DateField(widget=SelectDateWidget)
 
+
 class CompanyForm(forms.ModelForm):
     cents_paid = forms.DecimalField(max_digits=4, decimal_places=2, localize=True)
     products_delivered = forms.IntegerField(localize=True)
diff --git a/tests/i18n/models.py b/tests/i18n/models.py
index 6e3591de24..3afc0841c6 100644
--- a/tests/i18n/models.py
+++ b/tests/i18n/models.py
@@ -7,6 +7,7 @@ from django.utils.translation import ugettext_lazy as _
 class TestModel(models.Model):
     text = models.CharField(max_length=10, default=_('Anything'))
 
+
 class Company(models.Model):
     name = models.CharField(max_length=50)
     date_added = models.DateTimeField(default=datetime(1799, 1, 31, 23, 59, 59, 0))
diff --git a/tests/i18n/test_extraction.py b/tests/i18n/test_extraction.py
index 18088e5e16..633184f7c5 100644
--- a/tests/i18n/test_extraction.py
+++ b/tests/i18n/test_extraction.py
@@ -21,6 +21,7 @@ from django.utils.translation import TranslatorCommentWarning
 LOCALE = 'de'
 has_xgettext = find_command('xgettext')
 
+
 @skipUnless(has_xgettext, 'xgettext is mandatory for extraction tests')
 class ExtractorTests(SimpleTestCase):
 
@@ -130,9 +131,10 @@ class BasicExtractorTests(ExtractorTests):
         self.assertRaises(SyntaxError, management.call_command, 'makemessages', locale=LOCALE, extensions=['tpl'], verbosity=0)
         with self.assertRaises(SyntaxError) as context_manager:
             management.call_command('makemessages', locale=LOCALE, extensions=['tpl'], verbosity=0)
-        six.assertRegex(self, str(context_manager.exception),
-                r'Translation blocks must not include other block tags: blocktrans \(file templates[/\\]template_with_error\.tpl, line 3\)'
-            )
+        six.assertRegex(
+            self, str(context_manager.exception),
+            r'Translation blocks must not include other block tags: blocktrans \(file templates[/\\]template_with_error\.tpl, line 3\)'
+        )
         # Check that the temporary file was cleaned up
         self.assertFalse(os.path.exists('./templates/template_with_error.tpl.py'))
 
@@ -210,13 +212,16 @@ class BasicExtractorTests(ExtractorTests):
             self.assertEqual(len(ws), 3)
             for w in ws:
                 self.assertTrue(issubclass(w.category, TranslatorCommentWarning))
-            six.assertRegex(self, str(ws[0].message),
+            six.assertRegex(
+                self, str(ws[0].message),
                 r"The translator-targeted comment 'Translators: ignored i18n comment #1' \(file templates[/\\]comments.thtml, line 4\) was ignored, because it wasn't the last item on the line\."
             )
-            six.assertRegex(self, str(ws[1].message),
+            six.assertRegex(
+                self, str(ws[1].message),
                 r"The translator-targeted comment 'Translators: ignored i18n comment #3' \(file templates[/\\]comments.thtml, line 6\) was ignored, because it wasn't the last item on the line\."
             )
-            six.assertRegex(self, str(ws[2].message),
+            six.assertRegex(
+                self, str(ws[2].message),
                 r"The translator-targeted comment 'Translators: ignored i18n comment #4' \(file templates[/\\]comments.thtml, line 8\) was ignored, because it wasn't the last item on the line\."
             )
         # Now test .po file contents
@@ -281,6 +286,7 @@ class JavascriptExtractorTests(ExtractorTests):
             self.assertMsgId("quz", po_contents)
             self.assertMsgId("foobar", po_contents)
 
+
 class IgnoredExtractorTests(ExtractorTests):
 
     def test_ignore_option(self):
diff --git a/tests/i18n/tests.py b/tests/i18n/tests.py
index b1f3de0ef9..ac9242241d 100644
--- a/tests/i18n/tests.py
+++ b/tests/i18n/tests.py
@@ -956,12 +956,14 @@ class ResolutionOrderI18NTests(TransRealMixin, TestCase):
         self.assertTrue(msgstr in result, ("The string '%s' isn't in the "
             "translation of '%s'; the actual result is '%s'." % (msgstr, msgid, result)))
 
+
 @override_settings(INSTALLED_APPS=['i18n.resolution'] + list(settings.INSTALLED_APPS))
 class AppResolutionOrderI18NTests(ResolutionOrderI18NTests):
 
     def test_app_translation(self):
         self.assertUgettext('Date/time', 'APP')
 
+
 @override_settings(LOCALE_PATHS=extended_locale_paths)
 class LocalePathsResolutionOrderI18NTests(ResolutionOrderI18NTests):
 
@@ -973,6 +975,7 @@ class LocalePathsResolutionOrderI18NTests(ResolutionOrderI18NTests):
         with self.settings(INSTALLED_APPS=extended_apps):
             self.assertUgettext('Time', 'LOCALE_PATHS')
 
+
 class DjangoFallbackResolutionOrderI18NTests(ResolutionOrderI18NTests):
 
     def test_django_fallback(self):
diff --git a/tests/inline_formsets/models.py b/tests/inline_formsets/models.py
index 40c85fe739..383122dbd7 100644
--- a/tests/inline_formsets/models.py
+++ b/tests/inline_formsets/models.py
@@ -6,15 +6,18 @@ from django.utils.encoding import python_2_unicode_compatible
 class School(models.Model):
     name = models.CharField(max_length=100)
 
+
 class Parent(models.Model):
     name = models.CharField(max_length=100)
 
+
 class Child(models.Model):
     mother = models.ForeignKey(Parent, related_name='mothers_children')
     father = models.ForeignKey(Parent, related_name='fathers_children')
     school = models.ForeignKey(School)
     name = models.CharField(max_length=100)
 
+
 @python_2_unicode_compatible
 class Poet(models.Model):
     name = models.CharField(max_length=100)
@@ -22,6 +25,7 @@ class Poet(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Poem(models.Model):
     poet = models.ForeignKey(Poet)
diff --git a/tests/inspectdb/models.py b/tests/inspectdb/models.py
index 83cd906a07..f7c8af73c6 100644
--- a/tests/inspectdb/models.py
+++ b/tests/inspectdb/models.py
@@ -9,22 +9,27 @@ class People(models.Model):
     name = models.CharField(max_length=255)
     parent = models.ForeignKey('self')
 
+
 class Message(models.Model):
     from_field = models.ForeignKey(People, db_column='from_id')
 
+
 class PeopleData(models.Model):
     people_pk = models.ForeignKey(People, primary_key=True)
     ssn = models.CharField(max_length=11)
 
+
 class PeopleMoreData(models.Model):
     people_unique = models.ForeignKey(People, unique=True)
     license = models.CharField(max_length=255)
 
+
 class DigitsInColumnName(models.Model):
     all_digits = models.CharField(max_length=11, db_column='123')
     leading_digit = models.CharField(max_length=11, db_column='4extra')
     leading_digits = models.CharField(max_length=11, db_column='45extra')
 
+
 class SpecialColumnName(models.Model):
     field = models.IntegerField(db_column='field')
     # Underscores
@@ -35,6 +40,7 @@ class SpecialColumnName(models.Model):
     prc_x = models.IntegerField(db_column='prc(%) x')
     non_ascii = models.IntegerField(db_column='tamaƱo')
 
+
 class ColumnTypes(models.Model):
     id = models.AutoField(primary_key=True)
     big_int_field = models.BigIntegerField()
diff --git a/tests/inspectdb/tests.py b/tests/inspectdb/tests.py
index 82802843d9..abd43f10e3 100644
--- a/tests/inspectdb/tests.py
+++ b/tests/inspectdb/tests.py
@@ -14,6 +14,7 @@ if connection.vendor == 'oracle':
 else:
     expectedFailureOnOracle = lambda f: f
 
+
 class InspectDBTestCase(TestCase):
 
     def test_stealth_table_name_filter_option(self):
@@ -166,7 +167,7 @@ class InspectDBTestCase(TestCase):
         self.assertIn("        managed = False", output, msg='inspectdb should generate unmanaged models.')
 
     @skipUnless(connection.vendor == 'sqlite',
-                         "Only patched sqlite's DatabaseIntrospection.data_types_reverse for this test")
+        "Only patched sqlite's DatabaseIntrospection.data_types_reverse for this test")
     def test_custom_fields(self):
         """
         Introspection of columns with a custom field (#21090)
diff --git a/tests/known_related_objects/models.py b/tests/known_related_objects/models.py
index cfee4650d9..2b5ab6cfe5 100644
--- a/tests/known_related_objects/models.py
+++ b/tests/known_related_objects/models.py
@@ -6,17 +6,21 @@ Test that queries are not redone when going back through known relations.
 
 from django.db import models
 
+
 class Tournament(models.Model):
     name = models.CharField(max_length=30)
 
+
 class Organiser(models.Model):
     name = models.CharField(max_length=30)
 
+
 class Pool(models.Model):
     name = models.CharField(max_length=30)
     tournament = models.ForeignKey(Tournament)
     organiser = models.ForeignKey(Organiser)
 
+
 class PoolStyle(models.Model):
     name = models.CharField(max_length=30)
     pool = models.OneToOneField(Pool)
diff --git a/tests/known_related_objects/tests.py b/tests/known_related_objects/tests.py
index 6fd507cbdc..03307f49ac 100644
--- a/tests/known_related_objects/tests.py
+++ b/tests/known_related_objects/tests.py
@@ -4,6 +4,7 @@ from django.test import TestCase
 
 from .models import Tournament, Organiser, Pool, PoolStyle
 
+
 class ExistingRelatedInstancesTests(TestCase):
     fixtures = ['tournament.json']
 
diff --git a/tests/logging_tests/tests.py b/tests/logging_tests/tests.py
index bd1983f74e..1b3a20cc24 100644
--- a/tests/logging_tests/tests.py
+++ b/tests/logging_tests/tests.py
@@ -62,6 +62,7 @@ class LoggingFiltersTest(TestCase):
         with self.settings(DEBUG=False):
             self.assertEqual(filter_.filter("record is not used"), False)
 
+
 class DefaultLoggingTest(TestCase):
     def setUp(self):
         self.logger = logging.getLogger('django')
@@ -83,6 +84,7 @@ class DefaultLoggingTest(TestCase):
             self.logger.error("Hey, this is an error.")
             self.assertEqual(output.getvalue(), 'Hey, this is an error.\n')
 
+
 class WarningLoggerTests(TestCase):
     """
     Tests that warnings output for DeprecationWarnings is enabled
diff --git a/tests/lookup/models.py b/tests/lookup/models.py
index a130d35e8e..df8b26c4e9 100644
--- a/tests/lookup/models.py
+++ b/tests/lookup/models.py
@@ -17,6 +17,7 @@ class Author(models.Model):
     class Meta:
         ordering = ('name', )
 
+
 @python_2_unicode_compatible
 class Article(models.Model):
     headline = models.CharField(max_length=100)
@@ -29,6 +30,7 @@ class Article(models.Model):
     def __str__(self):
         return self.headline
 
+
 class Tag(models.Model):
     articles = models.ManyToManyField(Article)
     name = models.CharField(max_length=100)
@@ -36,6 +38,7 @@ class Tag(models.Model):
     class Meta:
         ordering = ('name', )
 
+
 @python_2_unicode_compatible
 class Season(models.Model):
     year = models.PositiveSmallIntegerField()
@@ -44,6 +47,7 @@ class Season(models.Model):
     def __str__(self):
         return six.text_type(self.year)
 
+
 @python_2_unicode_compatible
 class Game(models.Model):
     season = models.ForeignKey(Season, related_name='games')
@@ -53,6 +57,7 @@ class Game(models.Model):
     def __str__(self):
         return "%s at %s" % (self.away, self.home)
 
+
 @python_2_unicode_compatible
 class Player(models.Model):
     name = models.CharField(max_length=100)
diff --git a/tests/m2m_and_m2o/models.py b/tests/m2m_and_m2o/models.py
index c303743f04..482ae9a1fa 100644
--- a/tests/m2m_and_m2o/models.py
+++ b/tests/m2m_and_m2o/models.py
@@ -13,6 +13,7 @@ from django.utils.encoding import python_2_unicode_compatible
 class User(models.Model):
     username = models.CharField(max_length=20)
 
+
 @python_2_unicode_compatible
 class Issue(models.Model):
     num = models.IntegerField()
@@ -25,5 +26,6 @@ class Issue(models.Model):
     class Meta:
         ordering = ('num',)
 
+
 class UnicodeReferenceModel(models.Model):
     others = models.ManyToManyField("UnicodeReferenceModel")
diff --git a/tests/m2m_and_m2o/tests.py b/tests/m2m_and_m2o/tests.py
index 35443e32e4..e950a839d2 100644
--- a/tests/m2m_and_m2o/tests.py
+++ b/tests/m2m_and_m2o/tests.py
@@ -50,7 +50,7 @@ class RelatedObjectTests(TestCase):
         # These queries combine results from the m2m and the m2o relationships.
         # They're three ways of saying the same thing.
         self.assertQuerysetEqual(
-            Issue.objects.filter(Q(cc__id__exact = r.id) | Q(client=r.id)), [
+            Issue.objects.filter(Q(cc__id__exact=r.id) | Q(client=r.id)), [
                 1,
                 2,
                 3,
@@ -74,6 +74,7 @@ class RelatedObjectTests(TestCase):
             lambda i: i.num
         )
 
+
 class RelatedObjectUnicodeTests(TestCase):
     def test_m2m_with_unicode_reference(self):
         """
diff --git a/tests/m2m_intermediary/models.py b/tests/m2m_intermediary/models.py
index 770681f91c..9b194e321b 100644
--- a/tests/m2m_intermediary/models.py
+++ b/tests/m2m_intermediary/models.py
@@ -23,6 +23,7 @@ class Reporter(models.Model):
     def __str__(self):
         return "%s %s" % (self.first_name, self.last_name)
 
+
 @python_2_unicode_compatible
 class Article(models.Model):
     headline = models.CharField(max_length=100)
@@ -31,6 +32,7 @@ class Article(models.Model):
     def __str__(self):
         return self.headline
 
+
 @python_2_unicode_compatible
 class Writer(models.Model):
     reporter = models.ForeignKey(Reporter)
diff --git a/tests/m2m_regress/models.py b/tests/m2m_regress/models.py
index abd012b3d0..48fdad9304 100644
--- a/tests/m2m_regress/models.py
+++ b/tests/m2m_regress/models.py
@@ -2,6 +2,7 @@ from django.contrib.auth import models as auth
 from django.db import models
 from django.utils.encoding import python_2_unicode_compatible
 
+
 # No related name is needed here, since symmetrical relations are not
 # explicitly reversible.
 @python_2_unicode_compatible
@@ -13,6 +14,7 @@ class SelfRefer(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Tag(models.Model):
     name = models.CharField(max_length=10)
@@ -20,6 +22,7 @@ class Tag(models.Model):
     def __str__(self):
         return self.name
 
+
 # Regression for #11956 -- a many to many to the base class
 @python_2_unicode_compatible
 class TagCollection(Tag):
@@ -28,6 +31,7 @@ class TagCollection(Tag):
     def __str__(self):
         return self.name
 
+
 # A related_name is required on one of the ManyToManyField entries here because
 # they are both addressable as reverse relations from Tag.
 @python_2_unicode_compatible
@@ -39,21 +43,26 @@ class Entry(models.Model):
     def __str__(self):
         return self.name
 
+
 # Two models both inheriting from a base model with a self-referential m2m field
 class SelfReferChild(SelfRefer):
     pass
 
+
 class SelfReferChildSibling(SelfRefer):
     pass
 
+
 # Many-to-Many relation between models, where one of the PK's isn't an Autofield
 class Line(models.Model):
     name = models.CharField(max_length=100)
 
+
 class Worksheet(models.Model):
     id = models.CharField(primary_key=True, max_length=100)
     lines = models.ManyToManyField(Line, blank=True, null=True)
 
+
 # Regression for #11226 -- A model with the same name that another one to
 # which it has a m2m relation. This shouldn't cause a name clash between
 # the automatically created m2m intermediary table FK field names when
diff --git a/tests/m2m_signals/models.py b/tests/m2m_signals/models.py
index e997d87f21..e4110ccf34 100644
--- a/tests/m2m_signals/models.py
+++ b/tests/m2m_signals/models.py
@@ -12,6 +12,7 @@ class Part(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Car(models.Model):
     name = models.CharField(max_length=20)
@@ -24,9 +25,11 @@ class Car(models.Model):
     def __str__(self):
         return self.name
 
+
 class SportsCar(Car):
     price = models.IntegerField()
 
+
 @python_2_unicode_compatible
 class Person(models.Model):
     name = models.CharField(max_length=20)
diff --git a/tests/m2m_through/models.py b/tests/m2m_through/models.py
index a896f6d9ff..70d6baeca8 100644
--- a/tests/m2m_through/models.py
+++ b/tests/m2m_through/models.py
@@ -15,6 +15,7 @@ class Person(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Group(models.Model):
     name = models.CharField(max_length=128)
@@ -28,6 +29,7 @@ class Group(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Membership(models.Model):
     person = models.ForeignKey(Person)
@@ -41,6 +43,7 @@ class Membership(models.Model):
     def __str__(self):
         return "%s is a member of %s" % (self.person.name, self.group.name)
 
+
 @python_2_unicode_compatible
 class CustomMembership(models.Model):
     person = models.ForeignKey(Person, db_column="custom_person_column", related_name="custom_person_related_name")
@@ -54,11 +57,13 @@ class CustomMembership(models.Model):
     class Meta:
         db_table = "test_table"
 
+
 class TestNoDefaultsOrNulls(models.Model):
     person = models.ForeignKey(Person)
     group = models.ForeignKey(Group)
     nodefaultnonull = models.CharField(max_length=5)
 
+
 @python_2_unicode_compatible
 class PersonSelfRefM2M(models.Model):
     name = models.CharField(max_length=5)
@@ -67,6 +72,7 @@ class PersonSelfRefM2M(models.Model):
     def __str__(self):
         return self.name
 
+
 class Friendship(models.Model):
     first = models.ForeignKey(PersonSelfRefM2M, related_name="rel_from_set")
     second = models.ForeignKey(PersonSelfRefM2M, related_name="rel_to_set")
diff --git a/tests/m2m_through_regress/models.py b/tests/m2m_through_regress/models.py
index 91e1aa8cc1..c49e5b02eb 100644
--- a/tests/m2m_through_regress/models.py
+++ b/tests/m2m_through_regress/models.py
@@ -15,6 +15,7 @@ class Membership(models.Model):
     def __str__(self):
         return "%s is a member of %s" % (self.person.name, self.group.name)
 
+
 # using custom id column to test ticket #11107
 @python_2_unicode_compatible
 class UserMembership(models.Model):
@@ -26,6 +27,7 @@ class UserMembership(models.Model):
     def __str__(self):
         return "%s is a user and member of %s" % (self.user.username, self.group.name)
 
+
 @python_2_unicode_compatible
 class Person(models.Model):
     name = models.CharField(max_length=128)
@@ -33,6 +35,7 @@ class Person(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Group(models.Model):
     name = models.CharField(max_length=128)
@@ -43,17 +46,21 @@ class Group(models.Model):
     def __str__(self):
         return self.name
 
+
 # A set of models that use an non-abstract inherited model as the 'through' model.
 class A(models.Model):
     a_text = models.CharField(max_length=20)
 
+
 class ThroughBase(models.Model):
     a = models.ForeignKey(A)
     b = models.ForeignKey('B')
 
+
 class Through(ThroughBase):
     extra = models.CharField(max_length=20)
 
+
 class B(models.Model):
     b_text = models.CharField(max_length=20)
     a_list = models.ManyToManyField(A, through=Through)
@@ -68,6 +75,7 @@ class Car(models.Model):
     def __str__(self):
         return "%s" % self.make
 
+
 @python_2_unicode_compatible
 class Driver(models.Model):
     name = models.CharField(max_length=20, unique=True, null=True)
@@ -78,6 +86,7 @@ class Driver(models.Model):
     class Meta:
         ordering = ('name',)
 
+
 @python_2_unicode_compatible
 class CarDriver(models.Model):
     car = models.ForeignKey('Car', to_field='make')
diff --git a/tests/m2o_recursive/models.py b/tests/m2o_recursive/models.py
index 2775d713dd..b41e0cb0a3 100644
--- a/tests/m2o_recursive/models.py
+++ b/tests/m2o_recursive/models.py
@@ -22,6 +22,7 @@ class Category(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Person(models.Model):
     full_name = models.CharField(max_length=20)
diff --git a/tests/m2o_recursive/tests.py b/tests/m2o_recursive/tests.py
index f5e8938706..b21aef95d3 100644
--- a/tests/m2o_recursive/tests.py
+++ b/tests/m2o_recursive/tests.py
@@ -21,6 +21,7 @@ class ManyToOneRecursiveTests(TestCase):
         self.assertQuerysetEqual(self.c.child_set.all(), [])
         self.assertEqual(self.c.parent.id, self.r.id)
 
+
 class MultipleManyToOneRecursiveTests(TestCase):
 
     def setUp(self):
diff --git a/tests/many_to_many/models.py b/tests/many_to_many/models.py
index 31793b3974..eaf98ce565 100644
--- a/tests/many_to_many/models.py
+++ b/tests/many_to_many/models.py
@@ -22,6 +22,7 @@ class Publication(models.Model):
     class Meta:
         ordering = ('title',)
 
+
 @python_2_unicode_compatible
 class Article(models.Model):
     headline = models.CharField(max_length=100)
diff --git a/tests/many_to_one/models.py b/tests/many_to_one/models.py
index 4e2ed67eea..8c50ffe53b 100644
--- a/tests/many_to_one/models.py
+++ b/tests/many_to_one/models.py
@@ -18,6 +18,7 @@ class Reporter(models.Model):
     def __str__(self):
         return "%s %s" % (self.first_name, self.last_name)
 
+
 @python_2_unicode_compatible
 class Article(models.Model):
     headline = models.CharField(max_length=100)
diff --git a/tests/many_to_one_null/models.py b/tests/many_to_one_null/models.py
index e00ca85928..16ee56cec6 100644
--- a/tests/many_to_one_null/models.py
+++ b/tests/many_to_one_null/models.py
@@ -16,6 +16,7 @@ class Reporter(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Article(models.Model):
     headline = models.CharField(max_length=100)
diff --git a/tests/many_to_one_regress/models.py b/tests/many_to_one_regress/models.py
index 0ac0871793..c94bc5e05c 100644
--- a/tests/many_to_one_regress/models.py
+++ b/tests/many_to_one_regress/models.py
@@ -10,21 +10,26 @@ from django.utils.encoding import python_2_unicode_compatible
 # created (the field names being lower-cased versions of their opposite
 # classes is important here).
 
+
 class First(models.Model):
     second = models.IntegerField()
 
+
 class Second(models.Model):
-    first = models.ForeignKey(First, related_name = 'the_first')
+    first = models.ForeignKey(First, related_name='the_first')
+
 
 # Protect against repetition of #1839, #2415 and #2536.
 class Third(models.Model):
     name = models.CharField(max_length=20)
     third = models.ForeignKey('self', null=True, related_name='child_set')
 
+
 class Parent(models.Model):
     name = models.CharField(max_length=20)
     bestchild = models.ForeignKey('Child', null=True, related_name='favored_by')
 
+
 class Child(models.Model):
     name = models.CharField(max_length=20)
     parent = models.ForeignKey(Parent)
@@ -38,9 +43,11 @@ class Category(models.Model):
     def __str__(self):
         return self.name
 
+
 class Record(models.Model):
     category = models.ForeignKey(Category)
 
+
 @python_2_unicode_compatible
 class Relation(models.Model):
     left = models.ForeignKey(Record, related_name='left_set')
@@ -49,8 +56,10 @@ class Relation(models.Model):
     def __str__(self):
         return "%s - %s" % (self.left.category.name, self.right.category.name)
 
+
 class Car(models.Model):
     make = models.CharField(max_length=100, null=True, unique=True)
 
+
 class Driver(models.Model):
     car = models.ForeignKey(Car, to_field='make', null=True, related_name='drivers')
diff --git a/tests/max_lengths/models.py b/tests/max_lengths/models.py
index d66e833e8c..ec4cc8e114 100644
--- a/tests/max_lengths/models.py
+++ b/tests/max_lengths/models.py
@@ -7,6 +7,7 @@ class PersonWithDefaultMaxLengths(models.Model):
     homepage = models.URLField()
     avatar = models.FilePathField()
 
+
 class PersonWithCustomMaxLengths(models.Model):
     email = models.EmailField(max_length=250)
     vcard = models.FileField(upload_to='/tmp', max_length=250)
diff --git a/tests/max_lengths/tests.py b/tests/max_lengths/tests.py
index 5dd33fc80f..25101cd535 100644
--- a/tests/max_lengths/tests.py
+++ b/tests/max_lengths/tests.py
@@ -22,6 +22,7 @@ class MaxLengthArgumentsTests(unittest.TestCase):
         self.verify_max_length(PersonWithCustomMaxLengths, 'homepage', 250)
         self.verify_max_length(PersonWithCustomMaxLengths, 'avatar', 250)
 
+
 class MaxLengthORMTests(unittest.TestCase):
 
     def test_custom_max_lengths(self):
diff --git a/tests/middleware/tests.py b/tests/middleware/tests.py
index b474f6b0e3..0124e33c98 100644
--- a/tests/middleware/tests.py
+++ b/tests/middleware/tests.py
@@ -120,7 +120,7 @@ class CommonMiddlewareTest(TestCase):
         r = CommonMiddleware().process_request(request)
         self.assertEqual(r.status_code, 301)
         self.assertEqual(r.url,
-                          'http://www.testserver/middleware/slash/')
+            'http://www.testserver/middleware/slash/')
 
     @override_settings(APPEND_SLASH=True, PREPEND_WWW=True)
     def test_prepend_www_append_slash_slashless(self):
@@ -128,7 +128,7 @@ class CommonMiddlewareTest(TestCase):
         r = CommonMiddleware().process_request(request)
         self.assertEqual(r.status_code, 301)
         self.assertEqual(r.url,
-                          'http://www.testserver/middleware/slash/')
+            'http://www.testserver/middleware/slash/')
 
     # The following tests examine expected behavior given a custom urlconf that
     # overrides the default one through the request object.
@@ -228,7 +228,7 @@ class CommonMiddlewareTest(TestCase):
         r = CommonMiddleware().process_request(request)
         self.assertEqual(r.status_code, 301)
         self.assertEqual(r.url,
-                          'http://www.testserver/middleware/customurlconf/slash/')
+            'http://www.testserver/middleware/customurlconf/slash/')
 
     @override_settings(APPEND_SLASH=True, PREPEND_WWW=True)
     def test_prepend_www_append_slash_slashless_custom_urlconf(self):
@@ -237,7 +237,7 @@ class CommonMiddlewareTest(TestCase):
         r = CommonMiddleware().process_request(request)
         self.assertEqual(r.status_code, 301)
         self.assertEqual(r.url,
-                          'http://www.testserver/middleware/customurlconf/slash/')
+            'http://www.testserver/middleware/customurlconf/slash/')
 
     # Legacy tests for the 404 error reporting via email (to be removed in 1.8)
 
@@ -336,7 +336,7 @@ class BrokenLinkEmailsMiddlewareTest(TestCase):
                     return True
                 user_agent = request.META['HTTP_USER_AGENT']
                 return any(pattern.search(user_agent) for pattern in
-                               self.ignored_user_agent_patterns)
+                    self.ignored_user_agent_patterns)
 
         self.req.META['HTTP_REFERER'] = '/another/url/'
         self.req.META['HTTP_USER_AGENT'] = 'Spider machine 3.4'
@@ -346,6 +346,7 @@ class BrokenLinkEmailsMiddlewareTest(TestCase):
         SubclassedMiddleware().process_response(self.req, self.resp)
         self.assertEqual(len(mail.outbox), 1)
 
+
 class ConditionalGetMiddlewareTest(TestCase):
     urls = 'middleware.cond_get_urls'
 
@@ -704,6 +705,7 @@ class ETagGZipMiddlewareTest(TestCase):
 
         self.assertNotEqual(gzip_etag, nogzip_etag)
 
+
 class TransactionMiddlewareTest(IgnoreDeprecationWarningsMixin, TransactionTestCase):
     """
     Test the transaction middleware.
diff --git a/tests/middleware_exceptions/tests.py b/tests/middleware_exceptions/tests.py
index 02e53a00e8..83c6118c9d 100644
--- a/tests/middleware_exceptions/tests.py
+++ b/tests/middleware_exceptions/tests.py
@@ -778,6 +778,8 @@ class BadMiddlewareTests(BaseMiddlewareExceptionTest):
 
 
 _missing = object()
+
+
 class RootUrlconfTests(TestCase):
     urls = 'middleware_exceptions.urls'
 
diff --git a/tests/middleware_exceptions/views.py b/tests/middleware_exceptions/views.py
index ddf28c46a3..59abe26bff 100644
--- a/tests/middleware_exceptions/views.py
+++ b/tests/middleware_exceptions/views.py
@@ -7,20 +7,26 @@ from django.template.response import TemplateResponse
 def normal_view(request):
     return http.HttpResponse('OK')
 
+
 def template_response(request):
     return TemplateResponse(request, Template('OK'))
 
+
 def template_response_error(request):
     return TemplateResponse(request, Template('{%'))
 
+
 def not_found(request):
     raise http.Http404()
 
+
 def server_error(request):
     raise Exception('Error in view')
 
+
 def null_view(request):
     return None
 
+
 def permission_denied(request):
     raise PermissionDenied()
diff --git a/tests/model_fields/tests.py b/tests/model_fields/tests.py
index f3ef83a39c..d78f3d7c2d 100644
--- a/tests/model_fields/tests.py
+++ b/tests/model_fields/tests.py
@@ -133,6 +133,7 @@ class DecimalFieldTests(test.TestCase):
         # This should not crash. That counts as a win for our purposes.
         Foo.objects.filter(d__gte=100000000000)
 
+
 class ForeignKeyTests(test.TestCase):
     def test_callable_default(self):
         """Test the use of a lazy callable for ForeignKey.default"""
@@ -140,6 +141,7 @@ class ForeignKeyTests(test.TestCase):
         b = Bar.objects.create(b="bcd")
         self.assertEqual(b.a, a)
 
+
 class DateTimeFieldTests(unittest.TestCase):
     def test_datetimefield_to_python_usecs(self):
         """DateTimeField.to_python should support usecs"""
@@ -157,6 +159,7 @@ class DateTimeFieldTests(unittest.TestCase):
         self.assertEqual(f.to_python('01:02:03.999999'),
                          datetime.time(1, 2, 3, 999999))
 
+
 class BooleanFieldTests(unittest.TestCase):
     def _test_get_db_prep_lookup(self, f):
         from django.db import connection
@@ -294,6 +297,7 @@ class BooleanFieldTests(unittest.TestCase):
         self.assertIsNone(nb.nbfield)
         nb.save()           # no error
 
+
 class ChoicesTests(test.TestCase):
     def test_choices_and_field_display(self):
         """
@@ -306,6 +310,7 @@ class ChoicesTests(test.TestCase):
         self.assertEqual(Whiz(c=None).get_c_display(), None)    # Blank value
         self.assertEqual(Whiz(c='').get_c_display(), '')        # Empty value
 
+
 class SlugFieldTests(test.TestCase):
     def test_slugfield_max_length(self):
         """
@@ -409,6 +414,7 @@ class BigIntegerFieldTests(test.TestCase):
         b = BigInt.objects.get(value='10')
         self.assertEqual(b.value, 10)
 
+
 class TypeCoercionTests(test.TestCase):
     """
     Test that database lookups can accept the wrong types and convert
@@ -422,6 +428,7 @@ class TypeCoercionTests(test.TestCase):
     def test_lookup_integer_in_textfield(self):
         self.assertEqual(Post.objects.filter(body=24).count(), 0)
 
+
 class FileFieldTests(unittest.TestCase):
     def test_clearable(self):
         """
@@ -496,6 +503,7 @@ class BinaryFieldTests(test.TestCase):
         dm = DataModel(short_data=self.binary_data * 4)
         self.assertRaises(ValidationError, dm.full_clean)
 
+
 class GenericIPAddressFieldTests(test.TestCase):
     def test_genericipaddressfield_formfield_protocol(self):
         """
diff --git a/tests/model_forms/models.py b/tests/model_forms/models.py
index 34644a4bb9..72bf1ff26a 100644
--- a/tests/model_forms/models.py
+++ b/tests/model_forms/models.py
@@ -34,6 +34,7 @@ ARTICLE_STATUS_CHAR = (
     ('l', 'Live'),
 )
 
+
 @python_2_unicode_compatible
 class Category(models.Model):
     name = models.CharField(max_length=20)
@@ -46,6 +47,7 @@ class Category(models.Model):
     def __repr__(self):
         return self.__str__()
 
+
 @python_2_unicode_compatible
 class Writer(models.Model):
     name = models.CharField(max_length=50, help_text='Use both first and last names.')
@@ -56,6 +58,7 @@ class Writer(models.Model):
     def __str__(self):
         return self.name
 
+
 @python_2_unicode_compatible
 class Article(models.Model):
     headline = models.CharField(max_length=50)
@@ -76,15 +79,19 @@ class Article(models.Model):
     def __str__(self):
         return self.headline
 
+
 class ImprovedArticle(models.Model):
     article = models.OneToOneField(Article)
 
+
 class ImprovedArticleWithParentLink(models.Model):
     article = models.OneToOneField(Article, parent_link=True)
 
+
 class BetterWriter(Writer):
     score = models.IntegerField()
 
+
 @python_2_unicode_compatible
 class WriterProfile(models.Model):
     writer = models.OneToOneField(Writer, primary_key=True)
@@ -93,6 +100,7 @@ class WriterProfile(models.Model):
     def __str__(self):
         return "%s is %s" % (self.writer, self.age)
 
+
 @python_2_unicode_compatible
 class TextFile(models.Model):
     description = models.CharField(max_length=20)
@@ -144,6 +152,7 @@ try:
 except ImproperlyConfigured:
     test_images = False
 
+
 @python_2_unicode_compatible
 class CommaSeparatedInteger(models.Model):
     field = models.CommaSeparatedIntegerField(max_length=20)
@@ -151,6 +160,7 @@ class CommaSeparatedInteger(models.Model):
     def __str__(self):
         return self.field
 
+
 @python_2_unicode_compatible
 class Product(models.Model):
     slug = models.SlugField(unique=True)
@@ -158,6 +168,7 @@ class Product(models.Model):
     def __str__(self):
         return self.slug
 
+
 @python_2_unicode_compatible
 class Price(models.Model):
     price = models.DecimalField(max_digits=10, decimal_places=2)
@@ -169,9 +180,11 @@ class Price(models.Model):
     class Meta:
         unique_together = (('price', 'quantity'),)
 
+
 class ArticleStatus(models.Model):
     status = models.CharField(max_length=2, choices=ARTICLE_STATUS_CHAR, blank=True, null=True)
 
+
 @python_2_unicode_compatible
 class Inventory(models.Model):
     barcode = models.PositiveIntegerField(unique=True)
@@ -187,6 +200,7 @@ class Inventory(models.Model):
     def __repr__(self):
         return self.__str__()
 
+
 class Book(models.Model):
     title = models.CharField(max_length=40)
     author = models.ForeignKey(Writer, blank=True, null=True)
@@ -195,6 +209,7 @@ class Book(models.Model):
     class Meta:
         unique_together = ('title', 'author')
 
+
 class BookXtra(models.Model):
     isbn = models.CharField(max_length=16, unique=True)
     suffix1 = models.IntegerField(blank=True, default=0)
@@ -204,9 +219,11 @@ class BookXtra(models.Model):
         unique_together = (('suffix1', 'suffix2'))
         abstract = True
 
+
 class DerivedBook(Book, BookXtra):
     pass
 
+
 @python_2_unicode_compatible
 class ExplicitPK(models.Model):
     key = models.CharField(max_length=20, primary_key=True)
@@ -218,6 +235,7 @@ class ExplicitPK(models.Model):
     def __str__(self):
         return self.key
 
+
 @python_2_unicode_compatible
 class Post(models.Model):
     title = models.CharField(max_length=50, unique_for_date='posted', blank=True)
@@ -228,6 +246,7 @@ class Post(models.Model):
     def __str__(self):
         return self.title
 
+
 @python_2_unicode_compatible
 class DateTimePost(models.Model):
     title = models.CharField(max_length=50, unique_for_date='posted', blank=True)
@@ -238,9 +257,11 @@ class DateTimePost(models.Model):
     def __str__(self):
         return self.title
 
+
 class DerivedPost(Post):
     pass
 
+
 @python_2_unicode_compatible
 class BigInt(models.Model):
     biggie = models.BigIntegerField()
@@ -248,6 +269,7 @@ class BigInt(models.Model):
     def __str__(self):
         return six.text_type(self.biggie)
 
+
 class MarkupField(models.CharField):
     def __init__(self, *args, **kwargs):
         kwargs["max_length"] = 20
@@ -260,16 +282,19 @@ class MarkupField(models.CharField):
         # regressed at r10062
         return None
 
+
 class CustomFieldForExclusionModel(models.Model):
     name = models.CharField(max_length=10)
     markup = MarkupField()
 
+
 class FlexibleDatePost(models.Model):
     title = models.CharField(max_length=50, unique_for_date='posted', blank=True)
     slug = models.CharField(max_length=50, unique_for_year='posted', blank=True)
     subtitle = models.CharField(max_length=50, unique_for_month='posted', blank=True)
     posted = models.DateField(blank=True, null=True)
 
+
 @python_2_unicode_compatible
 class Colour(models.Model):
     name = models.CharField(max_length=50)
@@ -281,14 +306,17 @@ class Colour(models.Model):
     def __str__(self):
         return self.name
 
+
 class ColourfulItem(models.Model):
     name = models.CharField(max_length=50)
     colours = models.ManyToManyField(Colour)
 
+
 class ArticleStatusNote(models.Model):
     name = models.CharField(max_length=20)
     status = models.ManyToManyField(ArticleStatus)
 
+
 class CustomErrorMessage(models.Model):
     name1 = models.CharField(max_length=50,
         validators=[validators.validate_slug],
diff --git a/tests/model_inheritance_same_model_name/models.py b/tests/model_inheritance_same_model_name/models.py
index 8b02b08668..a8c051facf 100644
--- a/tests/model_inheritance_same_model_name/models.py
+++ b/tests/model_inheritance_same_model_name/models.py
@@ -11,6 +11,7 @@ from django.db import models
 from model_inheritance.models import NamedURL
 from django.utils.encoding import python_2_unicode_compatible
 
+
 #
 # Abstract base classes with related models
 #
diff --git a/tests/multiple_database/tests.py b/tests/multiple_database/tests.py
index 8596346c7e..222d236bb0 100644
--- a/tests/multiple_database/tests.py
+++ b/tests/multiple_database/tests.py
@@ -215,23 +215,23 @@ class QueryTestCase(TestCase):
         # Remove the second author
         dive.authors.remove(john)
         self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
-                          ['Dive into Python'])
+            ['Dive into Python'])
         self.assertEqual(list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)),
-                          [])
+            [])
 
         # Clear all authors
         dive.authors.clear()
         self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
-                          [])
+            [])
         self.assertEqual(list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)),
-                          [])
+            [])
 
         # Create an author through the m2m interface
         dive.authors.create(name='Jane Brown')
         self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
-                          [])
+            [])
         self.assertEqual(list(Book.objects.using('other').filter(authors__name='Jane Brown').values_list('title', flat=True)),
-                          ['Dive into Python'])
+            ['Dive into Python'])
 
     def test_m2m_reverse_operations(self):
         "M2M reverse manipulations are all constrained to a single DB"
@@ -251,42 +251,42 @@ class QueryTestCase(TestCase):
         # Add a books to the m2m
         mark.book_set.add(grease)
         self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
-                          ['Mark Pilgrim'])
+            ['Mark Pilgrim'])
         self.assertEqual(list(Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)),
-                          ['Mark Pilgrim'])
+            ['Mark Pilgrim'])
 
         # Remove a book from the m2m
         mark.book_set.remove(grease)
         self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
-                          ['Mark Pilgrim'])
+            ['Mark Pilgrim'])
         self.assertEqual(list(Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)),
-                          [])
+            [])
 
         # Clear the books associated with mark
         mark.book_set.clear()
         self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
-                          [])
+            [])
         self.assertEqual(list(Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)),
-                          [])
+            [])
 
         # Create a book through the m2m interface
         mark.book_set.create(title="Dive into HTML5", published=datetime.date(2020, 1, 1))
         self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
-                          [])
+            [])
         self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into HTML5').values_list('name', flat=True)),
-                          ['Mark Pilgrim'])
+            ['Mark Pilgrim'])
 
     def test_m2m_cross_database_protection(self):
         "Operations that involve sharing M2M objects across databases raise an error"
         # Create a book and author on the default database
         pro = Book.objects.create(title="Pro Django",
-                                  published=datetime.date(2008, 12, 16))
+            published=datetime.date(2008, 12, 16))
 
         marty = Person.objects.create(name="Marty Alchin")
 
         # Create a book and author on the other database
         dive = Book.objects.using('other').create(title="Dive into Python",
-                                                  published=datetime.date(2009, 5, 4))
+            published=datetime.date(2009, 5, 4))
 
         mark = Person.objects.using('other').create(name="Mark Pilgrim")
         # Set a foreign key set with an object from a different database
@@ -413,14 +413,14 @@ class QueryTestCase(TestCase):
 
         # Check that queries work across foreign key joins
         self.assertEqual(list(Person.objects.using('default').filter(edited__title='Pro Django').values_list('name', flat=True)),
-                          ['George Vilches'])
+            ['George Vilches'])
         self.assertEqual(list(Person.objects.using('other').filter(edited__title='Pro Django').values_list('name', flat=True)),
-                          [])
+            [])
 
         self.assertEqual(list(Person.objects.using('default').filter(edited__title='Dive into Python').values_list('name', flat=True)),
-                          [])
+            [])
         self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)),
-                          ['Chris Mills'])
+            ['Chris Mills'])
 
         # Reget the objects to clear caches
         chris = Person.objects.using('other').get(name="Chris Mills")
@@ -428,12 +428,12 @@ class QueryTestCase(TestCase):
 
         # Retrive related object by descriptor. Related objects should be database-baound
         self.assertEqual(list(chris.edited.values_list('title', flat=True)),
-                          ['Dive into Python'])
+            ['Dive into Python'])
 
     def test_foreign_key_reverse_operations(self):
         "FK reverse manipulations are all constrained to a single DB"
         dive = Book.objects.using('other').create(title="Dive into Python",
-                                                       published=datetime.date(2009, 5, 4))
+            published=datetime.date(2009, 5, 4))
 
         chris = Person.objects.using('other').create(name="Chris Mills")
 
@@ -444,48 +444,48 @@ class QueryTestCase(TestCase):
         # Add a second book edited by chris
         html5 = Book.objects.using('other').create(title="Dive into HTML5", published=datetime.date(2010, 3, 15))
         self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
-                          [])
+            [])
 
         chris.edited.add(html5)
         self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
-                          ['Chris Mills'])
+            ['Chris Mills'])
         self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)),
-                          ['Chris Mills'])
+            ['Chris Mills'])
 
         # Remove the second editor
         chris.edited.remove(html5)
         self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
-                          [])
+            [])
         self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)),
-                          ['Chris Mills'])
+            ['Chris Mills'])
 
         # Clear all edited books
         chris.edited.clear()
         self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
-                          [])
+            [])
         self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)),
-                          [])
+            [])
 
         # Create an author through the m2m interface
         chris.edited.create(title='Dive into Water', published=datetime.date(2010, 3, 15))
         self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
-                          [])
+            [])
         self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Water').values_list('name', flat=True)),
-                          ['Chris Mills'])
+            ['Chris Mills'])
         self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)),
-                          [])
+            [])
 
     def test_foreign_key_cross_database_protection(self):
         "Operations that involve sharing FK objects across databases raise an error"
         # Create a book and author on the default database
         pro = Book.objects.create(title="Pro Django",
-                                  published=datetime.date(2008, 12, 16))
+            published=datetime.date(2008, 12, 16))
 
         marty = Person.objects.create(name="Marty Alchin")
 
         # Create a book and author on the other database
         dive = Book.objects.using('other').create(title="Dive into Python",
-                                                  published=datetime.date(2009, 5, 4))
+            published=datetime.date(2009, 5, 4))
 
         mark = Person.objects.using('other').create(name="Mark Pilgrim")
 
@@ -529,37 +529,37 @@ class QueryTestCase(TestCase):
         self.assertEqual(html5._state.db, 'other')
         # ... but it isn't saved yet
         self.assertEqual(list(Person.objects.using('other').values_list('name', flat=True)),
-                          ['Mark Pilgrim'])
+            ['Mark Pilgrim'])
         self.assertEqual(list(Book.objects.using('other').values_list('title', flat=True)),
-                           ['Dive into Python'])
+            ['Dive into Python'])
 
         # When saved (no using required), new objects goes to 'other'
         chris.save()
         html5.save()
         self.assertEqual(list(Person.objects.using('default').values_list('name', flat=True)),
-                          ['Marty Alchin'])
+            ['Marty Alchin'])
         self.assertEqual(list(Person.objects.using('other').values_list('name', flat=True)),
-                          ['Chris Mills', 'Mark Pilgrim'])
+            ['Chris Mills', 'Mark Pilgrim'])
         self.assertEqual(list(Book.objects.using('default').values_list('title', flat=True)),
-                          ['Pro Django'])
+            ['Pro Django'])
         self.assertEqual(list(Book.objects.using('other').values_list('title', flat=True)),
-                          ['Dive into HTML5', 'Dive into Python'])
+            ['Dive into HTML5', 'Dive into Python'])
 
         # This also works if you assign the FK in the constructor
         water = Book(title="Dive into Water", published=datetime.date(2001, 1, 1), editor=mark)
         self.assertEqual(water._state.db, 'other')
         # ... but it isn't saved yet
         self.assertEqual(list(Book.objects.using('default').values_list('title', flat=True)),
-                          ['Pro Django'])
+            ['Pro Django'])
         self.assertEqual(list(Book.objects.using('other').values_list('title', flat=True)),
-                          ['Dive into HTML5', 'Dive into Python'])
+            ['Dive into HTML5', 'Dive into Python'])
 
         # When saved, the new book goes to 'other'
         water.save()
         self.assertEqual(list(Book.objects.using('default').values_list('title', flat=True)),
-                          ['Pro Django'])
+            ['Pro Django'])
         self.assertEqual(list(Book.objects.using('other').values_list('title', flat=True)),
-                          ['Dive into HTML5', 'Dive into Python', 'Dive into Water'])
+            ['Dive into HTML5', 'Dive into Python', 'Dive into Water'])
 
     def test_foreign_key_deletion(self):
         "Cascaded deletions of Foreign Key relations issue queries on the right database"
@@ -608,14 +608,14 @@ class QueryTestCase(TestCase):
 
         # Check that queries work across joins
         self.assertEqual(list(User.objects.using('default').filter(userprofile__flavor='chocolate').values_list('username', flat=True)),
-                          ['alice'])
+            ['alice'])
         self.assertEqual(list(User.objects.using('other').filter(userprofile__flavor='chocolate').values_list('username', flat=True)),
-                          [])
+            [])
 
         self.assertEqual(list(User.objects.using('default').filter(userprofile__flavor='crunchy frog').values_list('username', flat=True)),
-                          [])
+            [])
         self.assertEqual(list(User.objects.using('other').filter(userprofile__flavor='crunchy frog').values_list('username', flat=True)),
-                          ['bob'])
+            ['bob'])
 
         # Reget the objects to clear caches
         alice_profile = UserProfile.objects.using('default').get(flavor='chocolate')
@@ -664,22 +664,22 @@ class QueryTestCase(TestCase):
 
         # ... but it isn't saved yet
         self.assertEqual(list(User.objects.using('other').values_list('username', flat=True)),
-                          ['bob'])
+            ['bob'])
         self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)),
-                           ['crunchy frog'])
+            ['crunchy frog'])
 
         # When saved (no using required), new objects goes to 'other'
         charlie.save()
         bob_profile.save()
         new_bob_profile.save()
         self.assertEqual(list(User.objects.using('default').values_list('username', flat=True)),
-                          ['alice'])
+            ['alice'])
         self.assertEqual(list(User.objects.using('other').values_list('username', flat=True)),
-                          ['bob', 'charlie'])
+            ['bob', 'charlie'])
         self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)),
-                           ['chocolate'])
+            ['chocolate'])
         self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)),
-                           ['crunchy frog', 'spring surprise'])
+            ['crunchy frog', 'spring surprise'])
 
         # This also works if you assign the O2O relation in the constructor
         denise = User.objects.db_manager('other').create_user('denise', 'denise@example.com')
@@ -688,16 +688,16 @@ class QueryTestCase(TestCase):
         self.assertEqual(denise_profile._state.db, 'other')
         # ... but it isn't saved yet
         self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)),
-                           ['chocolate'])
+            ['chocolate'])
         self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)),
-                           ['crunchy frog', 'spring surprise'])
+            ['crunchy frog', 'spring surprise'])
 
         # When saved, the new profile goes to 'other'
         denise_profile.save()
         self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)),
-                           ['chocolate'])
+            ['chocolate'])
         self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)),
-                           ['crunchy frog', 'spring surprise', 'tofu'])
+            ['crunchy frog', 'spring surprise', 'tofu'])
 
     def test_generic_key_separation(self):
         "Generic fields are constrained to a single database"
@@ -724,7 +724,7 @@ class QueryTestCase(TestCase):
 
         # Retrive related object by descriptor. Related objects should be database-bound
         self.assertEqual(list(dive.reviews.all().values_list('source', flat=True)),
-                          ['Python Weekly'])
+            ['Python Weekly'])
 
     def test_generic_key_reverse_operations(self):
         "Generic reverse manipulations are all constrained to a single DB"
@@ -738,37 +738,37 @@ class QueryTestCase(TestCase):
         review2 = Review.objects.using('other').create(source="Python Monthly", content_object=temp)
 
         self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
-                          [])
+            [])
         self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
-                          ['Python Weekly'])
+            ['Python Weekly'])
 
         # Add a second review
         dive.reviews.add(review2)
         self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
-                          [])
+            [])
         self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
-                          ['Python Monthly', 'Python Weekly'])
+            ['Python Monthly', 'Python Weekly'])
 
         # Remove the second author
         dive.reviews.remove(review1)
         self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
-                          [])
+            [])
         self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
-                          ['Python Monthly'])
+            ['Python Monthly'])
 
         # Clear all reviews
         dive.reviews.clear()
         self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
-                          [])
+            [])
         self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
-                          [])
+            [])
 
         # Create an author through the generic interface
         dive.reviews.create(source='Python Daily')
         self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
-                          [])
+            [])
         self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
-                          ['Python Daily'])
+            ['Python Daily'])
 
     def test_generic_key_cross_database_protection(self):
         "Operations that involve sharing generic key objects across databases raise an error"
@@ -810,16 +810,16 @@ class QueryTestCase(TestCase):
         self.assertEqual(review3._state.db, 'other')
         # ... but it isn't saved yet
         self.assertEqual(list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)),
-                          ['Python Monthly'])
+            ['Python Monthly'])
         self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
-                          ['Python Weekly'])
+            ['Python Weekly'])
 
         # When saved, John goes to 'other'
         review3.save()
         self.assertEqual(list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)),
-                          ['Python Monthly'])
+            ['Python Monthly'])
         self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
-                          ['Python Daily', 'Python Weekly'])
+            ['Python Daily', 'Python Weekly'])
 
     def test_generic_key_deletion(self):
         "Cascaded deletions of Generic Key relations issue queries on the right database"
@@ -1360,18 +1360,18 @@ class RouterTestCase(TestCase):
     def test_generic_key_cross_database_protection(self):
         "Generic Key operations can span databases if they share a source"
         # Create a book and author on the default database
-        pro = Book.objects.using('default'
-                ).create(title="Pro Django", published=datetime.date(2008, 12, 16))
+        pro = Book.objects.using(
+            'default').create(title="Pro Django", published=datetime.date(2008, 12, 16))
 
-        review1 = Review.objects.using('default'
-                    ).create(source="Python Monthly", content_object=pro)
+        review1 = Review.objects.using(
+            'default').create(source="Python Monthly", content_object=pro)
 
         # Create a book and author on the other database
-        dive = Book.objects.using('other'
-                ).create(title="Dive into Python", published=datetime.date(2009, 5, 4))
+        dive = Book.objects.using(
+            'other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
 
-        review2 = Review.objects.using('other'
-                    ).create(source="Python Weekly", content_object=dive)
+        review2 = Review.objects.using(
+            'other').create(source="Python Weekly", content_object=dive)
 
         # Set a generic foreign key with an object from a different database
         try:
@@ -1571,6 +1571,7 @@ class AuthTestCase(TestCase):
         command_output = new_io.getvalue().strip()
         self.assertTrue('"email": "alice@example.com"' in command_output)
 
+
 class AntiPetRouter(object):
     # A router that only expresses an opinion on migrate,
     # passing pets to the 'other' database
@@ -1582,6 +1583,7 @@ class AntiPetRouter(object):
         else:
             return model._meta.object_name != 'Pet'
 
+
 class FixtureTestCase(TestCase):
     multi_db = True
     fixtures = ['multidb-common', 'multidb']
@@ -1604,7 +1606,8 @@ class FixtureTestCase(TestCase):
         except Book.DoesNotExist:
             self.fail('"Pro Django" should exist on default database')
 
-        self.assertRaises(Book.DoesNotExist,
+        self.assertRaises(
+            Book.DoesNotExist,
             Book.objects.using('other').get,
             title="Pro Django"
         )
@@ -1615,11 +1618,13 @@ class FixtureTestCase(TestCase):
         except Book.DoesNotExist:
             self.fail('"Dive into Python" should exist on other database')
 
-        self.assertRaises(Book.DoesNotExist,
+        self.assertRaises(
+            Book.DoesNotExist,
             Book.objects.get,
             title="Dive into Python"
         )
-        self.assertRaises(Book.DoesNotExist,
+        self.assertRaises(
+            Book.DoesNotExist,
             Book.objects.using('default').get,
             title="Dive into Python"
         )
@@ -1640,6 +1645,7 @@ class FixtureTestCase(TestCase):
         # No objects will actually be loaded
         self.assertEqual(command_output, "Installed 0 object(s) (of 2) from 1 fixture(s)")
 
+
 class PickleQuerySetTestCase(TestCase):
     multi_db = True
 
@@ -1657,6 +1663,7 @@ class DatabaseReceiver(object):
     def __call__(self, signal, sender, **kwargs):
         self._database = kwargs['using']
 
+
 class WriteToOtherRouter(object):
     """
     A router that sends all writes to the other database.
@@ -1664,6 +1671,7 @@ class WriteToOtherRouter(object):
     def db_for_write(self, model, **hints):
         return "other"
 
+
 class SignalTests(TestCase):
     multi_db = True
 
@@ -1771,6 +1779,7 @@ class SignalTests(TestCase):
         self._write_to_default()
         self.assertEqual(receiver._database, "other")
 
+
 class AttributeErrorRouter(object):
     "A router to test the exception handling of ConnectionRouter"
     def db_for_read(self, model, **hints):
@@ -1779,6 +1788,7 @@ class AttributeErrorRouter(object):
     def db_for_write(self, model, **hints):
         raise AttributeError
 
+
 class RouterAttributeErrorTestCase(TestCase):
     multi_db = True
 
@@ -1824,12 +1834,14 @@ class RouterAttributeErrorTestCase(TestCase):
         router.routers = [AttributeErrorRouter()]  # Install our router
         self.assertRaises(AttributeError, setattr, b, 'authors', [p])
 
+
 class ModelMetaRouter(object):
     "A router to ensure model arguments are real model classes"
     def db_for_write(self, model, **hints):
         if not hasattr(model, '_meta'):
             raise ValueError
 
+
 class RouterModelArgumentTestCase(TestCase):
     multi_db = True