From 3bc0d46a840f17dce561daca8a6b8690b2cf5d0a Mon Sep 17 00:00:00 2001 From: coagulant Date: Sun, 3 Nov 2013 01:02:56 +0400 Subject: [PATCH 1/5] 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/queries/tests.py | 4 +- tests/queryset_pickle/tests.py | 2 +- tests/requests/tests.py | 10 +- tests/serializers_regress/tests.py | 26 ++-- 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_debug.py | 6 +- tests/view_tests/tests/test_defaults.py | 4 +- 154 files changed, 647 insertions(+), 647 deletions(-) diff --git a/django/conf/__init__.py b/django/conf/__init__.py index 7a915f1486b..5245ff9e25a 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 377c010b321..19d70eeb3e3 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 4472600398d..e1a8a820e31 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 9ccddbb24d9..392eb48c1c7 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 42ca212392c..fd445fac6a7 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 b3731a3617b..b57f6213a52 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 bf8a5ce372e..4b1678cffd6 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 5accf9e3d2d..279cd3c5189 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 08029a876ea..dee0a889f64 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 41c732f7b85..37faa80b8a8 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 e3ac674ab0f..729eee53707 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 4bdf24e491c..2f8d403d85c 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 1d4e76c55b0..8f5a25ea535 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 1de3948a2be..5be8131ed60 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 da1f003411b..b1900a3b7ca 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 f6c8f40648e..7b85807404d 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 de592240f0f..0facf691a94 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 96a724b2b8c..a38457a435f 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 9b6630d7753..7e499da4eef 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 b12e478ccbc..368535d2936 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 bb26bec6be6..1d2eb5f9cb5 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 28b4d06ca2e..29e57f136c7 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 1bff4d98617..41dab5f53b6 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 c2c9f9da373..2b281d810f1 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 2a0df6c43f5..fe330707862 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 5accf9e3d2d..279cd3c5189 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 8f976d7045f..5bf43af0d47 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 528ae301071..ca7d2e294cd 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 25cfc793cf9..59978394771 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 9452428dd9f..61411767605 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 a5ec333d504..6057a21056e 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 413ce2788b7..2cc5001c6a2 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 6ff8ca791ba..dfbd1a681f7 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 8e9e9a487e9..86d63e42f14 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 8e9e9a487e9..86d63e42f14 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 8874da75192..7673d472a1c 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 395fca91140..175def19562 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 ee38fdf1d5e..012a14ef649 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 e3514dd82a9..6ab842dd616 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 0b48cb08513..e75f1a2a609 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 76651762286..c4ce53fec00 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 2242f7de582..ed3668907a8 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 12b3bdb2110..b2cb0b41819 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 04977eeef82..a0ffef90f4c 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 0066f86b52c..a17f875f408 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(' ' diff --git a/django/contrib/contenttypes/generic.py b/django/contrib/contenttypes/generic.py index 10d3f7d4a57..26af7f0d3fd 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 2f494064f33..9fe595d0cf9 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 e7de911a8d2..02e6f275477 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 26cec743a92..81aa1e2fb6b 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 14df0ff1d36..8212938f015 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 eae08479dff..1a71be681c7 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 827c5217a57..5149b541a21 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 662b20ae79a..6dc2ee23b94 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 5f1d4623ab6..cdff5396cc6 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 a331053eeb1..753baff9ac1 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 11d3b2452f6..374a0f424e4 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 f5dc7e10e9b..4e4fb633c76 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 a2c0e9e1334..5cfdb4a8ea2 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 4644fbc5332..555ca695319 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 65d78a17354..ed6bb2ad9c2 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 39cccf8440c..372232755d8 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 4e7a990d501..f771608e1d9 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 7a03712600a..72f766310ec 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 bd99047604a..a3682ffd91b 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 55381bf7fd1..6b10396aba8 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 9c24f614dff..59cd9a32cc7 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 fc3b247f1f4..5340dac99de 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 ee820fc3c6b..b61c95913d0 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 6bbadcdf160..22b3ceac1d1 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 8db977e0255..6b7c734066d 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 251173e432d..8234bc8d9b4 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 9ae06d76e05..7b8fc159b46 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 - self.assertRaises(ValueError, self.client.get, '/feeds/w3cgeo3/') # Polygons in + self.assertRaises(ValueError, self.client.get, '/feeds/w3cgeo2/') # Box in + self.assertRaises(ValueError, self.client.get, '/feeds/w3cgeo3/') # Polygons in diff --git a/django/contrib/gis/tests/geoapp/test_sitemaps.py b/django/contrib/gis/tests/geoapp/test_sitemaps.py index 92d70e1fd5b..d9ede80c57d 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 4b20c4b2c84..f1b2f1adbe4 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 83c73dfd4d9..615c1423249 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 5e8b0879ed6..1b66c6d94c3 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 d42fe1d6eec..df6f22c38a0 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 8bc9177fb4d..194578d1e0b 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 9d70026dbb0..5f57bc17494 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 2ec3fe484b3..d0d09dee485 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 c4e2b0abfb3..028f01382ba 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 3a6e31152f0..1ab42c03e13 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 275eba57136..862bdfb69bc 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 9b2c5e8bd1e..c49c20e59b1 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 3bd6993771b..4b23d48fb4b 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 577cb2176b7..bf65687d5cf 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 4c54b3e39d4..21cadf48b83 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 3516ac330b7..de49f5e2418 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 89549dc3c1b..a24ae2b51e3 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 723fe626bea..76b50916e09 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 cf5ec7aa778..695dda258b5 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 84bbf1569ff..b38d00c84a4 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 fc9a0d034f4..6cb2f1467e3 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 9e6e29d5e3b..43f61faf0aa 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 046af9af556..aef0bf08aaf 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 723453c9c59..b9496868b0d 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 5d07f68f734..6c9728889ff 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 6ebc572e0cc..da8629ace65 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 095cb4efe43..8bed6415c3f 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 cf219d39aa9..13785ed17a7 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 73df8633ca0..ce3f0950557 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 022de521342..dec2e2dd9e6 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 ca49f677124..5bfa68b071f 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 46a308f5ce2..988b8bc644f 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 664a817f375..28c0195a48f 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 07ab6cb27d5..4d11fb21e0f 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 96c6b240348..361e46f5e5a 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 0de00210fe8..1ef97d7cf0c 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 2b90f1dc2e9..048d8867203 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 b2ab1269b58..05a7329faea 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 d01b785001b..773b7034976 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 96d3e65189a..2829ca14433 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 f8625e73d91..49e70fab846 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 dd708a5d9ac..aaca7b6dc01 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,E302,E501,W601 [metadata] license-file = LICENSE diff --git a/tests/admin_changelist/admin.py b/tests/admin_changelist/admin.py index d0797581dce..42b8c959af6 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 e0b8bde2de4..bd2e4e5e98b 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 bdfacdc206a..bbec124d4d3 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 98c19befa44..da5ddc03b36 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 763e97bd721..0085b35586a 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 36b35aeefea..2aa96fbafa9 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 f964d6cffb1..560b4409c26 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 67f3b4216a6..4dcca9a4cb3 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 0aa8e989331..4b36f8bd32a 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 8e192bd0829..be42a131811 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 0c6ae915539..a79d4d9fac0 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 62007e43fbe..b70b01ed16a 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 41e8a2d5d36..3cd954d3ad7 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 b30ef136e9d..2d4e52e4d52 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 aecf8f32d54..b30742106b8 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 784724bf41f..cf721b5510c 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):
  • Order:
  • """) 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 95308d4eeb0..25b491a4992 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 1cf2f492a46..23f17f7b221 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 1e099d2bb47..820aecf1f79 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 04bc0a8632a..18088e5e16c 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 e8b3ac7b7d2..b1f3de0ef99 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 8e04a4d3285..0c991dcf136 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 ee5d77919f0..35443e32e4c 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 feb3351cf70..5dd33fc80f0 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 2da852d11e0..ddc7a4ceefb 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 4c57e0f5499..ac9d68132e5 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): '

    ') 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): '

    ') 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): '

    ') 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): '

    ') 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): '

    ') 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): '

    ' % 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): '

    ' % 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): '

    ') 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): '

    ') 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): '

    ') 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): '

    ') 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 4789e35a43a..27f54821d6d 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 f7c58621679..679c7e33f52 100644 --- a/tests/multiple_database/tests.py +++ b/tests/multiple_database/tests.py @@ -1785,10 +1785,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): @@ -1800,22 +1800,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 29e1fcb4bb6..d5b68658ff8 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/queries/tests.py b/tests/queries/tests.py index c1d461f4855..bdff134b27a 100644 --- a/tests/queries/tests.py +++ b/tests/queries/tests.py @@ -2224,12 +2224,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 diff --git a/tests/queryset_pickle/tests.py b/tests/queryset_pickle/tests.py index 7ce4348c1ae..077ac6f59cb 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 137b3245888..c00f5bb5e0d 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 a56abe0b6b0..7f65921aff0 100644 --- a/tests/serializers_regress/tests.py +++ b/tests/serializers_regress/tests.py @@ -256,21 +256,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, []), @@ -288,7 +288,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 36a519fd907..f9e59fd542a 100644 --- a/tests/template_tests/filters.py +++ b/tests/template_tests/filters.py @@ -352,7 +352,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 a39f952e4c0..041a17c9f1d 100644 --- a/tests/template_tests/tests.py +++ b/tests/template_tests/tests.py @@ -840,7 +840,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 cd59f50213d..5e4673c3c5c 100644 --- a/tests/test_client/tests.py +++ b/tests/test_client/tests.py @@ -438,7 +438,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 8a371cb52ba..459c110803d 100644 --- a/tests/test_client_regress/tests.py +++ b/tests/test_client_regress/tests.py @@ -121,14 +121,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')) @@ -1193,7 +1193,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 3f16dadae25..9030f072398 100644 --- a/tests/view_tests/__init__.py +++ b/tests/view_tests/__init__.py @@ -6,5 +6,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_debug.py b/tests/view_tests/tests/test_debug.py index b22c7aad43b..225215e4751 100644 --- a/tests/view_tests/tests/test_debug.py +++ b/tests/view_tests/tests/test_debug.py @@ -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) diff --git a/tests/view_tests/tests/test_defaults.py b/tests/view_tests/tests/test_defaults.py index 13e56d604bc..128fb7cb07b 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 e2ae8b048e7198428f696375b8bdcd89e90002d1 Mon Sep 17 00:00:00 2001 From: Ray Ashman Jr Date: Sat, 2 Nov 2013 19:53:29 -0400 Subject: [PATCH 2/5] 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 048d8867203..c5b94c83a0c 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 ('' % (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'[\w\.]+)' r'\[(?P\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 3fed8c6aa71..fa044ba6ece 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 40a8e278fca..11fc5afe49d 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 ca162d18d06..00f7ce160a8 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 0d664afdf40..7e38f7b021d 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 e5fe4a776a8..49855dd33b1 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 27413a2e67e..78483f2d4c8 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'(?= 1900: return super(type(dt), dt).strftime(fmt) diff --git a/django/utils/dictconfig.py b/django/utils/dictconfig.py index 773b7034976..e79dc041efa 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 ad4473df6a0..ee67df30eae 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 416234521f1..00d982025a4 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 0c59e2c04a9..fc68179f3ab 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 6d04ae52053..3ad549de19f 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('&', 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 413ac72a08d..e3365776f39 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 c8390cc7eb7..199b4ea87d1 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 c44726090f3..097d31dd0fb 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 7abefb2258f..b9d311499b7 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 8f20e8ed888..bb05afefc42 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 8fb0f64e095..b39ab203a78 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 951c3efcf9d..eec554a1ef1 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 d99c8bbd785..e4e8c6e1be6 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 88c77a51107..9e3beb0f7dc 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 b79af80dd1f..d78b6d64127 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 "" % 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 2829ca14433..0ee5d588c71 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 a0da002dc9f..df4e165066a 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 cd2f9c0f55c..056669278bd 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 370cb32ce71..d221c2c0873 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 9ede1ed49fd..751905efaf1 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 e55f6a12341..11c8734eec9 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 8d7ddec17cbf99c3887f191a4472ecaabe0f6cf6 Mon Sep 17 00:00:00 2001 From: Ray Ashman Jr Date: Sat, 2 Nov 2013 20:11:21 -0400 Subject: [PATCH 3/5] 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 c5b94c83a0c..2b90f1dc2e9 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 ('' % (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'[\w\.]+)' r'\[(?P\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 e459893e3454e60cb55f9995106324d5f2a8643f Mon Sep 17 00:00:00 2001 From: Ray Ashman Jr Date: Sat, 2 Nov 2013 20:20:53 -0400 Subject: [PATCH 4/5] 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 2b90f1dc2e9..048d8867203 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 fe995e6cbdcf2766cf0aa951c8ef4549ad27694c Mon Sep 17 00:00:00 2001 From: Alex Gaynor Date: Sat, 2 Nov 2013 17:37:15 -0700 Subject: [PATCH 5/5] Fixed the remaining E302 violations int eh django package --- django/forms/widgets.py | 11 +++++ 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 ++ 19 files changed, 199 insertions(+) diff --git a/django/forms/widgets.py b/django/forms/widgets.py index 88dc28d664e..ce38bf00a58 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 . 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 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 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') @@ -389,6 +397,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 +524,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 +859,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 inputs. diff --git a/django/http/multipartparser.py b/django/http/multipartparser.py index 28c0195a48f..dcf2d1ae0df 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 ad13108e4e2..efeca3ea2a3 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=''): @@ -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 d16a0a75339..ba2c3d4d076 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 eb6f855cadb..a4f0a89554f 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', '
    ')) + @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 2822c3d3629..77d63ab256c 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 410b03726ae..3465a7141e5 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 c6bb3acadf0..740b503cc55 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 44983065e4b..4f8ddfccac2 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 67cec49c74c..646168cd1ef 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 7da180323a3..04e4f73b7b8 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 1a7f0d2cd77..52e41ef0b94 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 fc8029d738d..7c54ce034c6 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 667de2470e4..31dae9b105c 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 cf5c3ac7509..e9ba0fdd63a 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 523c86df52c..6a9659171d1 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 6c12ea43f3b..268d084d425 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 ffa8b0b924c..818c1263b7e 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'') _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 5460eef25e2..f256f7a1e71 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.