diff --git a/django/conf/locale/__init__.py b/django/conf/locale/__init__.py index af08c00e98f..93e98194a42 100644 --- a/django/conf/locale/__init__.py +++ b/django/conf/locale/__init__.py @@ -1,434 +1,436 @@ +from __future__ import unicode_literals + LANG_INFO = { 'ar': { 'bidi': True, 'code': 'ar', 'name': 'Arabic', - 'name_local': u'\u0627\u0644\u0639\u0631\u0628\u064a\u0651\u0629', + 'name_local': '\u0627\u0644\u0639\u0631\u0628\u064a\u0651\u0629', }, 'az': { 'bidi': True, 'code': 'az', 'name': 'Azerbaijani', - 'name_local': u'az\u0259rbaycan dili', + 'name_local': 'az\u0259rbaycan dili', }, 'bg': { 'bidi': False, 'code': 'bg', 'name': 'Bulgarian', - 'name_local': u'\u0431\u044a\u043b\u0433\u0430\u0440\u0441\u043a\u0438', + 'name_local': '\u0431\u044a\u043b\u0433\u0430\u0440\u0441\u043a\u0438', }, 'bn': { 'bidi': False, 'code': 'bn', 'name': 'Bengali', - 'name_local': u'\u09ac\u09be\u0982\u09b2\u09be', + 'name_local': '\u09ac\u09be\u0982\u09b2\u09be', }, 'bs': { 'bidi': False, 'code': 'bs', 'name': 'Bosnian', - 'name_local': u'bosanski', + 'name_local': 'bosanski', }, 'ca': { 'bidi': False, 'code': 'ca', 'name': 'Catalan', - 'name_local': u'catal\xe0', + 'name_local': 'catal\xe0', }, 'cs': { 'bidi': False, 'code': 'cs', 'name': 'Czech', - 'name_local': u'\u010desky', + 'name_local': '\u010desky', }, 'cy': { 'bidi': False, 'code': 'cy', 'name': 'Welsh', - 'name_local': u'Cymraeg', + 'name_local': 'Cymraeg', }, 'da': { 'bidi': False, 'code': 'da', 'name': 'Danish', - 'name_local': u'Dansk', + 'name_local': 'Dansk', }, 'de': { 'bidi': False, 'code': 'de', 'name': 'German', - 'name_local': u'Deutsch', + 'name_local': 'Deutsch', }, 'el': { 'bidi': False, 'code': 'el', 'name': 'Greek', - 'name_local': u'\u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac', + 'name_local': '\u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac', }, 'en': { 'bidi': False, 'code': 'en', 'name': 'English', - 'name_local': u'English', + 'name_local': 'English', }, 'en-gb': { 'bidi': False, 'code': 'en-gb', 'name': 'British English', - 'name_local': u'British English', + 'name_local': 'British English', }, 'eo': { 'bidi': False, 'code': 'eo', 'name': 'Esperanto', - 'name_local': u'Esperanto', + 'name_local': 'Esperanto', }, 'es': { 'bidi': False, 'code': 'es', 'name': 'Spanish', - 'name_local': u'espa\xf1ol', + 'name_local': 'espa\xf1ol', }, 'es-ar': { 'bidi': False, 'code': 'es-ar', 'name': 'Argentinian Spanish', - 'name_local': u'espa\xf1ol de Argentina', + 'name_local': 'espa\xf1ol de Argentina', }, 'es-mx': { 'bidi': False, 'code': 'es-mx', 'name': 'Mexican Spanish', - 'name_local': u'espa\xf1ol de Mexico', + 'name_local': 'espa\xf1ol de Mexico', }, 'es-ni': { 'bidi': False, 'code': 'es-ni', 'name': 'Nicaraguan Spanish', - 'name_local': u'espa\xf1ol de Nicaragua', + 'name_local': 'espa\xf1ol de Nicaragua', }, 'et': { 'bidi': False, 'code': 'et', 'name': 'Estonian', - 'name_local': u'eesti', + 'name_local': 'eesti', }, 'eu': { 'bidi': False, 'code': 'eu', 'name': 'Basque', - 'name_local': u'Basque', + 'name_local': 'Basque', }, 'fa': { 'bidi': True, 'code': 'fa', 'name': 'Persian', - 'name_local': u'\u0641\u0627\u0631\u0633\u06cc', + 'name_local': '\u0641\u0627\u0631\u0633\u06cc', }, 'fi': { 'bidi': False, 'code': 'fi', 'name': 'Finnish', - 'name_local': u'suomi', + 'name_local': 'suomi', }, 'fr': { 'bidi': False, 'code': 'fr', 'name': 'French', - 'name_local': u'Fran\xe7ais', + 'name_local': 'Fran\xe7ais', }, 'fy-nl': { 'bidi': False, 'code': 'fy-nl', 'name': 'Frisian', - 'name_local': u'Frisian', + 'name_local': 'Frisian', }, 'ga': { 'bidi': False, 'code': 'ga', 'name': 'Irish', - 'name_local': u'Gaeilge', + 'name_local': 'Gaeilge', }, 'gl': { 'bidi': False, 'code': 'gl', 'name': 'Galician', - 'name_local': u'galego', + 'name_local': 'galego', }, 'he': { 'bidi': True, 'code': 'he', 'name': 'Hebrew', - 'name_local': u'\u05e2\u05d1\u05e8\u05d9\u05ea', + 'name_local': '\u05e2\u05d1\u05e8\u05d9\u05ea', }, 'hi': { 'bidi': False, 'code': 'hi', 'name': 'Hindi', - 'name_local': u'Hindi', + 'name_local': 'Hindi', }, 'hr': { 'bidi': False, 'code': 'hr', 'name': 'Croatian', - 'name_local': u'Hrvatski', + 'name_local': 'Hrvatski', }, 'hu': { 'bidi': False, 'code': 'hu', 'name': 'Hungarian', - 'name_local': u'Magyar', + 'name_local': 'Magyar', }, 'id': { 'bidi': False, 'code': 'id', 'name': 'Indonesian', - 'name_local': u'Bahasa Indonesia', + 'name_local': 'Bahasa Indonesia', }, 'is': { 'bidi': False, 'code': 'is', 'name': 'Icelandic', - 'name_local': u'\xcdslenska', + 'name_local': '\xcdslenska', }, 'it': { 'bidi': False, 'code': 'it', 'name': 'Italian', - 'name_local': u'italiano', + 'name_local': 'italiano', }, 'ja': { 'bidi': False, 'code': 'ja', 'name': 'Japanese', - 'name_local': u'\u65e5\u672c\u8a9e', + 'name_local': '\u65e5\u672c\u8a9e', }, 'ka': { 'bidi': False, 'code': 'ka', 'name': 'Georgian', - 'name_local': u'\u10e5\u10d0\u10e0\u10d7\u10e3\u10da\u10d8', + 'name_local': '\u10e5\u10d0\u10e0\u10d7\u10e3\u10da\u10d8', }, 'kk': { 'bidi': False, 'code': 'kk', 'name': 'Kazakh', - 'name_local': u'\u049a\u0430\u0437\u0430\u049b', + 'name_local': '\u049a\u0430\u0437\u0430\u049b', }, 'km': { 'bidi': False, 'code': 'km', 'name': 'Khmer', - 'name_local': u'Khmer', + 'name_local': 'Khmer', }, 'kn': { 'bidi': False, 'code': 'kn', 'name': 'Kannada', - 'name_local': u'Kannada', + 'name_local': 'Kannada', }, 'ko': { 'bidi': False, 'code': 'ko', 'name': 'Korean', - 'name_local': u'\ud55c\uad6d\uc5b4', + 'name_local': '\ud55c\uad6d\uc5b4', }, 'lt': { 'bidi': False, 'code': 'lt', 'name': 'Lithuanian', - 'name_local': u'Lithuanian', + 'name_local': 'Lithuanian', }, 'lv': { 'bidi': False, 'code': 'lv', 'name': 'Latvian', - 'name_local': u'latvie\u0161u', + 'name_local': 'latvie\u0161u', }, 'mk': { 'bidi': False, 'code': 'mk', 'name': 'Macedonian', - 'name_local': u'\u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0441\u043a\u0438', + 'name_local': '\u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0441\u043a\u0438', }, 'ml': { 'bidi': False, 'code': 'ml', 'name': 'Malayalam', - 'name_local': u'Malayalam', + 'name_local': 'Malayalam', }, 'mn': { 'bidi': False, 'code': 'mn', 'name': 'Mongolian', - 'name_local': u'Mongolian', + 'name_local': 'Mongolian', }, 'nb': { 'bidi': False, 'code': 'nb', 'name': 'Norwegian Bokmal', - 'name_local': u'Norsk (bokm\xe5l)', + 'name_local': 'Norsk (bokm\xe5l)', }, 'ne': { 'bidi': False, 'code': 'ne', 'name': 'Nepali', - 'name_local': u'\u0928\u0947\u092a\u093e\u0932\u0940', + 'name_local': '\u0928\u0947\u092a\u093e\u0932\u0940', }, 'nl': { 'bidi': False, 'code': 'nl', 'name': 'Dutch', - 'name_local': u'Nederlands', + 'name_local': 'Nederlands', }, 'nn': { 'bidi': False, 'code': 'nn', 'name': 'Norwegian Nynorsk', - 'name_local': u'Norsk (nynorsk)', + 'name_local': 'Norsk (nynorsk)', }, 'no': { 'bidi': False, 'code': 'no', 'name': 'Norwegian', - 'name_local': u'Norsk', + 'name_local': 'Norsk', }, 'pa': { 'bidi': False, 'code': 'pa', 'name': 'Punjabi', - 'name_local': u'Punjabi', + 'name_local': 'Punjabi', }, 'pl': { 'bidi': False, 'code': 'pl', 'name': 'Polish', - 'name_local': u'polski', + 'name_local': 'polski', }, 'pt': { 'bidi': False, 'code': 'pt', 'name': 'Portuguese', - 'name_local': u'Portugu\xeas', + 'name_local': 'Portugu\xeas', }, 'pt-br': { 'bidi': False, 'code': 'pt-br', 'name': 'Brazilian Portuguese', - 'name_local': u'Portugu\xeas Brasileiro', + 'name_local': 'Portugu\xeas Brasileiro', }, 'ro': { 'bidi': False, 'code': 'ro', 'name': 'Romanian', - 'name_local': u'Rom\xe2n\u0103', + 'name_local': 'Rom\xe2n\u0103', }, 'ru': { 'bidi': False, 'code': 'ru', 'name': 'Russian', - 'name_local': u'\u0420\u0443\u0441\u0441\u043a\u0438\u0439', + 'name_local': '\u0420\u0443\u0441\u0441\u043a\u0438\u0439', }, 'sk': { 'bidi': False, 'code': 'sk', 'name': 'Slovak', - 'name_local': u'slovensk\xfd', + 'name_local': 'slovensk\xfd', }, 'sl': { 'bidi': False, 'code': 'sl', 'name': 'Slovenian', - 'name_local': u'Sloven\u0161\u010dina', + 'name_local': 'Sloven\u0161\u010dina', }, 'sq': { 'bidi': False, 'code': 'sq', 'name': 'Albanian', - 'name_local': u'Albanian', + 'name_local': 'Albanian', }, 'sr': { 'bidi': False, 'code': 'sr', 'name': 'Serbian', - 'name_local': u'\u0441\u0440\u043f\u0441\u043a\u0438', + 'name_local': '\u0441\u0440\u043f\u0441\u043a\u0438', }, 'sr-latn': { 'bidi': False, 'code': 'sr-latn', 'name': 'Serbian Latin', - 'name_local': u'srpski (latinica)', + 'name_local': 'srpski (latinica)', }, 'sv': { 'bidi': False, 'code': 'sv', 'name': 'Swedish', - 'name_local': u'Svenska', + 'name_local': 'Svenska', }, 'sw': { 'bidi': False, 'code': 'sw', 'name': 'Swahili', - 'name_local': u'Kiswahili', + 'name_local': 'Kiswahili', }, 'ta': { 'bidi': False, 'code': 'ta', 'name': 'Tamil', - 'name_local': u'\u0ba4\u0bae\u0bbf\u0bb4\u0bcd', + 'name_local': '\u0ba4\u0bae\u0bbf\u0bb4\u0bcd', }, 'te': { 'bidi': False, 'code': 'te', 'name': 'Telugu', - 'name_local': u'\u0c24\u0c46\u0c32\u0c41\u0c17\u0c41', + 'name_local': '\u0c24\u0c46\u0c32\u0c41\u0c17\u0c41', }, 'th': { 'bidi': False, 'code': 'th', 'name': 'Thai', - 'name_local': u'Thai', + 'name_local': 'Thai', }, 'tr': { 'bidi': False, 'code': 'tr', 'name': 'Turkish', - 'name_local': u'T\xfcrk\xe7e', + 'name_local': 'T\xfcrk\xe7e', }, 'tt': { 'bidi': False, 'code': 'tt', 'name': 'Tatar', - 'name_local': u'\u0422\u0430\u0442\u0430\u0440\u0447\u0430', + 'name_local': '\u0422\u0430\u0442\u0430\u0440\u0447\u0430', }, 'uk': { 'bidi': False, 'code': 'uk', 'name': 'Ukrainian', - 'name_local': u'\u0423\u043a\u0440\u0430\u0457\u043d\u0441\u044c\u043a\u0430', + 'name_local': '\u0423\u043a\u0440\u0430\u0457\u043d\u0441\u044c\u043a\u0430', }, 'ur': { 'bidi': False, 'code': 'ur', 'name': 'Urdu', - 'name_local': u'\u0627\u0631\u062f\u0648', + 'name_local': '\u0627\u0631\u062f\u0648', }, 'vi': { 'bidi': False, 'code': 'vi', 'name': 'Vietnamese', - 'name_local': u'Vietnamese', + 'name_local': 'Vietnamese', }, 'zh-cn': { 'bidi': False, 'code': 'zh-cn', 'name': 'Simplified Chinese', - 'name_local': u'\u7b80\u4f53\u4e2d\u6587', + 'name_local': '\u7b80\u4f53\u4e2d\u6587', }, 'zh-tw': { 'bidi': False, 'code': 'zh-tw', 'name': 'Traditional Chinese', - 'name_local': u'\u7e41\u9ad4\u4e2d\u6587', + 'name_local': '\u7e41\u9ad4\u4e2d\u6587', } } diff --git a/django/conf/locale/bg/formats.py b/django/conf/locale/bg/formats.py index 3dc47049723..c5e89737b62 100644 --- a/django/conf/locale/bg/formats.py +++ b/django/conf/locale/bg/formats.py @@ -1,6 +1,7 @@ # -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # +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 @@ -19,5 +20,5 @@ SHORT_DATE_FORMAT = 'd.m.Y' # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = u' ' # Non-breaking space +THOUSAND_SEPARATOR = ' ' # Non-breaking space # NUMBER_GROUPING = diff --git a/django/conf/locale/cs/formats.py b/django/conf/locale/cs/formats.py index 56e9e735472..f0b674227b6 100644 --- a/django/conf/locale/cs/formats.py +++ b/django/conf/locale/cs/formats.py @@ -1,6 +1,7 @@ # -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # +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 @@ -33,5 +34,5 @@ DATETIME_INPUT_FORMATS = ( '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = u'\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 68a9276328c..6cf2335f5ee 100644 --- a/django/conf/locale/en/formats.py +++ b/django/conf/locale/en/formats.py @@ -37,7 +37,7 @@ DATETIME_INPUT_FORMATS = ( '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y', # '10/25/06' ) -DECIMAL_SEPARATOR = u'.' -THOUSAND_SEPARATOR = u',' +DECIMAL_SEPARATOR = '.' +THOUSAND_SEPARATOR = ',' NUMBER_GROUPING = 3 diff --git a/django/conf/locale/es_MX/formats.py b/django/conf/locale/es_MX/formats.py index af534e60ad4..cef6b4e2f92 100644 --- a/django/conf/locale/es_MX/formats.py +++ b/django/conf/locale/es_MX/formats.py @@ -1,6 +1,7 @@ # -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # +from __future__ import unicode_literals DATE_FORMAT = r'j \d\e F \d\e Y' TIME_FORMAT = 'H:i:s' @@ -24,5 +25,5 @@ DATETIME_INPUT_FORMATS = ( '%d/%m/%y %H:%M', ) DECIMAL_SEPARATOR = '.' # ',' is also official (less common): NOM-008-SCFI-2002 -THOUSAND_SEPARATOR = u'\xa0' # non-breaking space +THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3 diff --git a/django/conf/locale/et/formats.py b/django/conf/locale/et/formats.py index 7de0cd44b5a..dd0d1a696e4 100644 --- a/django/conf/locale/et/formats.py +++ b/django/conf/locale/et/formats.py @@ -1,6 +1,7 @@ # -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # +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 @@ -19,5 +20,5 @@ SHORT_DATE_FORMAT = 'd.m.Y' # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = u' ' # 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 198ece66b0f..9a658eed402 100644 --- a/django/conf/locale/fi/formats.py +++ b/django/conf/locale/fi/formats.py @@ -1,6 +1,7 @@ # -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # +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 @@ -19,5 +20,5 @@ SHORT_DATE_FORMAT = 'j.n.Y' # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = u' ' # 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 6d8e334f096..3b5e8861d87 100644 --- a/django/conf/locale/fr/formats.py +++ b/django/conf/locale/fr/formats.py @@ -1,6 +1,7 @@ # -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # +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 @@ -37,5 +38,5 @@ DATETIME_INPUT_FORMATS = ( '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = u'\xa0' # non-breaking space +THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3 diff --git a/django/conf/locale/he/formats.py b/django/conf/locale/he/formats.py index e83d7085a9a..1c8b1b55663 100644 --- a/django/conf/locale/he/formats.py +++ b/django/conf/locale/he/formats.py @@ -1,6 +1,7 @@ # -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # +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 diff --git a/django/conf/locale/hu/formats.py b/django/conf/locale/hu/formats.py index 53a8fc7cb0e..a9298bf022f 100644 --- a/django/conf/locale/hu/formats.py +++ b/django/conf/locale/hu/formats.py @@ -1,6 +1,7 @@ # -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # +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 @@ -28,5 +29,5 @@ DATETIME_INPUT_FORMATS = ( '%Y.%m.%d.', # '2006.10.25.' ) DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = u' ' # Non-breaking space +THOUSAND_SEPARATOR = ' ' # Non-breaking space NUMBER_GROUPING = 3 diff --git a/django/conf/locale/ja/formats.py b/django/conf/locale/ja/formats.py index ce9d1acb9a5..263aa0a3444 100644 --- a/django/conf/locale/ja/formats.py +++ b/django/conf/locale/ja/formats.py @@ -1,6 +1,7 @@ # -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # +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 diff --git a/django/conf/locale/km/formats.py b/django/conf/locale/km/formats.py index 70afa27c1d5..ace2fc1eea3 100644 --- a/django/conf/locale/km/formats.py +++ b/django/conf/locale/km/formats.py @@ -1,6 +1,7 @@ # -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # +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 diff --git a/django/conf/locale/ko/formats.py b/django/conf/locale/ko/formats.py index af65392934b..3c0431e4bfc 100644 --- a/django/conf/locale/ko/formats.py +++ b/django/conf/locale/ko/formats.py @@ -1,6 +1,7 @@ # -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # +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 diff --git a/django/conf/locale/lv/formats.py b/django/conf/locale/lv/formats.py index 316d777e8b1..e4ef524adf6 100644 --- a/django/conf/locale/lv/formats.py +++ b/django/conf/locale/lv/formats.py @@ -1,6 +1,7 @@ # -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # +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 @@ -37,5 +38,5 @@ DATETIME_INPUT_FORMATS = ( '%d.%m.%y', # '25.10.06' ) DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = u' ' # Non-breaking space +THOUSAND_SEPARATOR = ' ' # Non-breaking space NUMBER_GROUPING = 3 diff --git a/django/conf/locale/nb/formats.py b/django/conf/locale/nb/formats.py index 8de88512a02..4a896dd80d1 100644 --- a/django/conf/locale/nb/formats.py +++ b/django/conf/locale/nb/formats.py @@ -1,6 +1,7 @@ # -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # +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 @@ -39,5 +40,5 @@ DATETIME_INPUT_FORMATS = ( '%d.%m.%y', # '25.10.06' ) DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = u'\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 8de88512a02..4a896dd80d1 100644 --- a/django/conf/locale/nn/formats.py +++ b/django/conf/locale/nn/formats.py @@ -1,6 +1,7 @@ # -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # +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 @@ -39,5 +40,5 @@ DATETIME_INPUT_FORMATS = ( '%d.%m.%y', # '25.10.06' ) DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = u'\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 1c538b26ab6..021063d474d 100644 --- a/django/conf/locale/pl/formats.py +++ b/django/conf/locale/pl/formats.py @@ -1,6 +1,7 @@ # -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # +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 @@ -33,5 +34,5 @@ DATETIME_INPUT_FORMATS = ( '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = u' ' +THOUSAND_SEPARATOR = ' ' NUMBER_GROUPING = 3 diff --git a/django/conf/locale/pt_BR/formats.py b/django/conf/locale/pt_BR/formats.py index 6a44d38651c..6d9edeecce9 100644 --- a/django/conf/locale/pt_BR/formats.py +++ b/django/conf/locale/pt_BR/formats.py @@ -1,6 +1,7 @@ # -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # +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 diff --git a/django/conf/locale/ru/formats.py b/django/conf/locale/ru/formats.py index e8258247517..ec46bff4005 100644 --- a/django/conf/locale/ru/formats.py +++ b/django/conf/locale/ru/formats.py @@ -1,6 +1,7 @@ # -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # +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 @@ -36,5 +37,5 @@ DATETIME_INPUT_FORMATS = ( '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = u'\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 0443efb376f..4b2201f49ae 100644 --- a/django/conf/locale/sk/formats.py +++ b/django/conf/locale/sk/formats.py @@ -1,6 +1,7 @@ # -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # +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 @@ -33,5 +34,5 @@ DATETIME_INPUT_FORMATS = ( '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = u'\xa0' # non-breaking space +THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3 diff --git a/django/conf/locale/sv/formats.py b/django/conf/locale/sv/formats.py index ad7d3b3feea..767dbe8d3ea 100644 --- a/django/conf/locale/sv/formats.py +++ b/django/conf/locale/sv/formats.py @@ -1,6 +1,7 @@ # -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # +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 @@ -36,5 +37,5 @@ DATETIME_INPUT_FORMATS = ( '%m/%d/%y', # '10/25/06' ) DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = u'\xa0' # non-breaking space +THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3 diff --git a/django/conf/locale/uk/formats.py b/django/conf/locale/uk/formats.py index 8b4606fb64e..11293f047ab 100644 --- a/django/conf/locale/uk/formats.py +++ b/django/conf/locale/uk/formats.py @@ -2,6 +2,8 @@ # This file is distributed under the same license as the Django package. # +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 = 'j E Y р.' @@ -19,5 +21,5 @@ SHORT_DATE_FORMAT = 'j M Y' # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = u' ' +THOUSAND_SEPARATOR = ' ' # NUMBER_GROUPING = diff --git a/django/conf/locale/vi/formats.py b/django/conf/locale/vi/formats.py index 27b4efca25a..b491c2d20c9 100644 --- a/django/conf/locale/vi/formats.py +++ b/django/conf/locale/vi/formats.py @@ -1,6 +1,7 @@ # -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # +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 diff --git a/django/contrib/admin/forms.py b/django/contrib/admin/forms.py index e790e2e3b68..398af075b1f 100644 --- a/django/contrib/admin/forms.py +++ b/django/contrib/admin/forms.py @@ -1,9 +1,10 @@ +from __future__ import unicode_literals + from django import forms from django.contrib.auth import authenticate from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.models import User - from django.utils.translation import ugettext_lazy, ugettext as _ ERROR_MESSAGE = ugettext_lazy("Please enter the correct username and password " @@ -25,7 +26,7 @@ class AdminAuthenticationForm(AuthenticationForm): if username and password: self.user_cache = authenticate(username=username, password=password) if self.user_cache is None: - if u'@' in username: + if '@' in username: # Mistakenly entered e-mail address instead of username? Look it up. try: user = User.objects.get(email=username) diff --git a/django/contrib/admin/helpers.py b/django/contrib/admin/helpers.py index 58130574eef..6c648ecb4ad 100644 --- a/django/contrib/admin/helpers.py +++ b/django/contrib/admin/helpers.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django import forms from django.contrib.admin.util import (flatten_fieldsets, lookup_field, display_for_field, label_for_field, help_text_for_field) @@ -69,7 +71,7 @@ class Fieldset(object): description=None, model_admin=None): self.form = form self.name, self.fields = name, fields - self.classes = u' '.join(classes) + self.classes = ' '.join(classes) self.description = description self.model_admin = model_admin self.readonly_fields = readonly_fields @@ -109,7 +111,7 @@ class Fieldline(object): yield AdminField(self.form, field, is_first=(i == 0)) def errors(self): - return mark_safe(u'\n'.join([self.form[f].errors.as_ul() for f in self.fields if f not in self.readonly_fields]).strip('\n')) + return mark_safe('\n'.join([self.form[f].errors.as_ul() for f in self.fields if f not in self.readonly_fields]).strip('\n')) class AdminField(object): def __init__(self, form, field, is_first): @@ -121,14 +123,14 @@ class AdminField(object): classes = [] contents = conditional_escape(force_unicode(self.field.label)) if self.is_checkbox: - classes.append(u'vCheckboxLabel') + classes.append('vCheckboxLabel') else: - contents += u':' + contents += ':' if self.field.field.required: - classes.append(u'required') + classes.append('required') if not self.is_first: - classes.append(u'inline') - attrs = classes and {'class': u' '.join(classes)} or {} + classes.append('inline') + attrs = classes and {'class': ' '.join(classes)} or {} return self.field.label_tag(contents=mark_safe(contents), attrs=attrs) def errors(self): @@ -161,7 +163,7 @@ class AdminReadonlyField(object): if not self.is_first: attrs["class"] = "inline" label = self.field['label'] - contents = capfirst(force_unicode(escape(label))) + u":" + contents = capfirst(force_unicode(escape(label))) + ":" return mark_safe('%(contents)s' % { "attrs": flatatt(attrs), "contents": contents, diff --git a/django/contrib/admin/models.py b/django/contrib/admin/models.py index 0e5b8a79daf..93d8f307c0f 100644 --- a/django/contrib/admin/models.py +++ b/django/contrib/admin/models.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import User @@ -64,5 +66,5 @@ class LogEntry(models.Model): This is relative to the Django admin index page. """ if self.content_type and self.object_id: - return mark_safe(u"%s/%s/%s/" % (self.content_type.app_label, self.content_type.model, quote(self.object_id))) + return mark_safe("%s/%s/%s/" % (self.content_type.app_label, self.content_type.model, quote(self.object_id))) return None diff --git a/django/contrib/admin/templatetags/admin_list.py b/django/contrib/admin/templatetags/admin_list.py index bda8d4b4cdb..30a85ab7f79 100644 --- a/django/contrib/admin/templatetags/admin_list.py +++ b/django/contrib/admin/templatetags/admin_list.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import datetime from django.contrib.admin.util import (lookup_field, display_for_field, @@ -27,11 +29,11 @@ def paginator_number(cl,i): Generates an individual page index link in a paginated list. """ if i == DOT: - return u'... ' + return '... ' elif i == cl.page_num: - return mark_safe(u'%d ' % (i+1)) + return mark_safe('%d ' % (i+1)) else: - return mark_safe(u'%d ' % (escape(cl.get_query_string({PAGE_VAR: i})), (i == cl.paginator.num_pages-1 and ' class="end"' or ''), i+1)) + return mark_safe('%d ' % (escape(cl.get_query_string({PAGE_VAR: i})), (i == cl.paginator.num_pages-1 and ' class="end"' or ''), i+1)) @register.inclusion_tag('admin/pagination.html') def pagination(cl): @@ -163,7 +165,7 @@ def result_headers(cl): def _boolean_icon(field_val): icon_url = static('admin/img/icon-%s.gif' % {True: 'yes', False: 'no', None: 'unknown'}[field_val]) - return mark_safe(u'%s' % (icon_url, field_val)) + return mark_safe('%s' % (icon_url, field_val)) def items_for_result(cl, result, form): """ @@ -179,7 +181,7 @@ def items_for_result(cl, result, form): result_repr = EMPTY_CHANGELIST_VALUE else: if f is None: - if field_name == u'action_checkbox': + if field_name == 'action_checkbox': row_class = ' class="action-checkbox"' allow_tags = getattr(attr, 'allow_tags', False) boolean = getattr(attr, 'boolean', False) @@ -220,7 +222,7 @@ def items_for_result(cl, result, form): attr = pk value = result.serializable_value(attr) result_id = repr(force_unicode(value))[1:] - yield mark_safe(u'<%s%s>%s' % \ + yield mark_safe('<%s%s>%s' % \ (table_tag, row_class, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), conditional_escape(result_repr), table_tag)) else: # By default the fields come from ModelAdmin.list_editable, but if we pull @@ -233,9 +235,9 @@ def items_for_result(cl, result, form): result_repr = mark_safe(force_unicode(bf.errors) + force_unicode(bf)) else: result_repr = conditional_escape(result_repr) - yield mark_safe(u'%s' % (row_class, result_repr)) + yield mark_safe('%s' % (row_class, result_repr)) if form and not form[cl.model._meta.pk.name].is_hidden: - yield mark_safe(u'%s' % force_unicode(form[cl.model._meta.pk.name])) + yield mark_safe('%s' % force_unicode(form[cl.model._meta.pk.name])) class ResultList(list): # Wrapper class used to return items in a list_editable diff --git a/django/contrib/admin/util.py b/django/contrib/admin/util.py index 9611b000501..18b10f3cfa5 100644 --- a/django/contrib/admin/util.py +++ b/django/contrib/admin/util.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import datetime import decimal @@ -122,14 +124,14 @@ def get_deleted_objects(objs, opts, user, admin_site, using): if not user.has_perm(p): perms_needed.add(opts.verbose_name) # Display a link to the admin page. - return mark_safe(u'%s: %s' % + return mark_safe('%s: %s' % (escape(capfirst(opts.verbose_name)), admin_url, escape(obj))) else: # Don't display link to edit, because it either has no # admin or is edited inline. - return u'%s: %s' % (capfirst(opts.verbose_name), + return '%s: %s' % (capfirst(opts.verbose_name), force_unicode(obj)) to_delete = collector.nested(format_callback) diff --git a/django/contrib/admin/widgets.py b/django/contrib/admin/widgets.py index 980863ed840..18897bdeb19 100644 --- a/django/contrib/admin/widgets.py +++ b/django/contrib/admin/widgets.py @@ -1,8 +1,10 @@ """ Form Widget classes specific to the Django admin site. """ +from __future__ import unicode_literals import copy + from django import forms from django.contrib.admin.templatetags.admin_static import static from django.core.urlresolvers import reverse @@ -39,12 +41,12 @@ class FilteredSelectMultiple(forms.SelectMultiple): if self.is_stacked: attrs['class'] += 'stacked' output = [super(FilteredSelectMultiple, self).render(name, value, attrs, choices)] - output.append(u'\n' + output.append('SelectFilter.init("id_%s", "%s", %s, "%s"); });\n' % (name, self.verbose_name.replace('"', '\\"'), int(self.is_stacked), static('admin/'))) - return mark_safe(u''.join(output)) + return mark_safe(''.join(output)) class AdminDateWidget(forms.DateInput): @@ -83,24 +85,24 @@ class AdminSplitDateTime(forms.SplitDateTimeWidget): forms.MultiWidget.__init__(self, widgets, attrs) def format_output(self, rendered_widgets): - return mark_safe(u'

%s %s
%s %s

' % \ + return mark_safe('

%s %s
%s %s

' % \ (_('Date:'), rendered_widgets[0], _('Time:'), rendered_widgets[1])) class AdminRadioFieldRenderer(RadioFieldRenderer): def render(self): """Outputs a
    for this set of radio fields.""" - return mark_safe(u'\n%s\n
' % ( + return mark_safe('\n%s\n' % ( flatatt(self.attrs), - u'\n'.join([u'
  • %s
  • ' % force_unicode(w) for w in self])) + '\n'.join(['
  • %s
  • ' % force_unicode(w) for w in self])) ) class AdminRadioSelect(forms.RadioSelect): renderer = AdminRadioFieldRenderer class AdminFileWidget(forms.ClearableFileInput): - template_with_initial = (u'

    %s

    ' + template_with_initial = ('

    %s

    ' % forms.ClearableFileInput.template_with_initial) - template_with_clear = (u'%s' + template_with_clear = ('%s' % forms.ClearableFileInput.template_with_clear) def url_params_from_lookup_dict(lookups): @@ -113,7 +115,7 @@ def url_params_from_lookup_dict(lookups): items = [] for k, v in lookups.items(): if isinstance(v, (tuple, list)): - v = u','.join([str(x) for x in v]) + v = ','.join([str(x) for x in v]) elif isinstance(v, bool): # See django.db.fields.BooleanField.get_prep_lookup v = ('0', '1')[v] @@ -148,21 +150,21 @@ class ForeignKeyRawIdWidget(forms.TextInput): params = self.url_parameters() if params: - url = u'?' + u'&'.join([u'%s=%s' % (k, v) for k, v in params.items()]) + url = '?' + '&'.join(['%s=%s' % (k, v) for k, v in params.items()]) else: - url = u'' + url = '' if "class" not in attrs: 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(u' ' + extra.append(' ' % (related_url, url, name)) - extra.append(u'%s' + extra.append('%s' % (static('admin/img/selector-search.gif'), _('Lookup'))) output = [super(ForeignKeyRawIdWidget, self).render(name, value, attrs)] + extra if value: output.append(self.label_for_value(value)) - return mark_safe(u''.join(output)) + return mark_safe(''.join(output)) def base_url_parameters(self): return url_params_from_lookup_dict(self.rel.limit_choices_to) @@ -261,11 +263,11 @@ class RelatedFieldWidgetWrapper(forms.Widget): related_url = reverse('admin:%s_%s_add' % info, current_app=self.admin_site.name) # TODO: "add_id_" is hard-coded here. This should instead use the # correct API to determine the ID dynamically. - output.append(u' ' + output.append(' ' % (related_url, name)) - output.append(u'%s' + output.append('%s' % (static('admin/img/icon_addlink.gif'), _('Add Another'))) - return mark_safe(u''.join(output)) + return mark_safe(''.join(output)) def build_attrs(self, extra_attrs=None, **kwargs): "Helper function for building an attribute dictionary." diff --git a/django/contrib/admindocs/tests/__init__.py b/django/contrib/admindocs/tests/__init__.py index 49a925a4530..306475beb1f 100644 --- a/django/contrib/admindocs/tests/__init__.py +++ b/django/contrib/admindocs/tests/__init__.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from django.contrib.admindocs import views from django.db.models import fields as builtin_fields @@ -20,17 +20,17 @@ class TestFieldType(unittest.TestCase): def test_builtin_fields(self): self.assertEqual( views.get_readable_field_data_type(builtin_fields.BooleanField()), - _(u'Boolean (Either True or False)') + _('Boolean (Either True or False)') ) def test_custom_fields(self): self.assertEqual( views.get_readable_field_data_type(fields.CustomField()), - _(u'A custom field type') + _('A custom field type') ) self.assertEqual( views.get_readable_field_data_type(fields.DescriptionLackingField()), - _(u'Field of type: %(field_type)s') % { + _('Field of type: %(field_type)s') % { 'field_type': 'DescriptionLackingField' } ) diff --git a/django/contrib/auth/backends.py b/django/contrib/auth/backends.py index 04fbef4788e..9088e2fbf63 100644 --- a/django/contrib/auth/backends.py +++ b/django/contrib/auth/backends.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.contrib.auth.models import User, Permission @@ -36,7 +38,7 @@ class ModelBackend(object): if user_obj.is_anonymous() or obj is not None: return set() if not hasattr(user_obj, '_perm_cache'): - user_obj._perm_cache = set([u"%s.%s" % (p.content_type.app_label, p.codename) for p in user_obj.user_permissions.select_related()]) + user_obj._perm_cache = set(["%s.%s" % (p.content_type.app_label, p.codename) for p in user_obj.user_permissions.select_related()]) user_obj._perm_cache.update(self.get_group_permissions(user_obj)) return user_obj._perm_cache diff --git a/django/contrib/auth/hashers.py b/django/contrib/auth/hashers.py index 0897de8d84a..96ec40ba60f 100644 --- a/django/contrib/auth/hashers.py +++ b/django/contrib/auth/hashers.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import hashlib from django.dispatch import receiver diff --git a/django/contrib/auth/management/__init__.py b/django/contrib/auth/management/__init__.py index 66f54f18a85..100acb6c5be 100644 --- a/django/contrib/auth/management/__init__.py +++ b/django/contrib/auth/management/__init__.py @@ -1,6 +1,8 @@ """ Creates permissions for all installed apps that need permissions. """ +from __future__ import unicode_literals + import getpass import locale import unicodedata @@ -10,14 +12,14 @@ from django.contrib.auth.models import User def _get_permission_codename(action, opts): - return u'%s_%s' % (action, opts.object_name.lower()) + return '%s_%s' % (action, opts.object_name.lower()) def _get_all_permissions(opts): "Returns (codename, name) for all permissions in the given opts." perms = [] for action in ('add', 'change', 'delete'): - perms.append((_get_permission_codename(action, opts), u'Can %s %s' % (action, opts.verbose_name_raw))) + perms.append((_get_permission_codename(action, opts), 'Can %s %s' % (action, opts.verbose_name_raw))) return perms + list(opts.permissions) @@ -88,7 +90,7 @@ def get_system_username(): # if there is no corresponding entry in the /etc/passwd file # (a very restricted chroot environment, for example). # UnicodeDecodeError - preventive treatment for non-latin Windows. - return u'' + return '' def get_default_username(check_db=True): diff --git a/django/contrib/auth/models.py b/django/contrib/auth/models.py index 090b6d40c88..244721065da 100644 --- a/django/contrib/auth/models.py +++ b/django/contrib/auth/models.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import urllib from django.core.exceptions import ImproperlyConfigured @@ -76,7 +78,7 @@ class Permission(models.Model): 'codename') def __unicode__(self): - return u"%s | %s | %s" % ( + return "%s | %s | %s" % ( unicode(self.content_type.app_label), unicode(self.content_type), unicode(self.name)) @@ -285,7 +287,7 @@ class User(models.Model): """ Returns the first_name plus the last_name, with a space in between. """ - full_name = u'%s %s' % (self.first_name, self.last_name) + full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def set_password(self, raw_password): diff --git a/django/contrib/auth/tests/auth_backends.py b/django/contrib/auth/tests/auth_backends.py index 7b38acfa50e..9a4d8f9b3a7 100644 --- a/django/contrib/auth/tests/auth_backends.py +++ b/django/contrib/auth/tests/auth_backends.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.conf import settings from django.contrib.auth.models import User, Group, Permission, AnonymousUser from django.contrib.contenttypes.models import ContentType @@ -51,7 +53,7 @@ class BackendTest(TestCase): # reloading user to purge the _perm_cache user = User.objects.get(username='test') - self.assertEqual(user.get_all_permissions() == set([u'auth.test']), True) + self.assertEqual(user.get_all_permissions() == set(['auth.test']), True) self.assertEqual(user.get_group_permissions(), set([])) self.assertEqual(user.has_module_perms('Group'), False) self.assertEqual(user.has_module_perms('auth'), True) @@ -62,7 +64,7 @@ class BackendTest(TestCase): user.user_permissions.add(perm) user.save() user = User.objects.get(username='test') - self.assertEqual(user.get_all_permissions(), set([u'auth.test2', u'auth.test', u'auth.test3'])) + self.assertEqual(user.get_all_permissions(), set(['auth.test2', 'auth.test', 'auth.test3'])) self.assertEqual(user.has_perm('test'), False) self.assertEqual(user.has_perm('auth.test'), True) self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), True) @@ -72,9 +74,9 @@ class BackendTest(TestCase): group.save() user.groups.add(group) user = User.objects.get(username='test') - exp = set([u'auth.test2', u'auth.test', u'auth.test3', u'auth.test_group']) + exp = set(['auth.test2', 'auth.test', 'auth.test3', 'auth.test_group']) self.assertEqual(user.get_all_permissions(), exp) - self.assertEqual(user.get_group_permissions(), set([u'auth.test_group'])) + self.assertEqual(user.get_group_permissions(), set(['auth.test_group'])) self.assertEqual(user.has_perms(['auth.test3', 'auth.test_group']), True) user = AnonymousUser() diff --git a/django/contrib/auth/tests/forms.py b/django/contrib/auth/tests/forms.py index fd2b526f17e..2ab895804f6 100644 --- a/django/contrib/auth/tests/forms.py +++ b/django/contrib/auth/tests/forms.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import os from django.contrib.auth.models import User from django.contrib.auth.forms import (UserCreationForm, AuthenticationForm, @@ -299,7 +301,7 @@ class PasswordResetFormTest(TestCase): # potential case where contrib.sites is not installed. Refs #16412. form.save(domain_override='example.com') self.assertEqual(len(mail.outbox), 1) - self.assertEqual(mail.outbox[0].subject, u'Custom password reset on example.com') + self.assertEqual(mail.outbox[0].subject, 'Custom password reset on example.com') def test_bug_5605(self): # bug #5605, preserve the case of the user name (before the @ in the @@ -328,4 +330,4 @@ class PasswordResetFormTest(TestCase): form = PasswordResetForm(data) self.assertFalse(form.is_valid()) self.assertEqual(form["email"].errors, - [_(u"The user account associated with this e-mail address cannot reset the password.")]) + [_("The user account associated with this e-mail address cannot reset the password.")]) diff --git a/django/contrib/auth/tests/hashers.py b/django/contrib/auth/tests/hashers.py index 15fc1d1da72..673263b5669 100644 --- a/django/contrib/auth/tests/hashers.py +++ b/django/contrib/auth/tests/hashers.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.conf.global_settings import PASSWORD_HASHERS as default_hashers from django.contrib.auth.hashers import (is_password_usable, check_password, make_password, PBKDF2PasswordHasher, load_hashers, @@ -26,7 +28,7 @@ class TestUtilsHashPass(unittest.TestCase): encoded = make_password('letmein') self.assertTrue(encoded.startswith('pbkdf2_sha256$')) self.assertTrue(is_password_usable(encoded)) - self.assertTrue(check_password(u'letmein', encoded)) + self.assertTrue(check_password('letmein', encoded)) self.assertFalse(check_password('letmeinz', encoded)) def test_pkbdf2(self): @@ -34,7 +36,7 @@ class TestUtilsHashPass(unittest.TestCase): self.assertEqual(encoded, 'pbkdf2_sha256$10000$seasalt$FQCNpiZpTb0zub+HBsH6TOwyRxJ19FwvjbweatNmK/Y=') self.assertTrue(is_password_usable(encoded)) - self.assertTrue(check_password(u'letmein', encoded)) + self.assertTrue(check_password('letmein', encoded)) self.assertFalse(check_password('letmeinz', encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "pbkdf2_sha256") @@ -43,7 +45,7 @@ class TestUtilsHashPass(unittest.TestCase): self.assertEqual(encoded, 'sha1$seasalt$fec3530984afba6bade3347b7140d1a7da7da8c7') self.assertTrue(is_password_usable(encoded)) - self.assertTrue(check_password(u'letmein', encoded)) + self.assertTrue(check_password('letmein', encoded)) self.assertFalse(check_password('letmeinz', encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "sha1") @@ -52,7 +54,7 @@ class TestUtilsHashPass(unittest.TestCase): self.assertEqual(encoded, 'md5$seasalt$f5531bef9f3687d0ccf0f617f0e25573') self.assertTrue(is_password_usable(encoded)) - self.assertTrue(check_password(u'letmein', encoded)) + self.assertTrue(check_password('letmein', encoded)) self.assertFalse(check_password('letmeinz', encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "md5") @@ -60,7 +62,7 @@ class TestUtilsHashPass(unittest.TestCase): encoded = make_password('letmein', 'seasalt', 'unsalted_md5') self.assertEqual(encoded, '0d107d09f5bbe40cade3de5c71e9e9b7') self.assertTrue(is_password_usable(encoded)) - self.assertTrue(check_password(u'letmein', encoded)) + self.assertTrue(check_password('letmein', encoded)) self.assertFalse(check_password('letmeinz', encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "unsalted_md5") @@ -69,7 +71,7 @@ class TestUtilsHashPass(unittest.TestCase): encoded = make_password('letmein', 'ab', 'crypt') self.assertEqual(encoded, 'crypt$$abN/qM.L/H8EQ') self.assertTrue(is_password_usable(encoded)) - self.assertTrue(check_password(u'letmein', encoded)) + self.assertTrue(check_password('letmein', encoded)) self.assertFalse(check_password('letmeinz', encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "crypt") @@ -78,7 +80,7 @@ class TestUtilsHashPass(unittest.TestCase): encoded = make_password('letmein', hasher='bcrypt') self.assertTrue(is_password_usable(encoded)) self.assertTrue(encoded.startswith('bcrypt$')) - self.assertTrue(check_password(u'letmein', encoded)) + self.assertTrue(check_password('letmein', encoded)) self.assertFalse(check_password('letmeinz', encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "bcrypt") @@ -88,7 +90,7 @@ class TestUtilsHashPass(unittest.TestCase): self.assertFalse(check_password(None, encoded)) self.assertFalse(check_password(UNUSABLE_PASSWORD, encoded)) self.assertFalse(check_password('', encoded)) - self.assertFalse(check_password(u'letmein', encoded)) + self.assertFalse(check_password('letmein', encoded)) self.assertFalse(check_password('letmeinz', encoded)) self.assertRaises(ValueError, identify_hasher, encoded) diff --git a/django/contrib/auth/tests/management.py b/django/contrib/auth/tests/management.py index 81ab0aa0529..8d1f7c7965a 100644 --- a/django/contrib/auth/tests/management.py +++ b/django/contrib/auth/tests/management.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from StringIO import StringIO from django.contrib.auth import models, management @@ -15,19 +17,19 @@ class GetDefaultUsernameTestCase(TestCase): management.get_system_username = self._getpass_getuser def test_simple(self): - management.get_system_username = lambda: u'joe' + management.get_system_username = lambda: 'joe' self.assertEqual(management.get_default_username(), 'joe') def test_existing(self): models.User.objects.create(username='joe') - management.get_system_username = lambda: u'joe' + management.get_system_username = lambda: 'joe' self.assertEqual(management.get_default_username(), '') self.assertEqual( management.get_default_username(check_db=False), 'joe') def test_i18n(self): # 'Julia' with accented 'u': - management.get_system_username = lambda: u'J\xfalia' + management.get_system_username = lambda: 'J\xfalia' self.assertEqual(management.get_default_username(), 'julia') diff --git a/django/contrib/comments/admin.py b/django/contrib/comments/admin.py index 4cb90663a0e..0024a1d1b5d 100644 --- a/django/contrib/comments/admin.py +++ b/django/contrib/comments/admin.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.contrib import admin from django.contrib.comments.models import Comment from django.utils.translation import ugettext_lazy as _, ungettext @@ -62,8 +64,8 @@ class CommentsAdmin(admin.ModelAdmin): action(request, comment) n_comments += 1 - msg = ungettext(u'1 comment was successfully %(action)s.', - u'%(count)s comments were successfully %(action)s.', + msg = ungettext('1 comment was successfully %(action)s.', + '%(count)s comments were successfully %(action)s.', n_comments) self.message_user(request, msg % {'count': n_comments, 'action': done_message(n_comments)}) diff --git a/django/contrib/contenttypes/generic.py b/django/contrib/contenttypes/generic.py index a6732d7a2e3..d5062cabf3a 100644 --- a/django/contrib/contenttypes/generic.py +++ b/django/contrib/contenttypes/generic.py @@ -1,6 +1,7 @@ """ Classes allowing "generic" relations through ContentType and object-id fields. """ +from __future__ import unicode_literals from collections import defaultdict from functools import partial @@ -131,7 +132,7 @@ class GenericForeignKey(object): def __set__(self, instance, value): if instance is None: - raise AttributeError(u"%s must be accessed via instance" % self.related.opts.object_name) + raise AttributeError("%s must be accessed via instance" % self.related.opts.object_name) ct = None fk = None diff --git a/django/contrib/contenttypes/tests.py b/django/contrib/contenttypes/tests.py index 0057dd535d3..2eaa4c182ec 100644 --- a/django/contrib/contenttypes/tests.py +++ b/django/contrib/contenttypes/tests.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import urllib from django.db import models @@ -181,4 +183,4 @@ class ContentTypesTests(TestCase): app_label = 'contenttypes', model = 'OldModel', ) - self.assertEqual(unicode(ct), u'Old model') + self.assertEqual(unicode(ct), 'Old model') diff --git a/django/contrib/contenttypes/views.py b/django/contrib/contenttypes/views.py index 8d8e1c7a3e3..5c22cb6672e 100644 --- a/django/contrib/contenttypes/views.py +++ b/django/contrib/contenttypes/views.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django import http from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site, get_current_site @@ -12,11 +14,11 @@ def shortcut(request, content_type_id, object_id): try: content_type = ContentType.objects.get(pk=content_type_id) if not content_type.model_class(): - raise http.Http404(_(u"Content type %(ct_id)s object has no associated model") % + raise http.Http404(_("Content type %(ct_id)s object has no associated model") % {'ct_id': content_type_id}) obj = content_type.get_object_for_this_type(pk=object_id) except (ObjectDoesNotExist, ValueError): - raise http.Http404(_(u"Content type %(ct_id)s object %(obj_id)s doesn't exist") % + raise http.Http404(_("Content type %(ct_id)s object %(obj_id)s doesn't exist") % {'ct_id': content_type_id, 'obj_id': object_id}) try: diff --git a/django/contrib/databrowse/datastructures.py b/django/contrib/databrowse/datastructures.py index 9a4ba17e19f..6a78b3688b9 100644 --- a/django/contrib/databrowse/datastructures.py +++ b/django/contrib/databrowse/datastructures.py @@ -2,6 +2,7 @@ These classes are light wrappers around Django's database API that provide convenience functionality and permalink functions for the databrowse app. """ +from __future__ import unicode_literals from django.db import models from django.utils import formats @@ -61,7 +62,7 @@ class EasyField(object): self.model, self.field = easy_model, field def __repr__(self): - return smart_str(u'' % (self.model.model._meta.object_name, self.field.name)) + return smart_str('' % (self.model.model._meta.object_name, self.field.name)) def choices(self): for value, label in self.field.choices: @@ -79,7 +80,7 @@ class EasyChoice(object): self.value, self.label = value, label def __repr__(self): - return smart_str(u'' % (self.model.model._meta.object_name, self.field.name)) + return smart_str('' % (self.model.model._meta.object_name, self.field.name)) def url(self): return mark_safe('%s%s/%s/%s/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name, self.field.field.name, iri_to_uri(self.value))) @@ -89,12 +90,12 @@ class EasyInstance(object): self.model, self.instance = easy_model, instance def __repr__(self): - return smart_str(u'' % (self.model.model._meta.object_name, self.instance._get_pk_val())) + return smart_str('' % (self.model.model._meta.object_name, self.instance._get_pk_val())) def __unicode__(self): val = smart_unicode(self.instance) if len(val) > DISPLAY_SIZE: - return val[:DISPLAY_SIZE] + u'...' + return val[:DISPLAY_SIZE] + '...' return val def __str__(self): @@ -136,7 +137,7 @@ class EasyInstanceField(object): self.raw_value = getattr(instance.instance, field.name) def __repr__(self): - return smart_str(u'' % (self.model.model._meta.object_name, self.field.name)) + return smart_str('' % (self.model.model._meta.object_name, self.field.name)) def values(self): """ diff --git a/django/contrib/databrowse/plugins/calendars.py b/django/contrib/databrowse/plugins/calendars.py index 3416f88ca7f..587c752a949 100644 --- a/django/contrib/databrowse/plugins/calendars.py +++ b/django/contrib/databrowse/plugins/calendars.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django import http from django.db import models from django.contrib.databrowse.datastructures import EasyModel @@ -61,14 +63,14 @@ class CalendarPlugin(DatabrowsePlugin): def model_index_html(self, request, model, site): fields = self.field_dict(model) if not fields: - return u'' - return mark_safe(u'

    View calendar by: %s

    ' % \ - u', '.join(['%s' % (f.name, force_unicode(capfirst(f.verbose_name))) for f in fields.values()])) + return '' + return mark_safe('

    View calendar by: %s

    ' % \ + ', '.join(['%s' % (f.name, force_unicode(capfirst(f.verbose_name))) for f in fields.values()])) def urls(self, plugin_name, easy_instance_field): if isinstance(easy_instance_field.field, models.DateField): d = easy_instance_field.raw_value - return [mark_safe(u'%s%s/%s/%s/%s/%s/' % ( + return [mark_safe('%s%s/%s/%s/%s/%s/' % ( easy_instance_field.model.url(), plugin_name, easy_instance_field.field.name, str(d.year), diff --git a/django/contrib/databrowse/plugins/fieldchoices.py b/django/contrib/databrowse/plugins/fieldchoices.py index b3210681e9e..5a13252ab36 100644 --- a/django/contrib/databrowse/plugins/fieldchoices.py +++ b/django/contrib/databrowse/plugins/fieldchoices.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django import http from django.db import models from django.contrib.databrowse.datastructures import EasyModel @@ -29,14 +31,14 @@ class FieldChoicePlugin(DatabrowsePlugin): def model_index_html(self, request, model, site): fields = self.field_dict(model) if not fields: - return u'' - return mark_safe(u'

    View by: %s

    ' % \ - u', '.join(['%s' % (f.name, force_unicode(capfirst(f.verbose_name))) for f in fields.values()])) + return '' + return mark_safe('

    View by: %s

    ' % \ + ', '.join(['%s' % (f.name, force_unicode(capfirst(f.verbose_name))) for f in fields.values()])) def urls(self, plugin_name, easy_instance_field): if easy_instance_field.field in self.field_dict(easy_instance_field.model.model).values(): field_value = smart_str(easy_instance_field.raw_value) - return [mark_safe(u'%s%s/%s/%s/' % ( + return [mark_safe('%s%s/%s/%s/' % ( easy_instance_field.model.url(), plugin_name, easy_instance_field.field.name, urllib.quote(field_value, safe='')))] diff --git a/django/contrib/databrowse/sites.py b/django/contrib/databrowse/sites.py index d90bb562b23..b5cb2639d63 100644 --- a/django/contrib/databrowse/sites.py +++ b/django/contrib/databrowse/sites.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django import http from django.db import models from django.contrib.databrowse.datastructures import EasyModel @@ -61,7 +63,7 @@ class ModelDatabrowse(object): def main_view(self, request): easy_model = EasyModel(self.site, self.model) - html_snippets = mark_safe(u'\n'.join([p.model_index_html(request, self.model, self.site) for p in self.plugins.values()])) + html_snippets = mark_safe('\n'.join([p.model_index_html(request, self.model, self.site) for p in self.plugins.values()])) return render_to_response('databrowse/model_detail.html', { 'model': easy_model, 'root_url': self.site.root_url, diff --git a/django/contrib/flatpages/models.py b/django/contrib/flatpages/models.py index 85873ac7b17..42ec155f343 100644 --- a/django/contrib/flatpages/models.py +++ b/django/contrib/flatpages/models.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.db import models from django.contrib.sites.models import Site from django.utils.translation import ugettext_lazy as _ @@ -20,7 +22,7 @@ class FlatPage(models.Model): ordering = ('url',) def __unicode__(self): - return u"%s -- %s" % (self.url, self.title) + return "%s -- %s" % (self.url, self.title) def get_absolute_url(self): return self.url diff --git a/django/contrib/flatpages/tests/forms.py b/django/contrib/flatpages/tests/forms.py index 0e54176aa25..3bdfa15dfea 100644 --- a/django/contrib/flatpages/tests/forms.py +++ b/django/contrib/flatpages/tests/forms.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.conf import settings from django.contrib.flatpages.forms import FlatpageForm from django.contrib.flatpages.models import FlatPage @@ -60,7 +62,7 @@ class FlatpageAdminFormTests(TestCase): self.assertEqual( f.errors, - {'__all__': [u'Flatpage with url /myflatpage1/ already exists for site example.com']}) + {'__all__': ['Flatpage with url /myflatpage1/ already exists for site example.com']}) def test_flatpage_admin_form_edit(self): """ @@ -92,5 +94,5 @@ class FlatpageAdminFormTests(TestCase): self.assertEqual( f.errors, - {'sites': [translation.ugettext(u'This field is required.')]}) + {'sites': [translation.ugettext('This field is required.')]}) diff --git a/django/contrib/formtools/tests/__init__.py b/django/contrib/formtools/tests/__init__.py index b5d905071f6..3bccb550340 100644 --- a/django/contrib/formtools/tests/__init__.py +++ b/django/contrib/formtools/tests/__init__.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import os import re import warnings @@ -41,7 +43,7 @@ class PreviewTests(TestCase): self.preview = preview.FormPreview(TestForm) input_template = '' self.input = input_template % (self.preview.unused_name('stage'), "%d") - self.test_data = {'field1':u'foo', 'field1_':u'asdf'} + self.test_data = {'field1': 'foo', 'field1_': 'asdf'} def test_unused_name(self): """ @@ -117,7 +119,7 @@ class PreviewTests(TestCase): """ self.test_data.update({'stage':2}) hash = self.preview.security_hash(None, TestForm(self.test_data)) - self.test_data.update({'hash':hash, 'bool1':u'False'}) + self.test_data.update({'hash': hash, 'bool1': 'False'}) with warnings.catch_warnings(record=True): response = self.client.post('/preview/', self.test_data) self.assertEqual(response.content, success_string) @@ -163,8 +165,8 @@ class FormHmacTests(unittest.TestCase): leading/trailing whitespace so as to be friendly to broken browsers that submit it (usually in textareas). """ - f1 = HashTestForm({'name': u'joe', 'bio': u'Nothing notable.'}) - f2 = HashTestForm({'name': u' joe', 'bio': u'Nothing notable. '}) + f1 = HashTestForm({'name': 'joe', 'bio': 'Nothing notable.'}) + f2 = HashTestForm({'name': ' joe', 'bio': 'Nothing notable. '}) hash1 = utils.form_hmac(f1) hash2 = utils.form_hmac(f2) self.assertEqual(hash1, hash2) @@ -266,10 +268,10 @@ class WizardTests(TestCase): Form should advance if the hash is present and good, as calculated using current method. """ - data = {"0-field": u"test", - "1-field": u"test2", - "hash_0": u"cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca", - "wizard_step": u"1"} + data = {"0-field": "test", + "1-field": "test2", + "hash_0": "cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca", + "wizard_step": "1"} response = self.client.post('/wizard1/', data) self.assertEqual(2, response.context['step0']) @@ -291,18 +293,18 @@ class WizardTests(TestCase): reached[0] = True wizard = WizardWithProcessStep([WizardPageOneForm]) - data = {"0-field": u"test", - "1-field": u"test2", - "hash_0": u"cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca", - "wizard_step": u"1"} + data = {"0-field": "test", + "1-field": "test2", + "hash_0": "cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca", + "wizard_step": "1"} wizard(DummyRequest(POST=data)) self.assertTrue(reached[0]) - data = {"0-field": u"test", - "1-field": u"test2", + data = {"0-field": "test", + "1-field": "test2", "hash_0": "cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca", - "hash_1": u"1e6f6315da42e62f33a30640ec7e007ad3fbf1a1", - "wizard_step": u"2"} + "hash_1": "1e6f6315da42e62f33a30640ec7e007ad3fbf1a1", + "wizard_step": "2"} self.assertRaises(http.Http404, wizard, DummyRequest(POST=data)) def test_14498(self): @@ -321,10 +323,10 @@ class WizardTests(TestCase): wizard = WizardWithProcessStep([WizardPageOneForm, WizardPageTwoForm, WizardPageThreeForm]) - data = {"0-field": u"test", - "1-field": u"test2", - "hash_0": u"cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca", - "wizard_step": u"1"} + data = {"0-field": "test", + "1-field": "test2", + "hash_0": "cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca", + "wizard_step": "1"} wizard(DummyRequest(POST=data)) self.assertTrue(reached[0]) @@ -345,10 +347,10 @@ class WizardTests(TestCase): wizard = Wizard([WizardPageOneForm, WizardPageTwoForm]) - data = {"0-field": u"test", - "1-field": u"test2", - "hash_0": u"cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca", - "wizard_step": u"1"} + data = {"0-field": "test", + "1-field": "test2", + "hash_0": "cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca", + "wizard_step": "1"} wizard(DummyRequest(POST=data)) self.assertTrue(reached[0]) @@ -371,10 +373,10 @@ class WizardTests(TestCase): wizard = WizardWithProcessStep([WizardPageOneForm, WizardPageTwoForm, WizardPageThreeForm]) - data = {"0-field": u"test", - "1-field": u"test2", - "hash_0": u"cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca", - "wizard_step": u"1"} + data = {"0-field": "test", + "1-field": "test2", + "hash_0": "cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca", + "wizard_step": "1"} wizard(DummyRequest(POST=data)) self.assertTrue(reached[0]) diff --git a/django/contrib/formtools/tests/wizard/forms.py b/django/contrib/formtools/tests/wizard/forms.py index 8afbd307214..51cfaa661b6 100644 --- a/django/contrib/formtools/tests/wizard/forms.py +++ b/django/contrib/formtools/tests/wizard/forms.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django import forms, http from django.conf import settings from django.test import TestCase @@ -64,22 +66,22 @@ class TestWizard(WizardView): class FormTests(TestCase): def test_form_init(self): testform = TestWizard.get_initkwargs([Step1, Step2]) - self.assertEqual(testform['form_list'], {u'0': Step1, u'1': Step2}) + self.assertEqual(testform['form_list'], {'0': Step1, '1': Step2}) testform = TestWizard.get_initkwargs([('start', Step1), ('step2', Step2)]) self.assertEqual( - testform['form_list'], {u'start': Step1, u'step2': Step2}) + testform['form_list'], {'start': Step1, 'step2': Step2}) testform = TestWizard.get_initkwargs([Step1, Step2, ('finish', Step3)]) self.assertEqual( - testform['form_list'], {u'0': Step1, u'1': Step2, u'finish': Step3}) + testform['form_list'], {'0': Step1, '1': Step2, 'finish': Step3}) def test_first_step(self): request = get_request() testform = TestWizard.as_view([Step1, Step2]) response, instance = testform(request) - self.assertEqual(instance.steps.current, u'0') + self.assertEqual(instance.steps.current, '0') testform = TestWizard.as_view([('start', Step1), ('step2', Step2)]) response, instance = testform(request) diff --git a/django/contrib/formtools/tests/wizard/namedwizardtests/tests.py b/django/contrib/formtools/tests/wizard/namedwizardtests/tests.py index 37913fa078e..a860edd9e98 100644 --- a/django/contrib/formtools/tests/wizard/namedwizardtests/tests.py +++ b/django/contrib/formtools/tests/wizard/namedwizardtests/tests.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.core.urlresolvers import reverse from django.http import QueryDict from django.test import TestCase @@ -51,8 +53,8 @@ class NamedWizardTests(object): self.assertEqual(response.status_code, 200) self.assertEqual(response.context['wizard']['steps'].current, 'form1') self.assertEqual(response.context['wizard']['form'].errors, - {'name': [u'This field is required.'], - 'user': [u'This field is required.']}) + {'name': ['This field is required.'], + 'user': ['This field is required.']}) def test_form_post_success(self): response = self.client.post( @@ -150,10 +152,10 @@ class NamedWizardTests(object): self.assertEqual(all_data[1]['file1'].read(), open(__file__, 'rb').read()) del all_data[1]['file1'] self.assertEqual(all_data, [ - {'name': u'Pony', 'thirsty': True, 'user': self.testuser}, - {'address1': u'123 Main St', 'address2': u'Djangoland'}, - {'random_crap': u'blah blah'}, - [{'random_crap': u'blah blah'}, {'random_crap': u'blah blah'}]]) + {'name': 'Pony', 'thirsty': True, 'user': self.testuser}, + {'address1': '123 Main St', 'address2': 'Djangoland'}, + {'random_crap': 'blah blah'}, + [{'random_crap': 'blah blah'}, {'random_crap': 'blah blah'}]]) def test_cleaned_data(self): response = self.client.get( @@ -203,11 +205,11 @@ class NamedWizardTests(object): del all_data['file1'] self.assertEqual( all_data, - {'name': u'Pony', 'thirsty': True, 'user': self.testuser, - 'address1': u'123 Main St', 'address2': u'Djangoland', - 'random_crap': u'blah blah', 'formset-form4': [ - {'random_crap': u'blah blah'}, - {'random_crap': u'blah blah'} + {'name': 'Pony', 'thirsty': True, 'user': self.testuser, + 'address1': '123 Main St', 'address2': 'Djangoland', + 'random_crap': 'blah blah', 'formset-form4': [ + {'random_crap': 'blah blah'}, + {'random_crap': 'blah blah'} ]}) def test_manipulated_data(self): diff --git a/django/contrib/formtools/tests/wizard/wizardtests/tests.py b/django/contrib/formtools/tests/wizard/wizardtests/tests.py index a9a81ba70fd..a35664b3225 100644 --- a/django/contrib/formtools/tests/wizard/wizardtests/tests.py +++ b/django/contrib/formtools/tests/wizard/wizardtests/tests.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import os from django import forms @@ -33,8 +35,8 @@ class WizardTests(object): self.assertEqual(response.status_code, 200) self.assertEqual(response.context['wizard']['steps'].current, 'form1') self.assertEqual(response.context['wizard']['form'].errors, - {'name': [u'This field is required.'], - 'user': [u'This field is required.']}) + {'name': ['This field is required.'], + 'user': ['This field is required.']}) def test_form_post_success(self): response = self.client.post(self.wizard_url, self.wizard_step_data[0]) @@ -96,11 +98,11 @@ class WizardTests(object): self.assertEqual(all_data[1]['file1'].read(), open(__file__, 'rb').read()) del all_data[1]['file1'] self.assertEqual(all_data, [ - {'name': u'Pony', 'thirsty': True, 'user': self.testuser}, - {'address1': u'123 Main St', 'address2': u'Djangoland'}, - {'random_crap': u'blah blah'}, - [{'random_crap': u'blah blah'}, - {'random_crap': u'blah blah'}]]) + {'name': 'Pony', 'thirsty': True, 'user': self.testuser}, + {'address1': '123 Main St', 'address2': 'Djangoland'}, + {'random_crap': 'blah blah'}, + [{'random_crap': 'blah blah'}, + {'random_crap': 'blah blah'}]]) def test_cleaned_data(self): response = self.client.get(self.wizard_url) @@ -124,11 +126,11 @@ class WizardTests(object): self.assertEqual(all_data['file1'].read(), open(__file__, 'rb').read()) del all_data['file1'] self.assertEqual(all_data, { - 'name': u'Pony', 'thirsty': True, 'user': self.testuser, - 'address1': u'123 Main St', 'address2': u'Djangoland', - 'random_crap': u'blah blah', 'formset-form4': [ - {'random_crap': u'blah blah'}, - {'random_crap': u'blah blah'}]}) + 'name': 'Pony', 'thirsty': True, 'user': self.testuser, + 'address1': '123 Main St', 'address2': 'Djangoland', + 'random_crap': 'blah blah', 'formset-form4': [ + {'random_crap': 'blah blah'}, + {'random_crap': 'blah blah'}]}) def test_manipulated_data(self): response = self.client.get(self.wizard_url) diff --git a/django/contrib/gis/feeds.py b/django/contrib/gis/feeds.py index c14fb858a5e..d7c52bf0193 100644 --- a/django/contrib/gis/feeds.py +++ b/django/contrib/gis/feeds.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.contrib.syndication.views import Feed as BaseFeed from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed @@ -13,7 +15,7 @@ class GeoFeedMixin(object): a single white space. Given a tuple of coordinates, this will return a unicode GeoRSS representation. """ - return u' '.join([u'%f %f' % (coord[1], coord[0]) for coord in coords]) + return ' '.join(['%f %f' % (coord[1], coord[0]) for coord in coords]) def add_georss_point(self, handler, coords, w3c_geo=False): """ @@ -23,10 +25,10 @@ class GeoFeedMixin(object): """ if w3c_geo: lon, lat = coords[:2] - handler.addQuickElement(u'geo:lat', u'%f' % lat) - handler.addQuickElement(u'geo:lon', u'%f' % lon) + handler.addQuickElement('geo:lat', '%f' % lat) + handler.addQuickElement('geo:lon', '%f' % lon) else: - handler.addQuickElement(u'georss:point', self.georss_coords((coords,))) + handler.addQuickElement('georss:point', self.georss_coords((coords,))) def add_georss_element(self, handler, item, w3c_geo=False): """ @@ -57,7 +59,7 @@ class GeoFeedMixin(object): # If a GeoRSS box was given via tuple. if not box_coords is None: if w3c_geo: raise ValueError('Cannot use simple GeoRSS box in W3C Geo feeds.') - handler.addQuickElement(u'georss:box', self.georss_coords(box_coords)) + handler.addQuickElement('georss:box', self.georss_coords(box_coords)) else: # Getting the lower-case geometry type. gtype = str(geom.geom_type).lower() @@ -68,10 +70,10 @@ class GeoFeedMixin(object): # For formatting consistent w/the GeoRSS simple standard: # http://georss.org/1.0#simple if gtype in ('linestring', 'linearring'): - handler.addQuickElement(u'georss:line', self.georss_coords(geom.coords)) + handler.addQuickElement('georss:line', self.georss_coords(geom.coords)) elif gtype in ('polygon',): # Only support the exterior ring. - handler.addQuickElement(u'georss:polygon', self.georss_coords(geom[0].coords)) + handler.addQuickElement('georss:polygon', self.georss_coords(geom[0].coords)) else: raise ValueError('Geometry type "%s" not supported.' % geom.geom_type) @@ -79,7 +81,7 @@ class GeoFeedMixin(object): class GeoRSSFeed(Rss201rev2Feed, GeoFeedMixin): def rss_attributes(self): attrs = super(GeoRSSFeed, self).rss_attributes() - attrs[u'xmlns:georss'] = u'http://www.georss.org/georss' + attrs['xmlns:georss'] = 'http://www.georss.org/georss' return attrs def add_item_elements(self, handler, item): @@ -93,7 +95,7 @@ class GeoRSSFeed(Rss201rev2Feed, GeoFeedMixin): class GeoAtom1Feed(Atom1Feed, GeoFeedMixin): def root_attributes(self): attrs = super(GeoAtom1Feed, self).root_attributes() - attrs[u'xmlns:georss'] = u'http://www.georss.org/georss' + attrs['xmlns:georss'] = 'http://www.georss.org/georss' return attrs def add_item_elements(self, handler, item): @@ -107,7 +109,7 @@ class GeoAtom1Feed(Atom1Feed, GeoFeedMixin): class W3CGeoFeed(Rss201rev2Feed, GeoFeedMixin): def rss_attributes(self): attrs = super(W3CGeoFeed, self).rss_attributes() - attrs[u'xmlns:geo'] = u'http://www.w3.org/2003/01/geo/wgs84_pos#' + attrs['xmlns:geo'] = 'http://www.w3.org/2003/01/geo/wgs84_pos#' return attrs def add_item_elements(self, handler, item): diff --git a/django/contrib/gis/forms/fields.py b/django/contrib/gis/forms/fields.py index f806dcb3c62..432f0e18729 100644 --- a/django/contrib/gis/forms/fields.py +++ b/django/contrib/gis/forms/fields.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django import forms from django.utils.translation import ugettext_lazy as _ @@ -14,10 +16,10 @@ class GeometryField(forms.Field): widget = forms.Textarea default_error_messages = { - 'no_geom' : _(u'No geometry value provided.'), - 'invalid_geom' : _(u'Invalid geometry value.'), - 'invalid_geom_type' : _(u'Invalid geometry type.'), - 'transform_error' : _(u'An error occurred when transforming the geometry ' + 'no_geom' : _('No geometry value provided.'), + 'invalid_geom' : _('Invalid geometry value.'), + 'invalid_geom_type' : _('Invalid geometry type.'), + 'transform_error' : _('An error occurred when transforming the geometry ' 'to the SRID of the geometry form field.'), } diff --git a/django/contrib/gis/gdal/tests/test_envelope.py b/django/contrib/gis/gdal/tests/test_envelope.py index 7574284bbad..07e12c0ca73 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): self.assertRaises(OGRException, Envelope, (0, 0, 5, 5, 3)) self.assertRaises(OGRException, Envelope, ()) self.assertRaises(ValueError, Envelope, 0, 'a', 5, 5) - self.assertRaises(TypeError, Envelope, u'foo') + self.assertRaises(TypeError, Envelope, 'foo') self.assertRaises(OGRException, Envelope, (1, 1, 0, 0)) try: Envelope(0, 0, 0, 0) diff --git a/django/contrib/gis/geoip/tests.py b/django/contrib/gis/geoip/tests.py index a629d86bbfd..1d9132ba6f0 100644 --- a/django/contrib/gis/geoip/tests.py +++ b/django/contrib/gis/geoip/tests.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import os from django.conf import settings from django.contrib.gis.geos import GEOSGeometry @@ -99,13 +101,13 @@ class GeoIPTest(unittest.TestCase): "Testing that GeoIP strings are properly encoded, see #16553." g = GeoIP() d = g.city('62.224.93.23') - self.assertEqual(u'Sch\xf6mberg', d['city']) + self.assertEqual('Schümberg', d['city']) def test06_unicode_query(self): "Testing that GeoIP accepts unicode string queries, see #17059." g = GeoIP() - d = g.country(u'whitehouse.gov') - self.assertEqual(u'US', d['country_code']) + d = g.country('whitehouse.gov') + self.assertEqual('US', d['country_code']) def suite(): diff --git a/django/contrib/gis/sitemaps/views.py b/django/contrib/gis/sitemaps/views.py index 3a9acad7b04..eb42d0cae88 100644 --- a/django/contrib/gis/sitemaps/views.py +++ b/django/contrib/gis/sitemaps/views.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.http import HttpResponse, Http404 from django.template import loader from django.contrib.sites.models import get_current_site @@ -41,7 +43,7 @@ def sitemap(request, sitemaps, section=None): maps, urls = [], [] if section is not None: if section not in sitemaps: - raise Http404(_(u"No sitemap available for section: %r") % section) + raise Http404(_("No sitemap available for section: %r") % section) maps.append(sitemaps[section]) else: maps = sitemaps.values() @@ -55,9 +57,9 @@ def sitemap(request, sitemaps, section=None): else: urls.extend(site.get_urls(page=page, site=current_site)) except EmptyPage: - raise Http404(_(u"Page %s empty") % page) + raise Http404(_("Page %s empty") % page) except PageNotAnInteger: - raise Http404(_(u"No page '%s'") % page) + raise Http404(_("No page '%s'") % page) xml = smart_str(loader.render_to_string('gis/sitemaps/geo_sitemap.xml', {'urlset': urls})) return HttpResponse(xml, content_type='application/xml') diff --git a/django/contrib/gis/tests/geoapp/test_feeds.py b/django/contrib/gis/tests/geoapp/test_feeds.py index 936c1ded46c..85e777ae78c 100644 --- a/django/contrib/gis/tests/geoapp/test_feeds.py +++ b/django/contrib/gis/tests/geoapp/test_feeds.py @@ -44,7 +44,7 @@ class GeoFeedTest(TestCase): # Incrementing through the feeds. for feed in [feed1, feed2]: # Ensuring the georss namespace was added to the element. - self.assertEqual(feed.getAttribute(u'xmlns:georss'), u'http://www.georss.org/georss') + self.assertEqual(feed.getAttribute('xmlns:georss'), 'http://www.georss.org/georss') chan = feed.getElementsByTagName('channel')[0] items = chan.getElementsByTagName('item') self.assertEqual(len(items), City.objects.count()) @@ -64,7 +64,7 @@ class GeoFeedTest(TestCase): for feed in [feed1, feed2]: # Ensuring the georsss namespace was added to the element. - self.assertEqual(feed.getAttribute(u'xmlns:georss'), u'http://www.georss.org/georss') + self.assertEqual(feed.getAttribute('xmlns:georss'), 'http://www.georss.org/georss') entries = feed.getElementsByTagName('entry') self.assertEqual(len(entries), City.objects.count()) @@ -77,7 +77,7 @@ class GeoFeedTest(TestCase): doc = minidom.parseString(self.client.get('/feeds/w3cgeo1/').content) feed = doc.firstChild # Ensuring the geo namespace was added to the element. - self.assertEqual(feed.getAttribute(u'xmlns:geo'), u'http://www.w3.org/2003/01/geo/wgs84_pos#') + self.assertEqual(feed.getAttribute('xmlns:geo'), 'http://www.w3.org/2003/01/geo/wgs84_pos#') chan = feed.getElementsByTagName('channel')[0] items = chan.getElementsByTagName('item') self.assertEqual(len(items), City.objects.count()) diff --git a/django/contrib/gis/tests/geoapp/test_sitemaps.py b/django/contrib/gis/tests/geoapp/test_sitemaps.py index a5c8f41ba4f..5f063dfba31 100644 --- a/django/contrib/gis/tests/geoapp/test_sitemaps.py +++ b/django/contrib/gis/tests/geoapp/test_sitemaps.py @@ -34,7 +34,7 @@ class GeoSitemapTest(TestCase): # Getting the geo index. doc = minidom.parseString(self.client.get('/sitemap.xml').content) index = doc.firstChild - self.assertEqual(index.getAttribute(u'xmlns'), u'http://www.sitemaps.org/schemas/sitemap/0.9') + self.assertEqual(index.getAttribute('xmlns'), 'http://www.sitemaps.org/schemas/sitemap/0.9') self.assertEqual(3, len(index.getElementsByTagName('sitemap'))) def test_geositemap_kml(self): @@ -44,8 +44,8 @@ class GeoSitemapTest(TestCase): # Ensuring the right sitemaps namespaces are present. urlset = doc.firstChild - self.assertEqual(urlset.getAttribute(u'xmlns'), u'http://www.sitemaps.org/schemas/sitemap/0.9') - self.assertEqual(urlset.getAttribute(u'xmlns:geo'), u'http://www.google.com/geo/schemas/sitemap/1.0') + self.assertEqual(urlset.getAttribute('xmlns'), 'http://www.sitemaps.org/schemas/sitemap/0.9') + 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. @@ -84,8 +84,8 @@ class GeoSitemapTest(TestCase): # Ensuring the right sitemaps namespaces are present. urlset = doc.firstChild - self.assertEqual(urlset.getAttribute(u'xmlns'), u'http://www.sitemaps.org/schemas/sitemap/0.9') - self.assertEqual(urlset.getAttribute(u'xmlns:geo'), u'http://www.google.com/geo/schemas/sitemap/1.0') + self.assertEqual(urlset.getAttribute('xmlns'), 'http://www.sitemaps.org/schemas/sitemap/0.9') + self.assertEqual(urlset.getAttribute('xmlns:geo'), 'http://www.google.com/geo/schemas/sitemap/1.0') # Making sure the correct number of feed URLs were included. urls = urlset.getElementsByTagName('url') diff --git a/django/contrib/gis/views.py b/django/contrib/gis/views.py index fc51a0bf3aa..3fa8f044ded 100644 --- a/django/contrib/gis/views.py +++ b/django/contrib/gis/views.py @@ -1,10 +1,12 @@ +from __future__ import unicode_literals + from django.http import Http404 from django.utils.translation import ugettext as _ def feed(request, url, feed_dict=None): """Provided for backwards compatibility.""" if not feed_dict: - raise Http404(_(u"No feeds are registered.")) + raise Http404(_("No feeds are registered.")) try: slug, param = url.split('/', 1) @@ -14,7 +16,7 @@ def feed(request, url, feed_dict=None): try: f = feed_dict[slug] except KeyError: - raise Http404(_(u"Slug %r isn't registered.") % slug) + raise Http404(_("Slug %r isn't registered.") % slug) instance = f() instance.feed_url = getattr(f, 'feed_url', None) or request.path diff --git a/django/contrib/humanize/templatetags/humanize.py b/django/contrib/humanize/templatetags/humanize.py index b075ff05c7c..7a2e5147d8a 100644 --- a/django/contrib/humanize/templatetags/humanize.py +++ b/django/contrib/humanize/templatetags/humanize.py @@ -1,3 +1,4 @@ +from __future__ import unicode_literals import re from datetime import date, datetime, timedelta @@ -23,8 +24,8 @@ def ordinal(value): return value suffixes = (_('th'), _('st'), _('nd'), _('rd'), _('th'), _('th'), _('th'), _('th'), _('th'), _('th')) if value % 100 in (11, 12, 13): # special case - return u"%d%s" % (value, suffixes[0]) - return u"%d%s" % (value, suffixes[value % 10]) + return "%d%s" % (value, suffixes[0]) + return "%d%s" % (value, suffixes[value % 10]) @register.filter(is_safe=True) def intcomma(value, use_l10n=True): @@ -161,11 +162,11 @@ def naturalday(value, arg=None): today = datetime.now(tzinfo).date() delta = value - today if delta.days == 0: - return _(u'today') + return _('today') elif delta.days == 1: - return _(u'tomorrow') + return _('tomorrow') elif delta.days == -1: - return _(u'yesterday') + return _('yesterday') return defaultfilters.date(value, arg) @register.filter @@ -185,20 +186,20 @@ def naturaltime(value): 'naturaltime', '%(delta)s ago' ) % {'delta': defaultfilters.timesince(value)} elif delta.seconds == 0: - return _(u'now') + return _('now') elif delta.seconds < 60: return ungettext( - u'a second ago', u'%(count)s seconds ago', delta.seconds + 'a second ago', '%(count)s seconds ago', delta.seconds ) % {'count': delta.seconds} elif delta.seconds // 60 < 60: count = delta.seconds // 60 return ungettext( - u'a minute ago', u'%(count)s minutes ago', count + 'a minute ago', '%(count)s minutes ago', count ) % {'count': count} else: count = delta.seconds // 60 // 60 return ungettext( - u'an hour ago', u'%(count)s hours ago', count + 'an hour ago', '%(count)s hours ago', count ) % {'count': count} else: delta = value - now @@ -207,18 +208,18 @@ def naturaltime(value): 'naturaltime', '%(delta)s from now' ) % {'delta': defaultfilters.timeuntil(value)} elif delta.seconds == 0: - return _(u'now') + return _('now') elif delta.seconds < 60: return ungettext( - u'a second from now', u'%(count)s seconds from now', delta.seconds + 'a second from now', '%(count)s seconds from now', delta.seconds ) % {'count': delta.seconds} elif delta.seconds // 60 < 60: count = delta.seconds // 60 return ungettext( - u'a minute from now', u'%(count)s minutes from now', count + 'a minute from now', '%(count)s minutes from now', count ) % {'count': count} else: count = delta.seconds // 60 // 60 return ungettext( - u'an hour from now', u'%(count)s hours from now', count + 'an hour from now', '%(count)s hours from now', count ) % {'count': count} diff --git a/django/contrib/humanize/tests.py b/django/contrib/humanize/tests.py index bf6684766bc..ecf4b83d6de 100644 --- a/django/contrib/humanize/tests.py +++ b/django/contrib/humanize/tests.py @@ -1,3 +1,4 @@ +from __future__ import unicode_literals import datetime import new @@ -89,8 +90,8 @@ class HumanizeTests(TestCase): def test_apnumber(self): test_list = [str(x) for x in range(1, 11)] test_list.append(None) - result_list = (u'one', u'two', u'three', u'four', u'five', u'six', - u'seven', u'eight', u'nine', u'10', None) + result_list = ('one', 'two', 'three', 'four', 'five', 'six', + 'seven', 'eight', 'nine', '10', None) self.humanize_tester(test_list, result_list, 'apnumber') @@ -99,12 +100,12 @@ class HumanizeTests(TestCase): yesterday = today - datetime.timedelta(days=1) tomorrow = today + datetime.timedelta(days=1) someday = today - datetime.timedelta(days=10) - notdate = u"I'm not a date value" + notdate = "I'm not a date value" test_list = (today, yesterday, tomorrow, someday, notdate, None) someday_result = defaultfilters.date(someday) - result_list = (_(u'today'), _(u'yesterday'), _(u'tomorrow'), - someday_result, u"I'm not a date value", None) + result_list = (_('today'), _('yesterday'), _('tomorrow'), + someday_result, "I'm not a date value", None) self.humanize_tester(test_list, result_list, 'naturalday') def test_naturalday_tz(self): diff --git a/django/contrib/localflavor/ar/ar_provinces.py b/django/contrib/localflavor/ar/ar_provinces.py index a0efd4ba33e..600ef1eb166 100644 --- a/django/contrib/localflavor/ar/ar_provinces.py +++ b/django/contrib/localflavor/ar/ar_provinces.py @@ -7,30 +7,31 @@ http://www.argentina.gov.ar/argentina/portal/paginas.dhtml?pagina=425 This exists in this standalone file so that it's only imported into memory when explicitly needed. """ +from __future__ import unicode_literals PROVINCE_CHOICES = ( - ('B', u'Buenos Aires'), - ('K', u'Catamarca'), - ('H', u'Chaco'), - ('U', u'Chubut'), - ('C', u'Ciudad Autónoma de Buenos Aires'), - ('X', u'Córdoba'), - ('W', u'Corrientes'), - ('E', u'Entre Ríos'), - ('P', u'Formosa'), - ('Y', u'Jujuy'), - ('L', u'La Pampa'), - ('F', u'La Rioja'), - ('M', u'Mendoza'), - ('N', u'Misiones'), - ('Q', u'Neuquén'), - ('R', u'Río Negro'), - ('A', u'Salta'), - ('J', u'San Juan'), - ('D', u'San Luis'), - ('Z', u'Santa Cruz'), - ('S', u'Santa Fe'), - ('G', u'Santiago del Estero'), - ('V', u'Tierra del Fuego, Antártida e Islas del Atlántico Sur'), - ('T', u'Tucumán'), + ('B', 'Buenos Aires'), + ('K', 'Catamarca'), + ('H', 'Chaco'), + ('U', 'Chubut'), + ('C', 'Ciudad Autónoma de Buenos Aires'), + ('X', 'Córdoba'), + ('W', 'Corrientes'), + ('E', 'Entre Ríos'), + ('P', 'Formosa'), + ('Y', 'Jujuy'), + ('L', 'La Pampa'), + ('F', 'La Rioja'), + ('M', 'Mendoza'), + ('N', 'Misiones'), + ('Q', 'Neuquén'), + ('R', 'Río Negro'), + ('A', 'Salta'), + ('J', 'San Juan'), + ('D', 'San Luis'), + ('Z', 'Santa Cruz'), + ('S', 'Santa Fe'), + ('G', 'Santiago del Estero'), + ('V', 'Tierra del Fuego, Antártida e Islas del Atlántico Sur'), + ('T', 'Tucumán'), ) diff --git a/django/contrib/localflavor/ar/forms.py b/django/contrib/localflavor/ar/forms.py index 1805839ce4b..8e252beec9f 100644 --- a/django/contrib/localflavor/ar/forms.py +++ b/django/contrib/localflavor/ar/forms.py @@ -3,7 +3,7 @@ AR-specific Form helpers. """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from django.contrib.localflavor.ar.ar_provinces import PROVINCE_CHOICES from django.core.validators import EMPTY_VALUES @@ -37,11 +37,11 @@ class ARPostalCodeField(RegexField): def clean(self, value): value = super(ARPostalCodeField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' if len(value) not in (4, 8): raise ValidationError(self.error_messages['invalid']) if len(value) == 8: - return u'%s%s%s' % (value[0].upper(), value[1:5], value[5:].upper()) + return '%s%s%s' % (value[0].upper(), value[1:5], value[5:].upper()) return value class ARDNIField(CharField): @@ -63,7 +63,7 @@ class ARDNIField(CharField): """ value = super(ARDNIField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' if not value.isdigit(): value = value.replace('.', '') if not value.isdigit(): @@ -94,7 +94,7 @@ class ARCUITField(RegexField): """ value = super(ARCUITField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value, cd = self._canon(value) if self._calc_cd(value) != cd: raise ValidationError(self.error_messages['checksum']) @@ -113,5 +113,5 @@ class ARCUITField(RegexField): if check_digit == None: check_digit = cuit[-1] cuit = cuit[:-1] - return u'%s-%s-%s' % (cuit[:2], cuit[2:], check_digit) + return '%s-%s-%s' % (cuit[:2], cuit[2:], check_digit) diff --git a/django/contrib/localflavor/at/forms.py b/django/contrib/localflavor/at/forms.py index 262641bf1f3..c531bec2e9a 100644 --- a/django/contrib/localflavor/at/forms.py +++ b/django/contrib/localflavor/at/forms.py @@ -1,7 +1,7 @@ """ AT-specific Form helpers """ - +from __future__ import unicode_literals import re from django.core.validators import EMPTY_VALUES @@ -47,13 +47,13 @@ class ATSocialSecurityNumberField(Field): """ default_error_messages = { - 'invalid': _(u'Enter a valid Austrian Social Security Number in XXXX XXXXXX format.'), + 'invalid': _('Enter a valid Austrian Social Security Number in XXXX XXXXXX format.'), } def clean(self, value): value = super(ATSocialSecurityNumberField, self).clean(value) if value in EMPTY_VALUES: - return u"" + return "" if not re_ssn.search(value): raise ValidationError(self.error_messages['invalid']) sqnr, date = value.split(" ") @@ -66,4 +66,4 @@ class ATSocialSecurityNumberField(Field): res = res % 11 if res != int(check): raise ValidationError(self.error_messages['invalid']) - return u'%s%s %s'%(sqnr, check, date,) + return '%s%s %s'%(sqnr, check, date,) diff --git a/django/contrib/localflavor/au/forms.py b/django/contrib/localflavor/au/forms.py index 19df98dc336..34170fabc88 100644 --- a/django/contrib/localflavor/au/forms.py +++ b/django/contrib/localflavor/au/forms.py @@ -2,7 +2,7 @@ Australian-specific Form helpers """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re @@ -34,7 +34,7 @@ class AUPostCodeField(RegexField): class AUPhoneNumberField(Field): """Australian phone number field.""" default_error_messages = { - 'invalid': u'Phone numbers must contain 10 digits.', + 'invalid': 'Phone numbers must contain 10 digits.', } def clean(self, value): @@ -43,11 +43,11 @@ class AUPhoneNumberField(Field): """ super(AUPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = re.sub('(\(|\)|\s+|-)', '', smart_unicode(value)) phone_match = PHONE_DIGITS_RE.search(value) if phone_match: - return u'%s' % phone_match.group(1) + return '%s' % phone_match.group(1) raise ValidationError(self.error_messages['invalid']) diff --git a/django/contrib/localflavor/br/br_states.py b/django/contrib/localflavor/br/br_states.py index 98e54bca2c6..ab37b1d2231 100644 --- a/django/contrib/localflavor/br/br_states.py +++ b/django/contrib/localflavor/br/br_states.py @@ -5,33 +5,34 @@ An alphabetical list of Brazilian states for use as `choices` in a formfield. This exists in this standalone file so that it's only imported into memory when explicitly needed. """ +from __future__ import unicode_literals STATE_CHOICES = ( ('AC', 'Acre'), ('AL', 'Alagoas'), - ('AP', u'Amapá'), + ('AP', 'Amapá'), ('AM', 'Amazonas'), ('BA', 'Bahia'), - ('CE', u'Ceará'), + ('CE', 'Ceará'), ('DF', 'Distrito Federal'), - ('ES', u'Espírito Santo'), - ('GO', u'Goiás'), - ('MA', u'Maranhão'), + ('ES', 'Espírito Santo'), + ('GO', 'Goiás'), + ('MA', 'Maranhão'), ('MT', 'Mato Grosso'), ('MS', 'Mato Grosso do Sul'), ('MG', 'Minas Gerais'), - ('PA', u'Pará'), - ('PB', u'Paraíba'), - ('PR', u'Paraná'), + ('PA', 'Pará'), + ('PB', 'Paraíba'), + ('PR', 'Paraná'), ('PE', 'Pernambuco'), - ('PI', u'Piauí'), + ('PI', 'Piauí'), ('RJ', 'Rio de Janeiro'), ('RN', 'Rio Grande do Norte'), ('RS', 'Rio Grande do Sul'), - ('RO', u'Rondônia'), + ('RO', 'Rondônia'), ('RR', 'Roraima'), ('SC', 'Santa Catarina'), - ('SP', u'São Paulo'), + ('SP', 'São Paulo'), ('SE', 'Sergipe'), ('TO', 'Tocantins'), ) diff --git a/django/contrib/localflavor/br/forms.py b/django/contrib/localflavor/br/forms.py index 88c7f2efcc2..f287d46a9ae 100644 --- a/django/contrib/localflavor/br/forms.py +++ b/django/contrib/localflavor/br/forms.py @@ -3,7 +3,7 @@ BR-specific Form helpers """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re @@ -34,11 +34,11 @@ class BRPhoneNumberField(Field): def clean(self, value): super(BRPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = re.sub('(\(|\)|\s+)', '', smart_unicode(value)) m = phone_digits_re.search(value) if m: - return u'%s-%s-%s' % (m.group(1), m.group(2), m.group(3)) + return '%s-%s-%s' % (m.group(1), m.group(2), m.group(3)) raise ValidationError(self.error_messages['invalid']) class BRStateSelect(Select): @@ -55,7 +55,7 @@ class BRStateChoiceField(Field): """ widget = Select default_error_messages = { - 'invalid': _(u'Select a valid brazilian state. That state is not one of the available states.'), + 'invalid': _('Select a valid brazilian state. That state is not one of the available states.'), } def __init__(self, required=True, widget=None, label=None, @@ -67,9 +67,9 @@ class BRStateChoiceField(Field): def clean(self, value): value = super(BRStateChoiceField, self).clean(value) if value in EMPTY_VALUES: - value = u'' + value = '' value = smart_unicode(value) - if value == u'': + if value == '': return value valid_values = set([smart_unicode(k) for k, v in self.widget.choices]) if value not in valid_values: @@ -105,7 +105,7 @@ class BRCPFField(CharField): """ value = super(BRCPFField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' orig_value = value[:] if not value.isdigit(): value = re.sub("[-\.]", "", value) @@ -142,7 +142,7 @@ class BRCNPJField(Field): """ value = super(BRCNPJField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' orig_value = value[:] if not value.isdigit(): value = re.sub("[-/\.]", "", value) diff --git a/django/contrib/localflavor/ca/forms.py b/django/contrib/localflavor/ca/forms.py index c3be79968fd..ec66e665393 100644 --- a/django/contrib/localflavor/ca/forms.py +++ b/django/contrib/localflavor/ca/forms.py @@ -2,7 +2,7 @@ Canada-specific Form helpers """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re @@ -26,7 +26,7 @@ class CAPostalCodeField(CharField): http://www.canadapost.ca/tools/pg/manual/PGaddress-e.asp#1402170 """ default_error_messages = { - 'invalid': _(u'Enter a postal code in the format XXX XXX.'), + 'invalid': _('Enter a postal code in the format XXX XXX.'), } postcode_regex = re.compile(r'^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ]) *(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$') @@ -34,7 +34,7 @@ class CAPostalCodeField(CharField): def clean(self, value): value = super(CAPostalCodeField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' postcode = value.upper().strip() m = self.postcode_regex.match(postcode) if not m: @@ -44,7 +44,7 @@ class CAPostalCodeField(CharField): class CAPhoneNumberField(Field): """Canadian phone number field.""" default_error_messages = { - 'invalid': _(u'Phone numbers must be in XXX-XXX-XXXX format.'), + 'invalid': _('Phone numbers must be in XXX-XXX-XXXX format.'), } def clean(self, value): @@ -52,11 +52,11 @@ class CAPhoneNumberField(Field): """ super(CAPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = re.sub('(\(|\)|\s+)', '', smart_unicode(value)) m = phone_digits_re.search(value) if m: - return u'%s-%s-%s' % (m.group(1), m.group(2), m.group(3)) + return '%s-%s-%s' % (m.group(1), m.group(2), m.group(3)) raise ValidationError(self.error_messages['invalid']) class CAProvinceField(Field): @@ -66,13 +66,13 @@ class CAProvinceField(Field): abbreviation for the given province. """ default_error_messages = { - 'invalid': _(u'Enter a Canadian province or territory.'), + 'invalid': _('Enter a Canadian province or territory.'), } def clean(self, value): super(CAProvinceField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' try: value = value.strip().lower() except AttributeError: @@ -113,14 +113,14 @@ class CASocialInsuranceNumberField(Field): def clean(self, value): super(CASocialInsuranceNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' match = re.match(sin_re, value) if not match: raise ValidationError(self.error_messages['invalid']) - number = u'%s-%s-%s' % (match.group(1), match.group(2), match.group(3)) - check_number = u'%s%s%s' % (match.group(1), match.group(2), match.group(3)) + number = '%s-%s-%s' % (match.group(1), match.group(2), match.group(3)) + check_number = '%s%s%s' % (match.group(1), match.group(2), match.group(3)) if not self.luhn_checksum_is_valid(check_number): raise ValidationError(self.error_messages['invalid']) return number diff --git a/django/contrib/localflavor/ch/forms.py b/django/contrib/localflavor/ch/forms.py index 649a98ab715..e844a3c57cf 100644 --- a/django/contrib/localflavor/ch/forms.py +++ b/django/contrib/localflavor/ch/forms.py @@ -2,7 +2,7 @@ Swiss-specific Form helpers """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re @@ -40,11 +40,11 @@ class CHPhoneNumberField(Field): def clean(self, value): super(CHPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = re.sub('(\.|\s|/|-)', '', smart_unicode(value)) m = phone_digits_re.search(value) if m: - return u'%s %s %s %s' % (value[0:3], value[3:6], value[6:8], value[8:10]) + return '%s %s %s %s' % (value[0:3], value[3:6], value[6:8], value[8:10]) raise ValidationError(self.error_messages['invalid']) class CHStateSelect(Select): @@ -102,7 +102,7 @@ class CHIdentityCardNumberField(Field): def clean(self, value): super(CHIdentityCardNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' match = re.match(id_re, value) if not match: @@ -118,5 +118,5 @@ class CHIdentityCardNumberField(Field): if not self.has_valid_checksum(all_digits): raise ValidationError(self.error_messages['invalid']) - return u'%s%s%s' % (idnumber, pos9, checksum) + return '%s%s%s' % (idnumber, pos9, checksum) diff --git a/django/contrib/localflavor/cl/cl_regions.py b/django/contrib/localflavor/cl/cl_regions.py index 47db6d39125..d76f6ad8340 100644 --- a/django/contrib/localflavor/cl/cl_regions.py +++ b/django/contrib/localflavor/cl/cl_regions.py @@ -5,21 +5,22 @@ A list of Chilean regions as `choices` in a formfield. This exists in this standalone file so that it's only imported into memory when explicitly needed. """ +from __future__ import unicode_literals REGION_CHOICES = ( - ('RM', u'Región Metropolitana de Santiago'), - ('I', u'Región de Tarapacá'), - ('II', u'Región de Antofagasta'), - ('III', u'Región de Atacama'), - ('IV', u'Región de Coquimbo'), - ('V', u'Región de Valparaíso'), - ('VI', u'Región del Libertador Bernardo O\'Higgins'), - ('VII', u'Región del Maule'), - ('VIII',u'Región del Bío Bío'), - ('IX', u'Región de la Araucanía'), - ('X', u'Región de los Lagos'), - ('XI', u'Región de Aysén del General Carlos Ibáñez del Campo'), - ('XII', u'Región de Magallanes y la Antártica Chilena'), - ('XIV', u'Región de Los Ríos'), - ('XV', u'Región de Arica-Parinacota'), + ('RM', 'Región Metropolitana de Santiago'), + ('I', 'Región de Tarapacá'), + ('II', 'Región de Antofagasta'), + ('III', 'Región de Atacama'), + ('IV', 'Región de Coquimbo'), + ('V', 'Región de Valparaíso'), + ('VI', 'Región del Libertador Bernardo O\'Higgins'), + ('VII', 'Región del Maule'), + ('VIII','Región del Bío Bío'), + ('IX', 'Región de la Araucanía'), + ('X', 'Región de los Lagos'), + ('XI', 'Región de Aysén del General Carlos Ibáñez del Campo'), + ('XII', 'Región de Magallanes y la Antártica Chilena'), + ('XIV', 'Región de Los Ríos'), + ('XV', 'Región de Arica-Parinacota'), ) diff --git a/django/contrib/localflavor/cl/forms.py b/django/contrib/localflavor/cl/forms.py index 7a9aa2da8ca..59911763828 100644 --- a/django/contrib/localflavor/cl/forms.py +++ b/django/contrib/localflavor/cl/forms.py @@ -2,15 +2,15 @@ Chile specific form helpers. """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals -from django.contrib.localflavor.cl.cl_regions import REGION_CHOICES from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import RegexField, Select from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import smart_unicode +from .cl_regions import REGION_CHOICES class CLRegionSelect(Select): """ @@ -50,7 +50,7 @@ class CLRutField(RegexField): """ super(CLRutField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' rut, verificador = self._canonify(value) if self._algorithm(rut) == verificador: return self._format(rut, verificador) @@ -68,7 +68,7 @@ class CLRutField(RegexField): multi += 1 if multi == 8: multi = 2 - return u'0123456789K0'[11 - suma % 11] + return '0123456789K0'[11 - suma % 11] def _canonify(self, rut): """ @@ -93,5 +93,5 @@ class CLRutField(RegexField): else: new_dot = pos - 3 code = code[:new_dot] + '.' + code[new_dot:] - return u'%s-%s' % (code, verifier) + return '%s-%s' % (code, verifier) diff --git a/django/contrib/localflavor/cn/cn_provinces.py b/django/contrib/localflavor/cn/cn_provinces.py index fe0aa37cb64..c27cba64231 100644 --- a/django/contrib/localflavor/cn/cn_provinces.py +++ b/django/contrib/localflavor/cn/cn_provinces.py @@ -9,41 +9,41 @@ http://en.wikipedia.org/wiki/Province_%28China%29 http://en.wikipedia.org/wiki/Direct-controlled_municipality http://en.wikipedia.org/wiki/Autonomous_regions_of_China """ - +from __future__ import unicode_literals CN_PROVINCE_CHOICES = ( - ("anhui", u"安徽"), - ("beijing", u"北京"), - ("chongqing", u"重庆"), - ("fujian", u"福建"), - ("gansu", u"甘肃"), - ("guangdong", u"广东"), - ("guangxi", u"广西壮族自治区"), - ("guizhou", u"贵州"), - ("hainan", u"海南"), - ("hebei", u"河北"), - ("heilongjiang", u"黑龙江"), - ("henan", u"河南"), - ("hongkong", u"香港"), - ("hubei", u"湖北"), - ("hunan", u"湖南"), - ("jiangsu", u"江苏"), - ("jiangxi", u"江西"), - ("jilin", u"吉林"), - ("liaoning", u"辽宁"), - ("macao", u"澳门"), - ("neimongol", u"内蒙古自治区"), - ("ningxia", u"宁夏回族自治区"), - ("qinghai", u"青海"), - ("shaanxi", u"陕西"), - ("shandong", u"山东"), - ("shanghai", u"上海"), - ("shanxi", u"山西"), - ("sichuan", u"四川"), - ("taiwan", u"台湾"), - ("tianjin", u"天津"), - ("xinjiang", u"新疆维吾尔自治区"), - ("xizang", u"西藏自治区"), - ("yunnan", u"云南"), - ("zhejiang", u"浙江"), + ("anhui", "安徽"), + ("beijing", "北京"), + ("chongqing", "重庆"), + ("fujian", "福建"), + ("gansu", "甘肃"), + ("guangdong", "广东"), + ("guangxi", "广西壮族自治区"), + ("guizhou", "贵州"), + ("hainan", "海南"), + ("hebei", "河北"), + ("heilongjiang", "黑龙江"), + ("henan", "河南"), + ("hongkong", "香港"), + ("hubei", "湖北"), + ("hunan", "湖南"), + ("jiangsu", "江苏"), + ("jiangxi", "江西"), + ("jilin", "吉林"), + ("liaoning", "辽宁"), + ("macao", "澳门"), + ("neimongol", "内蒙古自治区"), + ("ningxia", "宁夏回族自治区"), + ("qinghai", "青海"), + ("shaanxi", "陕西"), + ("shandong", "山东"), + ("shanghai", "上海"), + ("shanxi", "山西"), + ("sichuan", "四川"), + ("taiwan", "台湾"), + ("tianjin", "天津"), + ("xinjiang", "新疆维吾尔自治区"), + ("xizang", "西藏自治区"), + ("yunnan", "云南"), + ("zhejiang", "浙江"), ) diff --git a/django/contrib/localflavor/cn/forms.py b/django/contrib/localflavor/cn/forms.py index af92ba06ecb..43adcf3f013 100644 --- a/django/contrib/localflavor/cn/forms.py +++ b/django/contrib/localflavor/cn/forms.py @@ -3,7 +3,7 @@ """ Chinese-specific form helpers """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re @@ -81,7 +81,7 @@ class CNPostCodeField(RegexField): Valid code is XXXXXX where X is digit. """ default_error_messages = { - 'invalid': _(u'Enter a post code in the format XXXXXX.'), + 'invalid': _('Enter a post code in the format XXXXXX.'), } def __init__(self, *args, **kwargs): @@ -102,10 +102,10 @@ class CNIDCardField(CharField): The checksum algorithm is described in GB11643-1999. """ default_error_messages = { - 'invalid': _(u'ID Card Number consists of 15 or 18 digits.'), - 'checksum': _(u'Invalid ID Card Number: Wrong checksum'), - 'birthday': _(u'Invalid ID Card Number: Wrong birthdate'), - 'location': _(u'Invalid ID Card Number: Wrong location code'), + 'invalid': _('ID Card Number consists of 15 or 18 digits.'), + 'checksum': _('Invalid ID Card Number: Wrong checksum'), + 'birthday': _('Invalid ID Card Number: Wrong birthdate'), + 'location': _('Invalid ID Card Number: Wrong location code'), } def __init__(self, max_length=18, min_length=15, *args, **kwargs): @@ -119,7 +119,7 @@ class CNIDCardField(CharField): # Check the length of the ID card number. super(CNIDCardField, self).clean(value) if not value: - return u"" + return "" # Check whether this ID card number has valid format if not re.match(ID_CARD_RE, value): raise ValidationError(self.error_messages['invalid']) @@ -133,7 +133,7 @@ class CNIDCardField(CharField): value = value.upper() if not self.has_valid_checksum(value): raise ValidationError(self.error_messages['checksum']) - return u'%s' % value + return '%s' % value def has_valid_birthday(self, value): """ @@ -190,7 +190,7 @@ class CNPhoneNumberField(RegexField): 010-55555555-35 """ default_error_messages = { - 'invalid': _(u'Enter a valid phone number.'), + 'invalid': _('Enter a valid phone number.'), } def __init__(self, *args, **kwargs): @@ -207,7 +207,7 @@ class CNCellNumberField(RegexField): The length of the cell number should be 11. """ default_error_messages = { - 'invalid': _(u'Enter a valid cell number.'), + 'invalid': _('Enter a valid cell number.'), } def __init__(self, *args, **kwargs): diff --git a/django/contrib/localflavor/co/co_departments.py b/django/contrib/localflavor/co/co_departments.py index f0989b6ba68..7168f54cc23 100644 --- a/django/contrib/localflavor/co/co_departments.py +++ b/django/contrib/localflavor/co/co_departments.py @@ -6,39 +6,40 @@ formfield. This exists in this standalone file so that it's only imported into memory when explicitly needed. """ +from __future__ import unicode_literals DEPARTMENT_CHOICES = ( - ('AMA', u'Amazonas'), - ('ANT', u'Antioquia'), - ('ARA', u'Arauca'), - ('ATL', u'Atlántico'), - ('DC', u'Bogotá'), - ('BOL', u'Bolívar'), - ('BOY', u'Boyacá'), - ('CAL', u'Caldas'), - ('CAQ', u'Caquetá'), - ('CAS', u'Casanare'), - ('CAU', u'Cauca'), - ('CES', u'Cesar'), - ('CHO', u'Chocó'), - ('COR', u'Córdoba'), - ('CUN', u'Cundinamarca'), - ('GUA', u'Guainía'), - ('GUV', u'Guaviare'), - ('HUI', u'Huila'), - ('LAG', u'La Guajira'), - ('MAG', u'Magdalena'), - ('MET', u'Meta'), - ('NAR', u'Nariño'), - ('NSA', u'Norte de Santander'), - ('PUT', u'Putumayo'), - ('QUI', u'Quindío'), - ('RIS', u'Risaralda'), - ('SAP', u'San Andrés and Providencia'), - ('SAN', u'Santander'), - ('SUC', u'Sucre'), - ('TOL', u'Tolima'), - ('VAC', u'Valle del Cauca'), - ('VAU', u'Vaupés'), - ('VID', u'Vichada'), + ('AMA', 'Amazonas'), + ('ANT', 'Antioquia'), + ('ARA', 'Arauca'), + ('ATL', 'Atlántico'), + ('DC', 'Bogotá'), + ('BOL', 'Bolívar'), + ('BOY', 'Boyacá'), + ('CAL', 'Caldas'), + ('CAQ', 'Caquetá'), + ('CAS', 'Casanare'), + ('CAU', 'Cauca'), + ('CES', 'Cesar'), + ('CHO', 'Chocó'), + ('COR', 'Córdoba'), + ('CUN', 'Cundinamarca'), + ('GUA', 'Guainía'), + ('GUV', 'Guaviare'), + ('HUI', 'Huila'), + ('LAG', 'La Guajira'), + ('MAG', 'Magdalena'), + ('MET', 'Meta'), + ('NAR', 'Nariño'), + ('NSA', 'Norte de Santander'), + ('PUT', 'Putumayo'), + ('QUI', 'Quindío'), + ('RIS', 'Risaralda'), + ('SAP', 'San Andrés and Providencia'), + ('SAN', 'Santander'), + ('SUC', 'Sucre'), + ('TOL', 'Tolima'), + ('VAC', 'Valle del Cauca'), + ('VAU', 'Vaupés'), + ('VID', 'Vichada'), ) diff --git a/django/contrib/localflavor/cz/forms.py b/django/contrib/localflavor/cz/forms.py index f3676b230b0..c7e81e40371 100644 --- a/django/contrib/localflavor/cz/forms.py +++ b/django/contrib/localflavor/cz/forms.py @@ -2,7 +2,7 @@ Czech-specific form helpers """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re @@ -29,7 +29,7 @@ class CZPostalCodeField(RegexField): Valid form is XXXXX or XXX XX, where X represents integer. """ default_error_messages = { - 'invalid': _(u'Enter a postal code in the format XXXXX or XXX XX.'), + 'invalid': _('Enter a postal code in the format XXXXX or XXX XX.'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): @@ -49,15 +49,15 @@ class CZBirthNumberField(Field): Czech birth number field. """ default_error_messages = { - 'invalid_format': _(u'Enter a birth number in the format XXXXXX/XXXX or XXXXXXXXXX.'), - 'invalid': _(u'Enter a valid birth number.'), + 'invalid_format': _('Enter a birth number in the format XXXXXX/XXXX or XXXXXXXXXX.'), + 'invalid': _('Enter a valid birth number.'), } def clean(self, value, gender=None): super(CZBirthNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' match = re.match(birth_number, value) if not match: @@ -67,7 +67,7 @@ class CZBirthNumberField(Field): # Three digits for verification number were used until 1. january 1954 if len(id) == 3: - return u'%s' % value + return '%s' % value # Birth number is in format YYMMDD. Females have month value raised by 50. # In case that all possible number are already used (for given date), @@ -90,7 +90,7 @@ class CZBirthNumberField(Field): modulo = int(birth + id[:3]) % 11 if (modulo == int(id[-1])) or (modulo == 10 and id[-1] == '0'): - return u'%s' % value + return '%s' % value else: raise ValidationError(self.error_messages['invalid']) @@ -99,14 +99,14 @@ class CZICNumberField(Field): Czech IC number field. """ default_error_messages = { - 'invalid': _(u'Enter a valid IC number.'), + 'invalid': _('Enter a valid IC number.'), } def clean(self, value): super(CZICNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' match = re.match(ic_number, value) if not match: @@ -130,7 +130,7 @@ class CZICNumberField(Field): if (not remainder % 10 and check == 1) or \ (remainder == 1 and check == 0) or \ (check == (11 - remainder)): - return u'%s' % value + return '%s' % value raise ValidationError(self.error_messages['invalid']) diff --git a/django/contrib/localflavor/de/forms.py b/django/contrib/localflavor/de/forms.py index 80b6248ed44..a7891d117f7 100644 --- a/django/contrib/localflavor/de/forms.py +++ b/django/contrib/localflavor/de/forms.py @@ -2,7 +2,7 @@ DE-specific Form helpers """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re @@ -68,7 +68,7 @@ class DEIdentityCardNumberField(Field): def clean(self, value): super(DEIdentityCardNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' match = re.match(id_re, value) if not match: raise ValidationError(self.error_messages['invalid']) @@ -80,9 +80,9 @@ class DEIdentityCardNumberField(Field): if residence == '0000000000' or birthday == '0000000' or validity == '0000000': raise ValidationError(self.error_messages['invalid']) - all_digits = u"%s%s%s%s" % (residence, birthday, validity, checksum) + all_digits = "%s%s%s%s" % (residence, birthday, validity, checksum) if not self.has_valid_checksum(residence) or not self.has_valid_checksum(birthday) or \ not self.has_valid_checksum(validity) or not self.has_valid_checksum(all_digits): raise ValidationError(self.error_messages['invalid']) - return u'%s%s-%s-%s-%s' % (residence, origin, birthday, validity, checksum) + return '%s%s-%s-%s-%s' % (residence, origin, birthday, validity, checksum) diff --git a/django/contrib/localflavor/de_CH/formats.py b/django/contrib/localflavor/de_CH/formats.py index d4f324a422f..9d56f9f2989 100644 --- a/django/contrib/localflavor/de_CH/formats.py +++ b/django/contrib/localflavor/de_CH/formats.py @@ -4,6 +4,8 @@ # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date +from __future__ import unicode_literals + DATE_FORMAT = 'j. F Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = 'j. F Y H:i:s' @@ -39,5 +41,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 = u'\xa0' # non-breaking space +THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3 diff --git a/django/contrib/localflavor/ec/ec_provinces.py b/django/contrib/localflavor/ec/ec_provinces.py index 7e55078be03..db25d26ff80 100644 --- a/django/contrib/localflavor/ec/ec_provinces.py +++ b/django/contrib/localflavor/ec/ec_provinces.py @@ -6,30 +6,31 @@ formfield. This exists in this standalone file so that it's only imported into memory when explicitly needed. """ +from __future__ import unicode_literals PROVINCE_CHOICES = ( - ('A', u'Azuay'), - ('B', u'Bolívar'), - ('F', u'Cañar'), - ('C', u'Carchi'), - ('H', u'Chimborazo'), - ('X', u'Cotopaxi'), - ('O', u'El Oro'), - ('E', u'Esmeraldas'), - ('W', u'Galápagos'), - ('G', u'Guayas'), - ('I', u'Imbabura'), - ('L', u'Loja'), - ('R', u'Los Ríos'), - ('M', u'Manabí'), - ('S', u'Morona Santiago'), - ('N', u'Napo'), - ('D', u'Orellana'), - ('Y', u'Pastaza'), - ('P', u'Pichincha'), - ('SE', u'Santa Elena'), - ('SD', u'Santo Domingo de los Tsáchilas'), - ('U', u'Sucumbíos'), - ('T', u'Tungurahua'), - ('Z', u'Zamora Chinchipe'), + ('A', 'Azuay'), + ('B', 'Bolívar'), + ('F', 'Cañar'), + ('C', 'Carchi'), + ('H', 'Chimborazo'), + ('X', 'Cotopaxi'), + ('O', 'El Oro'), + ('E', 'Esmeraldas'), + ('W', 'Galápagos'), + ('G', 'Guayas'), + ('I', 'Imbabura'), + ('L', 'Loja'), + ('R', 'Los Ríos'), + ('M', 'Manabí'), + ('S', 'Morona Santiago'), + ('N', 'Napo'), + ('D', 'Orellana'), + ('Y', 'Pastaza'), + ('P', 'Pichincha'), + ('SE', 'Santa Elena'), + ('SD', 'Santo Domingo de los Tsáchilas'), + ('U', 'Sucumbíos'), + ('T', 'Tungurahua'), + ('Z', 'Zamora Chinchipe'), ) diff --git a/django/contrib/localflavor/es/forms.py b/django/contrib/localflavor/es/forms.py index fe237270f52..b5e256ca44a 100644 --- a/django/contrib/localflavor/es/forms.py +++ b/django/contrib/localflavor/es/forms.py @@ -91,7 +91,7 @@ class ESIdentityCardNumberField(RegexField): def clean(self, value): super(ESIdentityCardNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' nif_get_checksum = lambda d: self.nif_control[int(d)%23] value = value.upper().replace(' ', '').replace('-', '') @@ -157,7 +157,7 @@ class ESCCCField(RegexField): def clean(self, value): super(ESCCCField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' control_str = [1, 2, 4, 8, 5, 10, 9, 7, 3, 6] m = re.match(r'^(\d{4})[ -]?(\d{4})[ -]?(\d{2})[ -]?(\d{10})$', value) entity, office, checksum, account = m.groups() diff --git a/django/contrib/localflavor/fi/fi_municipalities.py b/django/contrib/localflavor/fi/fi_municipalities.py index 4b8b886b8bb..6f90e5e02b5 100644 --- a/django/contrib/localflavor/fi/fi_municipalities.py +++ b/django/contrib/localflavor/fi/fi_municipalities.py @@ -7,347 +7,349 @@ This exists in this standalone file so that it's only imported into memory when explicitly needed. """ +from __future__ import unicode_literals + MUNICIPALITY_CHOICES = ( - ('akaa', u"Akaa"), - ('alajarvi', u"Alajärvi"), - ('alavieska', u"Alavieska"), - ('alavus', u"Alavus"), - ('artjarvi', u"Artjärvi"), - ('asikkala', u"Asikkala"), - ('askola', u"Askola"), - ('aura', u"Aura"), - ('brando', u"Brändö"), - ('eckero', u"Eckerö"), - ('enonkoski', u"Enonkoski"), - ('enontekio', u"Enontekiö"), - ('espoo', u"Espoo"), - ('eura', u"Eura"), - ('eurajoki', u"Eurajoki"), - ('evijarvi', u"Evijärvi"), - ('finstrom', u"Finström"), - ('forssa', u"Forssa"), - ('foglo', u"Föglö"), - ('geta', u"Geta"), - ('haapajarvi', u"Haapajärvi"), - ('haapavesi', u"Haapavesi"), - ('hailuoto', u"Hailuoto"), - ('halsua', u"Halsua"), - ('hamina', u"Hamina"), - ('hammarland', u"Hammarland"), - ('hankasalmi', u"Hankasalmi"), - ('hanko', u"Hanko"), - ('harjavalta', u"Harjavalta"), - ('hartola', u"Hartola"), - ('hattula', u"Hattula"), - ('haukipudas', u"Haukipudas"), - ('hausjarvi', u"Hausjärvi"), - ('heinola', u"Heinola"), - ('heinavesi', u"Heinävesi"), - ('helsinki', u"Helsinki"), - ('hirvensalmi', u"Hirvensalmi"), - ('hollola', u"Hollola"), - ('honkajoki', u"Honkajoki"), - ('huittinen', u"Huittinen"), - ('humppila', u"Humppila"), - ('hyrynsalmi', u"Hyrynsalmi"), - ('hyvinkaa', u"Hyvinkää"), - ('hameenkoski', u"Hämeenkoski"), - ('hameenkyro', u"Hämeenkyrö"), - ('hameenlinna', u"Hämeenlinna"), - ('ii', u"Ii"), - ('iisalmi', u"Iisalmi"), - ('iitti', u"Iitti"), - ('ikaalinen', u"Ikaalinen"), - ('ilmajoki', u"Ilmajoki"), - ('ilomantsi', u"Ilomantsi"), - ('imatra', u"Imatra"), - ('inari', u"Inari"), - ('inkoo', u"Inkoo"), - ('isojoki', u"Isojoki"), - ('isokyro', u"Isokyrö"), - ('jalasjarvi', u"Jalasjärvi"), - ('janakkala', u"Janakkala"), - ('joensuu', u"Joensuu"), - ('jokioinen', u"Jokioinen"), - ('jomala', u"Jomala"), - ('joroinen', u"Joroinen"), - ('joutsa', u"Joutsa"), - ('juankoski', u"Juankoski"), - ('juuka', u"Juuka"), - ('juupajoki', u"Juupajoki"), - ('juva', u"Juva"), - ('jyvaskyla', u"Jyväskylä"), - ('jamijarvi', u"Jämijärvi"), - ('jamsa', u"Jämsä"), - ('jarvenpaa', u"Järvenpää"), - ('kaarina', u"Kaarina"), - ('kaavi', u"Kaavi"), - ('kajaani', u"Kajaani"), - ('kalajoki', u"Kalajoki"), - ('kangasala', u"Kangasala"), - ('kangasniemi', u"Kangasniemi"), - ('kankaanpaa', u"Kankaanpää"), - ('kannonkoski', u"Kannonkoski"), - ('kannus', u"Kannus"), - ('karijoki', u"Karijoki"), - ('karjalohja', u"Karjalohja"), - ('karkkila', u"Karkkila"), - ('karstula', u"Karstula"), - ('karttula', u"Karttula"), - ('karvia', u"Karvia"), - ('kaskinen', u"Kaskinen"), - ('kauhajoki', u"Kauhajoki"), - ('kauhava', u"Kauhava"), - ('kauniainen', u"Kauniainen"), - ('kaustinen', u"Kaustinen"), - ('keitele', u"Keitele"), - ('kemi', u"Kemi"), - ('kemijarvi', u"Kemijärvi"), - ('keminmaa', u"Keminmaa"), - ('kemionsaari', u"Kemiönsaari"), - ('kempele', u"Kempele"), - ('kerava', u"Kerava"), - ('kerimaki', u"Kerimäki"), - ('kesalahti', u"Kesälahti"), - ('keuruu', u"Keuruu"), - ('kihnio', u"Kihniö"), - ('kiikoinen', u"Kiikoinen"), - ('kiiminki', u"Kiiminki"), - ('kinnula', u"Kinnula"), - ('kirkkonummi', u"Kirkkonummi"), - ('kitee', u"Kitee"), - ('kittila', u"Kittilä"), - ('kiuruvesi', u"Kiuruvesi"), - ('kivijarvi', u"Kivijärvi"), - ('kokemaki', u"Kokemäki"), - ('kokkola', u"Kokkola"), - ('kolari', u"Kolari"), - ('konnevesi', u"Konnevesi"), - ('kontiolahti', u"Kontiolahti"), - ('korsnas', u"Korsnäs"), - ('koskitl', u"Koski Tl"), - ('kotka', u"Kotka"), - ('kouvola', u"Kouvola"), - ('kristiinankaupunki', u"Kristiinankaupunki"), - ('kruunupyy', u"Kruunupyy"), - ('kuhmalahti', u"Kuhmalahti"), - ('kuhmo', u"Kuhmo"), - ('kuhmoinen', u"Kuhmoinen"), - ('kumlinge', u"Kumlinge"), - ('kuopio', u"Kuopio"), - ('kuortane', u"Kuortane"), - ('kurikka', u"Kurikka"), - ('kustavi', u"Kustavi"), - ('kuusamo', u"Kuusamo"), - ('kylmakoski', u"Kylmäkoski"), - ('kyyjarvi', u"Kyyjärvi"), - ('karkola', u"Kärkölä"), - ('karsamaki', u"Kärsämäki"), - ('kokar', u"Kökar"), - ('koylio', u"Köyliö"), - ('lahti', u"Lahti"), - ('laihia', u"Laihia"), - ('laitila', u"Laitila"), - ('lapinjarvi', u"Lapinjärvi"), - ('lapinlahti', u"Lapinlahti"), - ('lappajarvi', u"Lappajärvi"), - ('lappeenranta', u"Lappeenranta"), - ('lapua', u"Lapua"), - ('laukaa', u"Laukaa"), - ('lavia', u"Lavia"), - ('lemi', u"Lemi"), - ('lemland', u"Lemland"), - ('lempaala', u"Lempäälä"), - ('leppavirta', u"Leppävirta"), - ('lestijarvi', u"Lestijärvi"), - ('lieksa', u"Lieksa"), - ('lieto', u"Lieto"), - ('liminka', u"Liminka"), - ('liperi', u"Liperi"), - ('lohja', u"Lohja"), - ('loimaa', u"Loimaa"), - ('loppi', u"Loppi"), - ('loviisa', u"Loviisa"), - ('luhanka', u"Luhanka"), - ('lumijoki', u"Lumijoki"), - ('lumparland', u"Lumparland"), - ('luoto', u"Luoto"), - ('luumaki', u"Luumäki"), - ('luvia', u"Luvia"), - ('lansi-turunmaa', u"Länsi-Turunmaa"), - ('maalahti', u"Maalahti"), - ('maaninka', u"Maaninka"), - ('maarianhamina', u"Maarianhamina"), - ('marttila', u"Marttila"), - ('masku', u"Masku"), - ('merijarvi', u"Merijärvi"), - ('merikarvia', u"Merikarvia"), - ('miehikkala', u"Miehikkälä"), - ('mikkeli', u"Mikkeli"), - ('muhos', u"Muhos"), - ('multia', u"Multia"), - ('muonio', u"Muonio"), - ('mustasaari', u"Mustasaari"), - ('muurame', u"Muurame"), - ('mynamaki', u"Mynämäki"), - ('myrskyla', u"Myrskylä"), - ('mantsala', u"Mäntsälä"), - ('mantta-vilppula', u"Mänttä-Vilppula"), - ('mantyharju', u"Mäntyharju"), - ('naantali', u"Naantali"), - ('nakkila', u"Nakkila"), - ('nastola', u"Nastola"), - ('nilsia', u"Nilsiä"), - ('nivala', u"Nivala"), - ('nokia', u"Nokia"), - ('nousiainen', u"Nousiainen"), - ('nummi-pusula', u"Nummi-Pusula"), - ('nurmes', u"Nurmes"), - ('nurmijarvi', u"Nurmijärvi"), - ('narpio', u"Närpiö"), - ('oravainen', u"Oravainen"), - ('orimattila', u"Orimattila"), - ('oripaa', u"Oripää"), - ('orivesi', u"Orivesi"), - ('oulainen', u"Oulainen"), - ('oulu', u"Oulu"), - ('oulunsalo', u"Oulunsalo"), - ('outokumpu', u"Outokumpu"), - ('padasjoki', u"Padasjoki"), - ('paimio', u"Paimio"), - ('paltamo', u"Paltamo"), - ('parikkala', u"Parikkala"), - ('parkano', u"Parkano"), - ('pedersore', u"Pedersöre"), - ('pelkosenniemi', u"Pelkosenniemi"), - ('pello', u"Pello"), - ('perho', u"Perho"), - ('pertunmaa', u"Pertunmaa"), - ('petajavesi', u"Petäjävesi"), - ('pieksamaki', u"Pieksämäki"), - ('pielavesi', u"Pielavesi"), - ('pietarsaari', u"Pietarsaari"), - ('pihtipudas', u"Pihtipudas"), - ('pirkkala', u"Pirkkala"), - ('polvijarvi', u"Polvijärvi"), - ('pomarkku', u"Pomarkku"), - ('pori', u"Pori"), - ('pornainen', u"Pornainen"), - ('porvoo', u"Porvoo"), - ('posio', u"Posio"), - ('pudasjarvi', u"Pudasjärvi"), - ('pukkila', u"Pukkila"), - ('punkaharju', u"Punkaharju"), - ('punkalaidun', u"Punkalaidun"), - ('puolanka', u"Puolanka"), - ('puumala', u"Puumala"), - ('pyhtaa', u"Pyhtää"), - ('pyhajoki', u"Pyhäjoki"), - ('pyhajarvi', u"Pyhäjärvi"), - ('pyhanta', u"Pyhäntä"), - ('pyharanta', u"Pyhäranta"), - ('palkane', u"Pälkäne"), - ('poytya', u"Pöytyä"), - ('raahe', u"Raahe"), - ('raasepori', u"Raasepori"), - ('raisio', u"Raisio"), - ('rantasalmi', u"Rantasalmi"), - ('ranua', u"Ranua"), - ('rauma', u"Rauma"), - ('rautalampi', u"Rautalampi"), - ('rautavaara', u"Rautavaara"), - ('rautjarvi', u"Rautjärvi"), - ('reisjarvi', u"Reisjärvi"), - ('riihimaki', u"Riihimäki"), - ('ristiina', u"Ristiina"), - ('ristijarvi', u"Ristijärvi"), - ('rovaniemi', u"Rovaniemi"), - ('ruokolahti', u"Ruokolahti"), - ('ruovesi', u"Ruovesi"), - ('rusko', u"Rusko"), - ('raakkyla', u"Rääkkylä"), - ('saarijarvi', u"Saarijärvi"), - ('salla', u"Salla"), - ('salo', u"Salo"), - ('saltvik', u"Saltvik"), - ('sastamala', u"Sastamala"), - ('sauvo', u"Sauvo"), - ('savitaipale', u"Savitaipale"), - ('savonlinna', u"Savonlinna"), - ('savukoski', u"Savukoski"), - ('seinajoki', u"Seinäjoki"), - ('sievi', u"Sievi"), - ('siikainen', u"Siikainen"), - ('siikajoki', u"Siikajoki"), - ('siikalatva', u"Siikalatva"), - ('siilinjarvi', u"Siilinjärvi"), - ('simo', u"Simo"), - ('sipoo', u"Sipoo"), - ('siuntio', u"Siuntio"), - ('sodankyla', u"Sodankylä"), - ('soini', u"Soini"), - ('somero', u"Somero"), - ('sonkajarvi', u"Sonkajärvi"), - ('sotkamo', u"Sotkamo"), - ('sottunga', u"Sottunga"), - ('sulkava', u"Sulkava"), - ('sund', u"Sund"), - ('suomenniemi', u"Suomenniemi"), - ('suomussalmi', u"Suomussalmi"), - ('suonenjoki', u"Suonenjoki"), - ('sysma', u"Sysmä"), - ('sakyla', u"Säkylä"), - ('taipalsaari', u"Taipalsaari"), - ('taivalkoski', u"Taivalkoski"), - ('taivassalo', u"Taivassalo"), - ('tammela', u"Tammela"), - ('tampere', u"Tampere"), - ('tarvasjoki', u"Tarvasjoki"), - ('tervo', u"Tervo"), - ('tervola', u"Tervola"), - ('teuva', u"Teuva"), - ('tohmajarvi', u"Tohmajärvi"), - ('toholampi', u"Toholampi"), - ('toivakka', u"Toivakka"), - ('tornio', u"Tornio"), - ('turku', u"Turku"), - ('tuusniemi', u"Tuusniemi"), - ('tuusula', u"Tuusula"), - ('tyrnava', u"Tyrnävä"), - ('toysa', u"Töysä"), - ('ulvila', u"Ulvila"), - ('urjala', u"Urjala"), - ('utajarvi', u"Utajärvi"), - ('utsjoki', u"Utsjoki"), - ('uurainen', u"Uurainen"), - ('uusikaarlepyy', u"Uusikaarlepyy"), - ('uusikaupunki', u"Uusikaupunki"), - ('vaala', u"Vaala"), - ('vaasa', u"Vaasa"), - ('valkeakoski', u"Valkeakoski"), - ('valtimo', u"Valtimo"), - ('vantaa', u"Vantaa"), - ('varkaus', u"Varkaus"), - ('varpaisjarvi', u"Varpaisjärvi"), - ('vehmaa', u"Vehmaa"), - ('vesanto', u"Vesanto"), - ('vesilahti', u"Vesilahti"), - ('veteli', u"Veteli"), - ('vierema', u"Vieremä"), - ('vihanti', u"Vihanti"), - ('vihti', u"Vihti"), - ('viitasaari', u"Viitasaari"), - ('vimpeli', u"Vimpeli"), - ('virolahti', u"Virolahti"), - ('virrat', u"Virrat"), - ('vardo', u"Vårdö"), - ('vahakyro', u"Vähäkyrö"), - ('voyri-maksamaa', u"Vöyri-Maksamaa"), - ('yli-ii', u"Yli-Ii"), - ('ylitornio', u"Ylitornio"), - ('ylivieska', u"Ylivieska"), - ('ylojarvi', u"Ylöjärvi"), - ('ypaja', u"Ypäjä"), - ('ahtari', u"Ähtäri"), - ('aanekoski', u"Äänekoski") -) \ No newline at end of file + ('akaa', "Akaa"), + ('alajarvi', "Alajärvi"), + ('alavieska', "Alavieska"), + ('alavus', "Alavus"), + ('artjarvi', "Artjärvi"), + ('asikkala', "Asikkala"), + ('askola', "Askola"), + ('aura', "Aura"), + ('brando', "Brändö"), + ('eckero', "Eckerö"), + ('enonkoski', "Enonkoski"), + ('enontekio', "Enontekiö"), + ('espoo', "Espoo"), + ('eura', "Eura"), + ('eurajoki', "Eurajoki"), + ('evijarvi', "Evijärvi"), + ('finstrom', "Finström"), + ('forssa', "Forssa"), + ('foglo', "Föglö"), + ('geta', "Geta"), + ('haapajarvi', "Haapajärvi"), + ('haapavesi', "Haapavesi"), + ('hailuoto', "Hailuoto"), + ('halsua', "Halsua"), + ('hamina', "Hamina"), + ('hammarland', "Hammarland"), + ('hankasalmi', "Hankasalmi"), + ('hanko', "Hanko"), + ('harjavalta', "Harjavalta"), + ('hartola', "Hartola"), + ('hattula', "Hattula"), + ('haukipudas', "Haukipudas"), + ('hausjarvi', "Hausjärvi"), + ('heinola', "Heinola"), + ('heinavesi', "Heinävesi"), + ('helsinki', "Helsinki"), + ('hirvensalmi', "Hirvensalmi"), + ('hollola', "Hollola"), + ('honkajoki', "Honkajoki"), + ('huittinen', "Huittinen"), + ('humppila', "Humppila"), + ('hyrynsalmi', "Hyrynsalmi"), + ('hyvinkaa', "Hyvinkää"), + ('hameenkoski', "Hämeenkoski"), + ('hameenkyro', "Hämeenkyrö"), + ('hameenlinna', "Hämeenlinna"), + ('ii', "Ii"), + ('iisalmi', "Iisalmi"), + ('iitti', "Iitti"), + ('ikaalinen', "Ikaalinen"), + ('ilmajoki', "Ilmajoki"), + ('ilomantsi', "Ilomantsi"), + ('imatra', "Imatra"), + ('inari', "Inari"), + ('inkoo', "Inkoo"), + ('isojoki', "Isojoki"), + ('isokyro', "Isokyrö"), + ('jalasjarvi', "Jalasjärvi"), + ('janakkala', "Janakkala"), + ('joensuu', "Joensuu"), + ('jokioinen', "Jokioinen"), + ('jomala', "Jomala"), + ('joroinen', "Joroinen"), + ('joutsa', "Joutsa"), + ('juankoski', "Juankoski"), + ('juuka', "Juuka"), + ('juupajoki', "Juupajoki"), + ('juva', "Juva"), + ('jyvaskyla', "Jyväskylä"), + ('jamijarvi', "Jämijärvi"), + ('jamsa', "Jämsä"), + ('jarvenpaa', "Järvenpää"), + ('kaarina', "Kaarina"), + ('kaavi', "Kaavi"), + ('kajaani', "Kajaani"), + ('kalajoki', "Kalajoki"), + ('kangasala', "Kangasala"), + ('kangasniemi', "Kangasniemi"), + ('kankaanpaa', "Kankaanpää"), + ('kannonkoski', "Kannonkoski"), + ('kannus', "Kannus"), + ('karijoki', "Karijoki"), + ('karjalohja', "Karjalohja"), + ('karkkila', "Karkkila"), + ('karstula', "Karstula"), + ('karttula', "Karttula"), + ('karvia', "Karvia"), + ('kaskinen', "Kaskinen"), + ('kauhajoki', "Kauhajoki"), + ('kauhava', "Kauhava"), + ('kauniainen', "Kauniainen"), + ('kaustinen', "Kaustinen"), + ('keitele', "Keitele"), + ('kemi', "Kemi"), + ('kemijarvi', "Kemijärvi"), + ('keminmaa', "Keminmaa"), + ('kemionsaari', "Kemiönsaari"), + ('kempele', "Kempele"), + ('kerava', "Kerava"), + ('kerimaki', "Kerimäki"), + ('kesalahti', "Kesälahti"), + ('keuruu', "Keuruu"), + ('kihnio', "Kihniö"), + ('kiikoinen', "Kiikoinen"), + ('kiiminki', "Kiiminki"), + ('kinnula', "Kinnula"), + ('kirkkonummi', "Kirkkonummi"), + ('kitee', "Kitee"), + ('kittila', "Kittilä"), + ('kiuruvesi', "Kiuruvesi"), + ('kivijarvi', "Kivijärvi"), + ('kokemaki', "Kokemäki"), + ('kokkola', "Kokkola"), + ('kolari', "Kolari"), + ('konnevesi', "Konnevesi"), + ('kontiolahti', "Kontiolahti"), + ('korsnas', "Korsnäs"), + ('koskitl', "Koski Tl"), + ('kotka', "Kotka"), + ('kouvola', "Kouvola"), + ('kristiinankaupunki', "Kristiinankaupunki"), + ('kruunupyy', "Kruunupyy"), + ('kuhmalahti', "Kuhmalahti"), + ('kuhmo', "Kuhmo"), + ('kuhmoinen', "Kuhmoinen"), + ('kumlinge', "Kumlinge"), + ('kuopio', "Kuopio"), + ('kuortane', "Kuortane"), + ('kurikka', "Kurikka"), + ('kustavi', "Kustavi"), + ('kuusamo', "Kuusamo"), + ('kylmakoski', "Kylmäkoski"), + ('kyyjarvi', "Kyyjärvi"), + ('karkola', "Kärkölä"), + ('karsamaki', "Kärsämäki"), + ('kokar', "Kökar"), + ('koylio', "Köyliö"), + ('lahti', "Lahti"), + ('laihia', "Laihia"), + ('laitila', "Laitila"), + ('lapinjarvi', "Lapinjärvi"), + ('lapinlahti', "Lapinlahti"), + ('lappajarvi', "Lappajärvi"), + ('lappeenranta', "Lappeenranta"), + ('lapua', "Lapua"), + ('laukaa', "Laukaa"), + ('lavia', "Lavia"), + ('lemi', "Lemi"), + ('lemland', "Lemland"), + ('lempaala', "Lempäälä"), + ('leppavirta', "Leppävirta"), + ('lestijarvi', "Lestijärvi"), + ('lieksa', "Lieksa"), + ('lieto', "Lieto"), + ('liminka', "Liminka"), + ('liperi', "Liperi"), + ('lohja', "Lohja"), + ('loimaa', "Loimaa"), + ('loppi', "Loppi"), + ('loviisa', "Loviisa"), + ('luhanka', "Luhanka"), + ('lumijoki', "Lumijoki"), + ('lumparland', "Lumparland"), + ('luoto', "Luoto"), + ('luumaki', "Luumäki"), + ('luvia', "Luvia"), + ('lansi-turunmaa', "Länsi-Turunmaa"), + ('maalahti', "Maalahti"), + ('maaninka', "Maaninka"), + ('maarianhamina', "Maarianhamina"), + ('marttila', "Marttila"), + ('masku', "Masku"), + ('merijarvi', "Merijärvi"), + ('merikarvia', "Merikarvia"), + ('miehikkala', "Miehikkälä"), + ('mikkeli', "Mikkeli"), + ('muhos', "Muhos"), + ('multia', "Multia"), + ('muonio', "Muonio"), + ('mustasaari', "Mustasaari"), + ('muurame', "Muurame"), + ('mynamaki', "Mynämäki"), + ('myrskyla', "Myrskylä"), + ('mantsala', "Mäntsälä"), + ('mantta-vilppula', "Mänttä-Vilppula"), + ('mantyharju', "Mäntyharju"), + ('naantali', "Naantali"), + ('nakkila', "Nakkila"), + ('nastola', "Nastola"), + ('nilsia', "Nilsiä"), + ('nivala', "Nivala"), + ('nokia', "Nokia"), + ('nousiainen', "Nousiainen"), + ('nummi-pusula', "Nummi-Pusula"), + ('nurmes', "Nurmes"), + ('nurmijarvi', "Nurmijärvi"), + ('narpio', "Närpiö"), + ('oravainen', "Oravainen"), + ('orimattila', "Orimattila"), + ('oripaa', "Oripää"), + ('orivesi', "Orivesi"), + ('oulainen', "Oulainen"), + ('oulu', "Oulu"), + ('oulunsalo', "Oulunsalo"), + ('outokumpu', "Outokumpu"), + ('padasjoki', "Padasjoki"), + ('paimio', "Paimio"), + ('paltamo', "Paltamo"), + ('parikkala', "Parikkala"), + ('parkano', "Parkano"), + ('pedersore', "Pedersöre"), + ('pelkosenniemi', "Pelkosenniemi"), + ('pello', "Pello"), + ('perho', "Perho"), + ('pertunmaa', "Pertunmaa"), + ('petajavesi', "Petäjävesi"), + ('pieksamaki', "Pieksämäki"), + ('pielavesi', "Pielavesi"), + ('pietarsaari', "Pietarsaari"), + ('pihtipudas', "Pihtipudas"), + ('pirkkala', "Pirkkala"), + ('polvijarvi', "Polvijärvi"), + ('pomarkku', "Pomarkku"), + ('pori', "Pori"), + ('pornainen', "Pornainen"), + ('porvoo', "Porvoo"), + ('posio', "Posio"), + ('pudasjarvi', "Pudasjärvi"), + ('pukkila', "Pukkila"), + ('punkaharju', "Punkaharju"), + ('punkalaidun', "Punkalaidun"), + ('puolanka', "Puolanka"), + ('puumala', "Puumala"), + ('pyhtaa', "Pyhtää"), + ('pyhajoki', "Pyhäjoki"), + ('pyhajarvi', "Pyhäjärvi"), + ('pyhanta', "Pyhäntä"), + ('pyharanta', "Pyhäranta"), + ('palkane', "Pälkäne"), + ('poytya', "Pöytyä"), + ('raahe', "Raahe"), + ('raasepori', "Raasepori"), + ('raisio', "Raisio"), + ('rantasalmi', "Rantasalmi"), + ('ranua', "Ranua"), + ('rauma', "Rauma"), + ('rautalampi', "Rautalampi"), + ('rautavaara', "Rautavaara"), + ('rautjarvi', "Rautjärvi"), + ('reisjarvi', "Reisjärvi"), + ('riihimaki', "Riihimäki"), + ('ristiina', "Ristiina"), + ('ristijarvi', "Ristijärvi"), + ('rovaniemi', "Rovaniemi"), + ('ruokolahti', "Ruokolahti"), + ('ruovesi', "Ruovesi"), + ('rusko', "Rusko"), + ('raakkyla', "Rääkkylä"), + ('saarijarvi', "Saarijärvi"), + ('salla', "Salla"), + ('salo', "Salo"), + ('saltvik', "Saltvik"), + ('sastamala', "Sastamala"), + ('sauvo', "Sauvo"), + ('savitaipale', "Savitaipale"), + ('savonlinna', "Savonlinna"), + ('savukoski', "Savukoski"), + ('seinajoki', "Seinäjoki"), + ('sievi', "Sievi"), + ('siikainen', "Siikainen"), + ('siikajoki', "Siikajoki"), + ('siikalatva', "Siikalatva"), + ('siilinjarvi', "Siilinjärvi"), + ('simo', "Simo"), + ('sipoo', "Sipoo"), + ('siuntio', "Siuntio"), + ('sodankyla', "Sodankylä"), + ('soini', "Soini"), + ('somero', "Somero"), + ('sonkajarvi', "Sonkajärvi"), + ('sotkamo', "Sotkamo"), + ('sottunga', "Sottunga"), + ('sulkava', "Sulkava"), + ('sund', "Sund"), + ('suomenniemi', "Suomenniemi"), + ('suomussalmi', "Suomussalmi"), + ('suonenjoki', "Suonenjoki"), + ('sysma', "Sysmä"), + ('sakyla', "Säkylä"), + ('taipalsaari', "Taipalsaari"), + ('taivalkoski', "Taivalkoski"), + ('taivassalo', "Taivassalo"), + ('tammela', "Tammela"), + ('tampere', "Tampere"), + ('tarvasjoki', "Tarvasjoki"), + ('tervo', "Tervo"), + ('tervola', "Tervola"), + ('teuva', "Teuva"), + ('tohmajarvi', "Tohmajärvi"), + ('toholampi', "Toholampi"), + ('toivakka', "Toivakka"), + ('tornio', "Tornio"), + ('turku', "Turku"), + ('tuusniemi', "Tuusniemi"), + ('tuusula', "Tuusula"), + ('tyrnava', "Tyrnävä"), + ('toysa', "Töysä"), + ('ulvila', "Ulvila"), + ('urjala', "Urjala"), + ('utajarvi', "Utajärvi"), + ('utsjoki', "Utsjoki"), + ('uurainen', "Uurainen"), + ('uusikaarlepyy', "Uusikaarlepyy"), + ('uusikaupunki', "Uusikaupunki"), + ('vaala', "Vaala"), + ('vaasa', "Vaasa"), + ('valkeakoski', "Valkeakoski"), + ('valtimo', "Valtimo"), + ('vantaa', "Vantaa"), + ('varkaus', "Varkaus"), + ('varpaisjarvi', "Varpaisjärvi"), + ('vehmaa', "Vehmaa"), + ('vesanto', "Vesanto"), + ('vesilahti', "Vesilahti"), + ('veteli', "Veteli"), + ('vierema', "Vieremä"), + ('vihanti', "Vihanti"), + ('vihti', "Vihti"), + ('viitasaari', "Viitasaari"), + ('vimpeli', "Vimpeli"), + ('virolahti', "Virolahti"), + ('virrat', "Virrat"), + ('vardo', "Vårdö"), + ('vahakyro', "Vähäkyrö"), + ('voyri-maksamaa', "Vöyri-Maksamaa"), + ('yli-ii', "Yli-Ii"), + ('ylitornio', "Ylitornio"), + ('ylivieska', "Ylivieska"), + ('ylojarvi', "Ylöjärvi"), + ('ypaja', "Ypäjä"), + ('ahtari', "Ähtäri"), + ('aanekoski', "Äänekoski") +) diff --git a/django/contrib/localflavor/fi/forms.py b/django/contrib/localflavor/fi/forms.py index ddc3b48c54b..633f3e5f1b2 100644 --- a/django/contrib/localflavor/fi/forms.py +++ b/django/contrib/localflavor/fi/forms.py @@ -2,7 +2,7 @@ FI-specific Form helpers """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re @@ -36,7 +36,7 @@ class FISocialSecurityNumber(Field): def clean(self, value): super(FISocialSecurityNumber, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' checkmarks = "0123456789ABCDEFHJKLMNPRSTUVWXY" result = re.match(r"""^ @@ -51,5 +51,5 @@ class FISocialSecurityNumber(Field): gd = result.groupdict() checksum = int(gd['date'] + gd['serial']) if checkmarks[checksum % len(checkmarks)] == gd['checksum'].upper(): - return u'%s' % value.upper() + return '%s' % value.upper() raise ValidationError(self.error_messages['invalid']) diff --git a/django/contrib/localflavor/fr/forms.py b/django/contrib/localflavor/fr/forms.py index 34e4a96bf4f..47177db685f 100644 --- a/django/contrib/localflavor/fr/forms.py +++ b/django/contrib/localflavor/fr/forms.py @@ -1,7 +1,7 @@ """ FR-specific Form helpers """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re @@ -38,11 +38,11 @@ class FRPhoneNumberField(Field): def clean(self, value): super(FRPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = re.sub('(\.|\s)', '', smart_unicode(value)) m = phone_digits_re.search(value) if m: - return u'%s %s %s %s %s' % (value[0:2], value[2:4], value[4:6], value[6:8], value[8:10]) + return '%s %s %s %s %s' % (value[0:2], value[2:4], value[4:6], value[6:8], value[8:10]) raise ValidationError(self.error_messages['invalid']) class FRDepartmentSelect(Select): diff --git a/django/contrib/localflavor/fr/fr_department.py b/django/contrib/localflavor/fr/fr_department.py index 9f146ac8f94..a2cca957c27 100644 --- a/django/contrib/localflavor/fr/fr_department.py +++ b/django/contrib/localflavor/fr/fr_department.py @@ -1,117 +1,118 @@ # -*- coding: utf-8 -*- # See the "Code officiel géographique" on the INSEE website . +from __future__ import unicode_literals DEPARTMENT_CHOICES = ( # Metropolitan departments - ('01', u'01 - Ain'), - ('02', u'02 - Aisne'), - ('03', u'03 - Allier'), - ('04', u'04 - Alpes-de-Haute-Provence'), - ('05', u'05 - Hautes-Alpes'), - ('06', u'06 - Alpes-Maritimes'), - ('07', u'07 - Ardèche'), - ('08', u'08 - Ardennes'), - ('09', u'09 - Ariège'), - ('10', u'10 - Aube'), - ('11', u'11 - Aude'), - ('12', u'12 - Aveyron'), - ('13', u'13 - Bouches-du-Rhône'), - ('14', u'14 - Calvados'), - ('15', u'15 - Cantal'), - ('16', u'16 - Charente'), - ('17', u'17 - Charente-Maritime'), - ('18', u'18 - Cher'), - ('19', u'19 - Corrèze'), - ('2A', u'2A - Corse-du-Sud'), - ('2B', u'2B - Haute-Corse'), - ('21', u'21 - Côte-d\'Or'), - ('22', u'22 - Côtes-d\'Armor'), - ('23', u'23 - Creuse'), - ('24', u'24 - Dordogne'), - ('25', u'25 - Doubs'), - ('26', u'26 - Drôme'), - ('27', u'27 - Eure'), - ('28', u'28 - Eure-et-Loir'), - ('29', u'29 - Finistère'), - ('30', u'30 - Gard'), - ('31', u'31 - Haute-Garonne'), - ('32', u'32 - Gers'), - ('33', u'33 - Gironde'), - ('34', u'34 - Hérault'), - ('35', u'35 - Ille-et-Vilaine'), - ('36', u'36 - Indre'), - ('37', u'37 - Indre-et-Loire'), - ('38', u'38 - Isère'), - ('39', u'39 - Jura'), - ('40', u'40 - Landes'), - ('41', u'41 - Loir-et-Cher'), - ('42', u'42 - Loire'), - ('43', u'43 - Haute-Loire'), - ('44', u'44 - Loire-Atlantique'), - ('45', u'45 - Loiret'), - ('46', u'46 - Lot'), - ('47', u'47 - Lot-et-Garonne'), - ('48', u'48 - Lozère'), - ('49', u'49 - Maine-et-Loire'), - ('50', u'50 - Manche'), - ('51', u'51 - Marne'), - ('52', u'52 - Haute-Marne'), - ('53', u'53 - Mayenne'), - ('54', u'54 - Meurthe-et-Moselle'), - ('55', u'55 - Meuse'), - ('56', u'56 - Morbihan'), - ('57', u'57 - Moselle'), - ('58', u'58 - Nièvre'), - ('59', u'59 - Nord'), - ('60', u'60 - Oise'), - ('61', u'61 - Orne'), - ('62', u'62 - Pas-de-Calais'), - ('63', u'63 - Puy-de-Dôme'), - ('64', u'64 - Pyrénées-Atlantiques'), - ('65', u'65 - Hautes-Pyrénées'), - ('66', u'66 - Pyrénées-Orientales'), - ('67', u'67 - Bas-Rhin'), - ('68', u'68 - Haut-Rhin'), - ('69', u'69 - Rhône'), - ('70', u'70 - Haute-Saône'), - ('71', u'71 - Saône-et-Loire'), - ('72', u'72 - Sarthe'), - ('73', u'73 - Savoie'), - ('74', u'74 - Haute-Savoie'), - ('75', u'75 - Paris'), - ('76', u'76 - Seine-Maritime'), - ('77', u'77 - Seine-et-Marne'), - ('78', u'78 - Yvelines'), - ('79', u'79 - Deux-Sèvres'), - ('80', u'80 - Somme'), - ('81', u'81 - Tarn'), - ('82', u'82 - Tarn-et-Garonne'), - ('83', u'83 - Var'), - ('84', u'84 - Vaucluse'), - ('85', u'85 - Vendée'), - ('86', u'86 - Vienne'), - ('87', u'87 - Haute-Vienne'), - ('88', u'88 - Vosges'), - ('89', u'89 - Yonne'), - ('90', u'90 - Territoire de Belfort'), - ('91', u'91 - Essonne'), - ('92', u'92 - Hauts-de-Seine'), - ('93', u'93 - Seine-Saint-Denis'), - ('94', u'94 - Val-de-Marne'), - ('95', u'95 - Val-d\'Oise'), + ('01', '01 - Ain'), + ('02', '02 - Aisne'), + ('03', '03 - Allier'), + ('04', '04 - Alpes-de-Haute-Provence'), + ('05', '05 - Hautes-Alpes'), + ('06', '06 - Alpes-Maritimes'), + ('07', '07 - Ardèche'), + ('08', '08 - Ardennes'), + ('09', '09 - Ariège'), + ('10', '10 - Aube'), + ('11', '11 - Aude'), + ('12', '12 - Aveyron'), + ('13', '13 - Bouches-du-Rhône'), + ('14', '14 - Calvados'), + ('15', '15 - Cantal'), + ('16', '16 - Charente'), + ('17', '17 - Charente-Maritime'), + ('18', '18 - Cher'), + ('19', '19 - Corrèze'), + ('2A', '2A - Corse-du-Sud'), + ('2B', '2B - Haute-Corse'), + ('21', '21 - Côte-d\'Or'), + ('22', '22 - Côtes-d\'Armor'), + ('23', '23 - Creuse'), + ('24', '24 - Dordogne'), + ('25', '25 - Doubs'), + ('26', '26 - Drôme'), + ('27', '27 - Eure'), + ('28', '28 - Eure-et-Loir'), + ('29', '29 - Finistère'), + ('30', '30 - Gard'), + ('31', '31 - Haute-Garonne'), + ('32', '32 - Gers'), + ('33', '33 - Gironde'), + ('34', '34 - Hérault'), + ('35', '35 - Ille-et-Vilaine'), + ('36', '36 - Indre'), + ('37', '37 - Indre-et-Loire'), + ('38', '38 - Isère'), + ('39', '39 - Jura'), + ('40', '40 - Landes'), + ('41', '41 - Loir-et-Cher'), + ('42', '42 - Loire'), + ('43', '43 - Haute-Loire'), + ('44', '44 - Loire-Atlantique'), + ('45', '45 - Loiret'), + ('46', '46 - Lot'), + ('47', '47 - Lot-et-Garonne'), + ('48', '48 - Lozère'), + ('49', '49 - Maine-et-Loire'), + ('50', '50 - Manche'), + ('51', '51 - Marne'), + ('52', '52 - Haute-Marne'), + ('53', '53 - Mayenne'), + ('54', '54 - Meurthe-et-Moselle'), + ('55', '55 - Meuse'), + ('56', '56 - Morbihan'), + ('57', '57 - Moselle'), + ('58', '58 - Nièvre'), + ('59', '59 - Nord'), + ('60', '60 - Oise'), + ('61', '61 - Orne'), + ('62', '62 - Pas-de-Calais'), + ('63', '63 - Puy-de-Dôme'), + ('64', '64 - Pyrénées-Atlantiques'), + ('65', '65 - Hautes-Pyrénées'), + ('66', '66 - Pyrénées-Orientales'), + ('67', '67 - Bas-Rhin'), + ('68', '68 - Haut-Rhin'), + ('69', '69 - Rhône'), + ('70', '70 - Haute-Saône'), + ('71', '71 - Saône-et-Loire'), + ('72', '72 - Sarthe'), + ('73', '73 - Savoie'), + ('74', '74 - Haute-Savoie'), + ('75', '75 - Paris'), + ('76', '76 - Seine-Maritime'), + ('77', '77 - Seine-et-Marne'), + ('78', '78 - Yvelines'), + ('79', '79 - Deux-Sèvres'), + ('80', '80 - Somme'), + ('81', '81 - Tarn'), + ('82', '82 - Tarn-et-Garonne'), + ('83', '83 - Var'), + ('84', '84 - Vaucluse'), + ('85', '85 - Vendée'), + ('86', '86 - Vienne'), + ('87', '87 - Haute-Vienne'), + ('88', '88 - Vosges'), + ('89', '89 - Yonne'), + ('90', '90 - Territoire de Belfort'), + ('91', '91 - Essonne'), + ('92', '92 - Hauts-de-Seine'), + ('93', '93 - Seine-Saint-Denis'), + ('94', '94 - Val-de-Marne'), + ('95', '95 - Val-d\'Oise'), # Overseas departments, communities, and other territories - ('971', u'971 - Guadeloupe'), - ('972', u'972 - Martinique'), - ('973', u'973 - Guyane'), - ('974', u'974 - La Réunion'), - ('975', u'975 - Saint-Pierre-et-Miquelon'), - ('976', u'976 - Mayotte'), - ('977', u'977 - Saint-Barthélemy'), - ('978', u'978 - Saint-Martin'), - ('984', u'984 - Terres australes et antarctiques françaises'), - ('986', u'986 - Wallis et Futuna'), - ('987', u'987 - Polynésie française'), - ('988', u'988 - Nouvelle-Calédonie'), - ('989', u'989 - Île de Clipperton'), + ('971', '971 - Guadeloupe'), + ('972', '972 - Martinique'), + ('973', '973 - Guyane'), + ('974', '974 - La Réunion'), + ('975', '975 - Saint-Pierre-et-Miquelon'), + ('976', '976 - Mayotte'), + ('977', '977 - Saint-Barthélemy'), + ('978', '978 - Saint-Martin'), + ('984', '984 - Terres australes et antarctiques françaises'), + ('986', '986 - Wallis et Futuna'), + ('987', '987 - Polynésie française'), + ('988', '988 - Nouvelle-Calédonie'), + ('989', '989 - Île de Clipperton'), ) diff --git a/django/contrib/localflavor/gb/forms.py b/django/contrib/localflavor/gb/forms.py index a6658578b1f..bf90f802812 100644 --- a/django/contrib/localflavor/gb/forms.py +++ b/django/contrib/localflavor/gb/forms.py @@ -2,7 +2,7 @@ GB-specific Form helpers """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re @@ -22,7 +22,7 @@ class GBPostcodeField(CharField): The value is uppercased and a space added in the correct place, if required. """ default_error_messages = { - 'invalid': _(u'Enter a valid postcode.'), + 'invalid': _('Enter a valid postcode.'), } outcode_pattern = '[A-PR-UWYZ]([0-9]{1,2}|([A-HIK-Y][0-9](|[0-9]|[ABEHMNPRVWXY]))|[0-9][A-HJKSTUW])' incode_pattern = '[0-9][ABD-HJLNP-UW-Z]{2}' @@ -31,7 +31,7 @@ class GBPostcodeField(CharField): def clean(self, value): value = super(GBPostcodeField, self).clean(value) - if value == u'': + if value == '': return value postcode = value.upper().strip() # Put a single space before the incode (second part). diff --git a/django/contrib/localflavor/hk/forms.py b/django/contrib/localflavor/hk/forms.py index 852ef7d4b21..8cf9360e198 100644 --- a/django/contrib/localflavor/hk/forms.py +++ b/django/contrib/localflavor/hk/forms.py @@ -1,7 +1,7 @@ """ Hong Kong specific Form helpers """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re @@ -51,14 +51,14 @@ class HKPhoneNumberField(CharField): super(HKPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = re.sub('(\(|\)|\s+|\+)', '', smart_unicode(value)) m = hk_phone_digits_re.search(value) if not m: raise ValidationError(self.error_messages['invalid']) - value = u'%s-%s' % (m.group(1), m.group(2)) + value = '%s-%s' % (m.group(1), m.group(2)) for special in hk_special_numbers: if value.startswith(special): raise ValidationError(self.error_messages['disguise']) diff --git a/django/contrib/localflavor/hr/forms.py b/django/contrib/localflavor/hr/forms.py index 0ff283d6c83..eb4436a78c5 100644 --- a/django/contrib/localflavor/hr/forms.py +++ b/django/contrib/localflavor/hr/forms.py @@ -2,7 +2,7 @@ """ HR-specific Form helpers """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re @@ -19,8 +19,8 @@ from django.utils.translation import ugettext_lazy as _ jmbg_re = re.compile(r'^(?P
    \d{2})(?P\d{2})(?P\d{3})' + \ r'(?P\d{2})(?P\d{3})(?P\d{1})$') oib_re = re.compile(r'^\d{11}$') -plate_re = re.compile(ur'^(?P[A-ZČŠŽ]{2})' + \ - ur'(?P\d{3,4})(?P[ABCDEFGHIJKLMNOPRSTUVZ]{1,2})$') +plate_re = re.compile(r'^(?P[A-ZČŠŽ]{2})' + \ + r'(?P\d{3,4})(?P[ABCDEFGHIJKLMNOPRSTUVZ]{1,2})$') postal_code_re = re.compile(r'^\d{5}$') phone_re = re.compile(r'^(\+385|00385|0)(?P\d{2})(?P\d{6,7})$') jmbag_re = re.compile(r'^601983(?P\d{1})1(?P\d{10})(?P\d{1})$') @@ -79,7 +79,7 @@ class HRJMBGField(Field): def clean(self, value): super(HRJMBGField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = value.strip() @@ -110,7 +110,7 @@ class HRJMBGField(Field): if not str(m) == k: raise ValidationError(self.error_messages['invalid']) - return u'%s' % (value, ) + return '%s' % (value, ) class HROIBField(RegexField): @@ -130,7 +130,7 @@ class HROIBField(RegexField): def clean(self, value): super(HROIBField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' return '%s' % (value, ) @@ -157,7 +157,7 @@ class HRLicensePlateField(Field): def clean(self, value): super(HRLicensePlateField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = re.sub(r'[\s\-]+', '', smart_unicode(value.strip())).upper() @@ -175,7 +175,7 @@ class HRLicensePlateField(Field): if int(number) == 0: raise ValidationError(self.error_messages['number']) - return u'%s %s-%s' % (prefix,number,matches.group('suffix'), ) + return '%s %s-%s' % (prefix,number,matches.group('suffix'), ) class HRPostalCodeField(Field): @@ -193,7 +193,7 @@ class HRPostalCodeField(Field): def clean(self, value): super(HRPostalCodeField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = value.strip() if not postal_code_re.search(value): @@ -223,7 +223,7 @@ class HRPhoneNumberField(Field): def clean(self, value): super(HRPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = re.sub(r'[\-\s\(\)]', '', smart_unicode(value)) @@ -262,7 +262,7 @@ class HRJMBAGField(Field): def clean(self, value): super(HRJMBAGField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = re.sub(r'[\-\s]', '', value.strip()) diff --git a/django/contrib/localflavor/hr/hr_choices.py b/django/contrib/localflavor/hr/hr_choices.py index 24d3d42c5be..beb2969405a 100644 --- a/django/contrib/localflavor/hr/hr_choices.py +++ b/django/contrib/localflavor/hr/hr_choices.py @@ -6,30 +6,32 @@ Sources: Croatia doesn't have official abbreviations for counties. The ones provided are in common use. """ +from __future__ import unicode_literals + from django.utils.translation import ugettext_lazy as _ HR_COUNTY_CHOICES = ( ('GZG', _('Grad Zagreb')), - (u'BBŽ', _(u'Bjelovarsko-bilogorska županija')), - (u'BPŽ', _(u'Brodsko-posavska županija')), - (u'DNŽ', _(u'Dubrovačko-neretvanska županija')), - (u'IŽ', _(u'Istarska županija')), - (u'KŽ', _(u'Karlovačka županija')), - (u'KKŽ', _(u'Koprivničko-križevačka županija')), - (u'KZŽ', _(u'Krapinsko-zagorska županija')), - (u'LSŽ', _(u'Ličko-senjska županija')), - (u'MŽ', _(u'Međimurska županija')), - (u'OBŽ', _(u'Osječko-baranjska županija')), - (u'PSŽ', _(u'Požeško-slavonska županija')), - (u'PGŽ', _(u'Primorsko-goranska županija')), - (u'SMŽ', _(u'Sisačko-moslavačka županija')), - (u'SDŽ', _(u'Splitsko-dalmatinska županija')), - (u'ŠKŽ', _(u'Šibensko-kninska županija')), - (u'VŽ', _(u'Varaždinska županija')), - (u'VPŽ', _(u'Virovitičko-podravska županija')), - (u'VSŽ', _(u'Vukovarsko-srijemska županija')), - (u'ZDŽ', _(u'Zadarska županija')), - (u'ZGŽ', _(u'Zagrebačka županija')), + ('BBŽ', _('Bjelovarsko-bilogorska županija')), + ('BPŽ', _('Brodsko-posavska županija')), + ('DNŽ', _('Dubrovačko-neretvanska županija')), + ('IŽ', _('Istarska županija')), + ('KŽ', _('Karlovačka županija')), + ('KKŽ', _('Koprivničko-križevačka županija')), + ('KZŽ', _('Krapinsko-zagorska županija')), + ('LSŽ', _('Ličko-senjska županija')), + ('MŽ', _('Međimurska županija')), + ('OBŽ', _('Osječko-baranjska županija')), + ('PSŽ', _('Požeško-slavonska županija')), + ('PGŽ', _('Primorsko-goranska županija')), + ('SMŽ', _('Sisačko-moslavačka županija')), + ('SDŽ', _('Splitsko-dalmatinska županija')), + ('ŠKŽ', _('Šibensko-kninska županija')), + ('VŽ', _('Varaždinska županija')), + ('VPŽ', _('Virovitičko-podravska županija')), + ('VSŽ', _('Vukovarsko-srijemska županija')), + ('ZDŽ', _('Zadarska županija')), + ('ZGŽ', _('Zagrebačka županija')), ) """ @@ -42,7 +44,7 @@ Only common license plate prefixes are provided. Special cases and obsolete pref HR_LICENSE_PLATE_PREFIX_CHOICES = ( ('BJ', 'BJ'), ('BM', 'BM'), - (u'ČK', u'ČK'), + ('ČK', 'ČK'), ('DA', 'DA'), ('DE', 'DE'), ('DJ', 'DJ'), @@ -53,27 +55,27 @@ HR_LICENSE_PLATE_PREFIX_CHOICES = ( ('KC', 'KC'), ('KR', 'KR'), ('KT', 'KT'), - (u'KŽ', u'KŽ'), + ('KŽ', 'KŽ'), ('MA', 'MA'), ('NA', 'NA'), ('NG', 'NG'), ('OG', 'OG'), ('OS', 'OS'), ('PU', 'PU'), - (u'PŽ', u'PŽ'), + ('PŽ', 'PŽ'), ('RI', 'RI'), ('SB', 'SB'), ('SK', 'SK'), ('SL', 'SL'), ('ST', 'ST'), - (u'ŠI', u'ŠI'), + ('ŠI', 'ŠI'), ('VK', 'VK'), ('VT', 'VT'), ('VU', 'VU'), - (u'VŽ', u'VŽ'), + ('VŽ', 'VŽ'), ('ZD', 'ZD'), ('ZG', 'ZG'), - (u'ŽU', u'ŽU'), + ('ŽU', 'ŽU'), ) """ diff --git a/django/contrib/localflavor/id/forms.py b/django/contrib/localflavor/id/forms.py index 9439dba5942..f22b06134e8 100644 --- a/django/contrib/localflavor/id/forms.py +++ b/django/contrib/localflavor/id/forms.py @@ -2,7 +2,7 @@ ID-specific Form helpers """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re import time @@ -34,7 +34,7 @@ class IDPostCodeField(Field): def clean(self, value): super(IDPostCodeField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = value.strip() if not postcode_re.search(value): @@ -47,7 +47,7 @@ class IDPostCodeField(Field): if value[0] == '1' and value[4] != '0': raise ValidationError(self.error_messages['invalid']) - return u'%s' % (value, ) + return '%s' % (value, ) class IDProvinceSelect(Select): @@ -75,7 +75,7 @@ class IDPhoneNumberField(Field): def clean(self, value): super(IDPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' phone_number = re.sub(r'[\-\s\(\)]', '', smart_unicode(value)) @@ -117,7 +117,7 @@ class IDLicensePlateField(Field): from django.contrib.localflavor.id.id_choices import LICENSE_PLATE_PREFIX_CHOICES super(IDLicensePlateField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' plate_number = re.sub(r'\s+', ' ', smart_unicode(value.strip())).upper() @@ -179,7 +179,7 @@ class IDNationalIdentityNumberField(Field): def clean(self, value): super(IDNationalIdentityNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = re.sub(r'[\s.]', '', smart_unicode(value)) diff --git a/django/contrib/localflavor/il/forms.py b/django/contrib/localflavor/il/forms.py index a14358737eb..de6ba6b23d4 100644 --- a/django/contrib/localflavor/il/forms.py +++ b/django/contrib/localflavor/il/forms.py @@ -1,6 +1,7 @@ """ Israeli-specific form helpers """ +from __future__ import unicode_literals import re from django.core.exceptions import ValidationError @@ -28,7 +29,7 @@ class ILPostalCodeField(RegexField): """ default_error_messages = { - 'invalid': _(u'Enter a postal code in the format XXXXX'), + 'invalid': _('Enter a postal code in the format XXXXX'), } def __init__(self, *args, **kwargs): @@ -47,14 +48,14 @@ class ILIDNumberField(Field): """ default_error_messages = { - 'invalid': _(u'Enter a valid ID number.'), + 'invalid': _('Enter a valid ID number.'), } def clean(self, value): value = super(ILIDNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' match = id_number_re.match(value) if not match: diff --git a/django/contrib/localflavor/in_/forms.py b/django/contrib/localflavor/in_/forms.py index 11011e1df22..b62ec7bdb24 100644 --- a/django/contrib/localflavor/in_/forms.py +++ b/django/contrib/localflavor/in_/forms.py @@ -2,7 +2,7 @@ India-specific Form helpers. """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re @@ -38,7 +38,7 @@ phone_digits_re = re.compile(r""" class INZipCodeField(RegexField): default_error_messages = { - 'invalid': _(u'Enter a zip code in the format XXXXXX or XXX XXX.'), + 'invalid': _('Enter a zip code in the format XXXXXX or XXX XXX.'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): @@ -48,7 +48,7 @@ class INZipCodeField(RegexField): def clean(self, value): super(INZipCodeField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' # Convert to "NNNNNN" if "NNN NNN" given value = re.sub(r'^(\d{3})\s(\d{3})$', r'\1\2', value) return value @@ -61,13 +61,13 @@ class INStateField(Field): registration abbreviation for the given state or union territory """ default_error_messages = { - 'invalid': _(u'Enter an Indian state or territory.'), + 'invalid': _('Enter an Indian state or territory.'), } def clean(self, value): super(INStateField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' try: value = value.strip().lower() except AttributeError: @@ -106,10 +106,10 @@ class INPhoneNumberField(CharField): def clean(self, value): super(INPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = smart_unicode(value) m = phone_digits_re.match(value) if m: - return u'%s' % (value) + return '%s' % (value) raise ValidationError(self.error_messages['invalid']) diff --git a/django/contrib/localflavor/is_/forms.py b/django/contrib/localflavor/is_/forms.py index ca7bd5004eb..7af9f51cfbd 100644 --- a/django/contrib/localflavor/is_/forms.py +++ b/django/contrib/localflavor/is_/forms.py @@ -2,7 +2,7 @@ Iceland specific form helpers. """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from django.contrib.localflavor.is_.is_postalcodes import IS_POSTALCODES from django.core.validators import EMPTY_VALUES @@ -20,7 +20,7 @@ class ISIdNumberField(RegexField): """ default_error_messages = { 'invalid': _('Enter a valid Icelandic identification number. The format is XXXXXX-XXXX.'), - 'checksum': _(u'The Icelandic identification number is not valid.'), + 'checksum': _('The Icelandic identification number is not valid.'), } def __init__(self, max_length=11, min_length=10, *args, **kwargs): @@ -31,7 +31,7 @@ class ISIdNumberField(RegexField): value = super(ISIdNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = self._canonify(value) if self._validate(value): @@ -73,7 +73,7 @@ class ISPhoneNumberField(RegexField): value = super(ISPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' return value.replace('-', '').replace(' ', '') diff --git a/django/contrib/localflavor/is_/is_postalcodes.py b/django/contrib/localflavor/is_/is_postalcodes.py index 4feca9c0131..f1f3357c1c5 100644 --- a/django/contrib/localflavor/is_/is_postalcodes.py +++ b/django/contrib/localflavor/is_/is_postalcodes.py @@ -1,151 +1,152 @@ # -*- coding: utf-8 -*- +from __future__ import unicode_literals IS_POSTALCODES = ( - ('101', u'101 Reykjavík'), - ('103', u'103 Reykjavík'), - ('104', u'104 Reykjavík'), - ('105', u'105 Reykjavík'), - ('107', u'107 Reykjavík'), - ('108', u'108 Reykjavík'), - ('109', u'109 Reykjavík'), - ('110', u'110 Reykjavík'), - ('111', u'111 Reykjavík'), - ('112', u'112 Reykjavík'), - ('113', u'113 Reykjavík'), - ('116', u'116 Kjalarnes'), - ('121', u'121 Reykjavík'), - ('123', u'123 Reykjavík'), - ('124', u'124 Reykjavík'), - ('125', u'125 Reykjavík'), - ('127', u'127 Reykjavík'), - ('128', u'128 Reykjavík'), - ('129', u'129 Reykjavík'), - ('130', u'130 Reykjavík'), - ('132', u'132 Reykjavík'), - ('150', u'150 Reykjavík'), - ('155', u'155 Reykjavík'), - ('170', u'170 Seltjarnarnes'), - ('172', u'172 Seltjarnarnes'), - ('190', u'190 Vogar'), - ('200', u'200 Kópavogur'), - ('201', u'201 Kópavogur'), - ('202', u'202 Kópavogur'), - ('203', u'203 Kópavogur'), - ('210', u'210 Garðabær'), - ('212', u'212 Garðabær'), - ('220', u'220 Hafnarfjörður'), - ('221', u'221 Hafnarfjörður'), - ('222', u'222 Hafnarfjörður'), - ('225', u'225 Álftanes'), - ('230', u'230 Reykjanesbær'), - ('232', u'232 Reykjanesbær'), - ('233', u'233 Reykjanesbær'), - ('235', u'235 Keflavíkurflugvöllur'), - ('240', u'240 Grindavík'), - ('245', u'245 Sandgerði'), - ('250', u'250 Garður'), - ('260', u'260 Reykjanesbær'), - ('270', u'270 Mosfellsbær'), - ('300', u'300 Akranes'), - ('301', u'301 Akranes'), - ('302', u'302 Akranes'), - ('310', u'310 Borgarnes'), - ('311', u'311 Borgarnes'), - ('320', u'320 Reykholt í Borgarfirði'), - ('340', u'340 Stykkishólmur'), - ('345', u'345 Flatey á Breiðafirði'), - ('350', u'350 Grundarfjörður'), - ('355', u'355 Ólafsvík'), - ('356', u'356 Snæfellsbær'), - ('360', u'360 Hellissandur'), - ('370', u'370 Búðardalur'), - ('371', u'371 Búðardalur'), - ('380', u'380 Reykhólahreppur'), - ('400', u'400 Ísafjörður'), - ('401', u'401 Ísafjörður'), - ('410', u'410 Hnífsdalur'), - ('415', u'415 Bolungarvík'), - ('420', u'420 Súðavík'), - ('425', u'425 Flateyri'), - ('430', u'430 Suðureyri'), - ('450', u'450 Patreksfjörður'), - ('451', u'451 Patreksfjörður'), - ('460', u'460 Tálknafjörður'), - ('465', u'465 Bíldudalur'), - ('470', u'470 Þingeyri'), - ('471', u'471 Þingeyri'), - ('500', u'500 Staður'), - ('510', u'510 Hólmavík'), - ('512', u'512 Hólmavík'), - ('520', u'520 Drangsnes'), - ('522', u'522 Kjörvogur'), - ('523', u'523 Bær'), - ('524', u'524 Norðurfjörður'), - ('530', u'530 Hvammstangi'), - ('531', u'531 Hvammstangi'), - ('540', u'540 Blönduós'), - ('541', u'541 Blönduós'), - ('545', u'545 Skagaströnd'), - ('550', u'550 Sauðárkrókur'), - ('551', u'551 Sauðárkrókur'), - ('560', u'560 Varmahlíð'), - ('565', u'565 Hofsós'), - ('566', u'566 Hofsós'), - ('570', u'570 Fljót'), - ('580', u'580 Siglufjörður'), - ('600', u'600 Akureyri'), - ('601', u'601 Akureyri'), - ('602', u'602 Akureyri'), - ('603', u'603 Akureyri'), - ('610', u'610 Grenivík'), - ('611', u'611 Grímsey'), - ('620', u'620 Dalvík'), - ('621', u'621 Dalvík'), - ('625', u'625 Ólafsfjörður'), - ('630', u'630 Hrísey'), - ('640', u'640 Húsavík'), - ('641', u'641 Húsavík'), - ('645', u'645 Fosshóll'), - ('650', u'650 Laugar'), - ('660', u'660 Mývatn'), - ('670', u'670 Kópasker'), - ('671', u'671 Kópasker'), - ('675', u'675 Raufarhöfn'), - ('680', u'680 Þórshöfn'), - ('681', u'681 Þórshöfn'), - ('685', u'685 Bakkafjörður'), - ('690', u'690 Vopnafjörður'), - ('700', u'700 Egilsstaðir'), - ('701', u'701 Egilsstaðir'), - ('710', u'710 Seyðisfjörður'), - ('715', u'715 Mjóifjörður'), - ('720', u'720 Borgarfjörður eystri'), - ('730', u'730 Reyðarfjörður'), - ('735', u'735 Eskifjörður'), - ('740', u'740 Neskaupstaður'), - ('750', u'750 Fáskrúðsfjörður'), - ('755', u'755 Stöðvarfjörður'), - ('760', u'760 Breiðdalsvík'), - ('765', u'765 Djúpivogur'), - ('780', u'780 Höfn í Hornafirði'), - ('781', u'781 Höfn í Hornafirði'), - ('785', u'785 Öræfi'), - ('800', u'800 Selfoss'), - ('801', u'801 Selfoss'), - ('802', u'802 Selfoss'), - ('810', u'810 Hveragerði'), - ('815', u'815 Þorlákshöfn'), - ('820', u'820 Eyrarbakki'), - ('825', u'825 Stokkseyri'), - ('840', u'840 Laugarvatn'), - ('845', u'845 Flúðir'), - ('850', u'850 Hella'), - ('851', u'851 Hella'), - ('860', u'860 Hvolsvöllur'), - ('861', u'861 Hvolsvöllur'), - ('870', u'870 Vík'), - ('871', u'871 Vík'), - ('880', u'880 Kirkjubæjarklaustur'), - ('900', u'900 Vestmannaeyjar'), - ('902', u'902 Vestmannaeyjar') + ('101', '101 Reykjavík'), + ('103', '103 Reykjavík'), + ('104', '104 Reykjavík'), + ('105', '105 Reykjavík'), + ('107', '107 Reykjavík'), + ('108', '108 Reykjavík'), + ('109', '109 Reykjavík'), + ('110', '110 Reykjavík'), + ('111', '111 Reykjavík'), + ('112', '112 Reykjavík'), + ('113', '113 Reykjavík'), + ('116', '116 Kjalarnes'), + ('121', '121 Reykjavík'), + ('123', '123 Reykjavík'), + ('124', '124 Reykjavík'), + ('125', '125 Reykjavík'), + ('127', '127 Reykjavík'), + ('128', '128 Reykjavík'), + ('129', '129 Reykjavík'), + ('130', '130 Reykjavík'), + ('132', '132 Reykjavík'), + ('150', '150 Reykjavík'), + ('155', '155 Reykjavík'), + ('170', '170 Seltjarnarnes'), + ('172', '172 Seltjarnarnes'), + ('190', '190 Vogar'), + ('200', '200 Kópavogur'), + ('201', '201 Kópavogur'), + ('202', '202 Kópavogur'), + ('203', '203 Kópavogur'), + ('210', '210 Garðabær'), + ('212', '212 Garðabær'), + ('220', '220 Hafnarfjörður'), + ('221', '221 Hafnarfjörður'), + ('222', '222 Hafnarfjörður'), + ('225', '225 Álftanes'), + ('230', '230 Reykjanesbær'), + ('232', '232 Reykjanesbær'), + ('233', '233 Reykjanesbær'), + ('235', '235 Keflavíkurflugvöllur'), + ('240', '240 Grindavík'), + ('245', '245 Sandgerði'), + ('250', '250 Garður'), + ('260', '260 Reykjanesbær'), + ('270', '270 Mosfellsbær'), + ('300', '300 Akranes'), + ('301', '301 Akranes'), + ('302', '302 Akranes'), + ('310', '310 Borgarnes'), + ('311', '311 Borgarnes'), + ('320', '320 Reykholt í Borgarfirði'), + ('340', '340 Stykkishólmur'), + ('345', '345 Flatey á Breiðafirði'), + ('350', '350 Grundarfjörður'), + ('355', '355 Ólafsvík'), + ('356', '356 Snæfellsbær'), + ('360', '360 Hellissandur'), + ('370', '370 Búðardalur'), + ('371', '371 Búðardalur'), + ('380', '380 Reykhólahreppur'), + ('400', '400 Ísafjörður'), + ('401', '401 Ísafjörður'), + ('410', '410 Hnífsdalur'), + ('415', '415 Bolungarvík'), + ('420', '420 Súðavík'), + ('425', '425 Flateyri'), + ('430', '430 Suðureyri'), + ('450', '450 Patreksfjörður'), + ('451', '451 Patreksfjörður'), + ('460', '460 Tálknafjörður'), + ('465', '465 Bíldudalur'), + ('470', '470 Þingeyri'), + ('471', '471 Þingeyri'), + ('500', '500 Staður'), + ('510', '510 Hólmavík'), + ('512', '512 Hólmavík'), + ('520', '520 Drangsnes'), + ('522', '522 Kjörvogur'), + ('523', '523 Bær'), + ('524', '524 Norðurfjörður'), + ('530', '530 Hvammstangi'), + ('531', '531 Hvammstangi'), + ('540', '540 Blönduós'), + ('541', '541 Blönduós'), + ('545', '545 Skagaströnd'), + ('550', '550 Sauðárkrókur'), + ('551', '551 Sauðárkrókur'), + ('560', '560 Varmahlíð'), + ('565', '565 Hofsós'), + ('566', '566 Hofsós'), + ('570', '570 Fljót'), + ('580', '580 Siglufjörður'), + ('600', '600 Akureyri'), + ('601', '601 Akureyri'), + ('602', '602 Akureyri'), + ('603', '603 Akureyri'), + ('610', '610 Grenivík'), + ('611', '611 Grímsey'), + ('620', '620 Dalvík'), + ('621', '621 Dalvík'), + ('625', '625 Ólafsfjörður'), + ('630', '630 Hrísey'), + ('640', '640 Húsavík'), + ('641', '641 Húsavík'), + ('645', '645 Fosshóll'), + ('650', '650 Laugar'), + ('660', '660 Mývatn'), + ('670', '670 Kópasker'), + ('671', '671 Kópasker'), + ('675', '675 Raufarhöfn'), + ('680', '680 Þórshöfn'), + ('681', '681 Þórshöfn'), + ('685', '685 Bakkafjörður'), + ('690', '690 Vopnafjörður'), + ('700', '700 Egilsstaðir'), + ('701', '701 Egilsstaðir'), + ('710', '710 Seyðisfjörður'), + ('715', '715 Mjóifjörður'), + ('720', '720 Borgarfjörður eystri'), + ('730', '730 Reyðarfjörður'), + ('735', '735 Eskifjörður'), + ('740', '740 Neskaupstaður'), + ('750', '750 Fáskrúðsfjörður'), + ('755', '755 Stöðvarfjörður'), + ('760', '760 Breiðdalsvík'), + ('765', '765 Djúpivogur'), + ('780', '780 Höfn í Hornafirði'), + ('781', '781 Höfn í Hornafirði'), + ('785', '785 Öræfi'), + ('800', '800 Selfoss'), + ('801', '801 Selfoss'), + ('802', '802 Selfoss'), + ('810', '810 Hveragerði'), + ('815', '815 Þorlákshöfn'), + ('820', '820 Eyrarbakki'), + ('825', '825 Stokkseyri'), + ('840', '840 Laugarvatn'), + ('845', '845 Flúðir'), + ('850', '850 Hella'), + ('851', '851 Hella'), + ('860', '860 Hvolsvöllur'), + ('861', '861 Hvolsvöllur'), + ('870', '870 Vík'), + ('871', '871 Vík'), + ('880', '880 Kirkjubæjarklaustur'), + ('900', '900 Vestmannaeyjar'), + ('902', '902 Vestmannaeyjar') ) diff --git a/django/contrib/localflavor/it/forms.py b/django/contrib/localflavor/it/forms.py index 0060b486bdc..60b1eff951e 100644 --- a/django/contrib/localflavor/it/forms.py +++ b/django/contrib/localflavor/it/forms.py @@ -2,7 +2,7 @@ IT-specific Form helpers """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re @@ -45,7 +45,7 @@ class ITSocialSecurityNumberField(RegexField): 'Informazioni sulla codificazione delle persone fisiche'. """ default_error_messages = { - 'invalid': _(u'Enter a valid Social Security number.'), + 'invalid': _('Enter a valid Social Security number.'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): @@ -55,8 +55,8 @@ class ITSocialSecurityNumberField(RegexField): def clean(self, value): value = super(ITSocialSecurityNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' - value = re.sub('\s', u'', value).upper() + return '' + value = re.sub('\s', '', value).upper() try: check_digit = ssn_check_digit(value) except ValueError: @@ -70,13 +70,13 @@ class ITVatNumberField(Field): A form field that validates Italian VAT numbers (partita IVA). """ default_error_messages = { - 'invalid': _(u'Enter a valid VAT number.'), + 'invalid': _('Enter a valid VAT number.'), } def clean(self, value): value = super(ITVatNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' try: vat_number = int(value) except ValueError: diff --git a/django/contrib/localflavor/it/it_province.py b/django/contrib/localflavor/it/it_province.py index dcaad98c63f..5aad1611dda 100644 --- a/django/contrib/localflavor/it/it_province.py +++ b/django/contrib/localflavor/it/it_province.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -* +from __future__ import unicode_literals PROVINCE_CHOICES = ( ('AG', 'Agrigento'), @@ -45,7 +46,7 @@ PROVINCE_CHOICES = ( ('IM', 'Imperia'), ('IS', 'Isernia'), ('SP', 'La Spezia'), - ('AQ', u'L’Aquila'), + ('AQ', 'L’Aquila'), ('LT', 'Latina'), ('LE', 'Lecce'), ('LC', 'Lecco'), diff --git a/django/contrib/localflavor/it/it_region.py b/django/contrib/localflavor/it/it_region.py index 0700b46ea8e..e12a1e731b4 100644 --- a/django/contrib/localflavor/it/it_region.py +++ b/django/contrib/localflavor/it/it_region.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -* +from __future__ import unicode_literals REGION_CHOICES = ( ('ABR', 'Abruzzo'), @@ -19,6 +20,6 @@ REGION_CHOICES = ( ('TOS', 'Toscana'), ('TAA', 'Trentino-Alto Adige'), ('UMB', 'Umbria'), - ('VAO', u'Valle d’Aosta'), + ('VAO', 'Valle d’Aosta'), ('VEN', 'Veneto'), ) diff --git a/django/contrib/localflavor/it/util.py b/django/contrib/localflavor/it/util.py index c162ff7effa..ec1b7e3f83a 100644 --- a/django/contrib/localflavor/it/util.py +++ b/django/contrib/localflavor/it/util.py @@ -1,4 +1,4 @@ -from django.utils.encoding import smart_str, smart_unicode +from django.utils.encoding import smart_unicode def ssn_check_digit(value): "Calculate Italian social security number check digit." @@ -34,7 +34,7 @@ def ssn_check_digit(value): def vat_number_check_digit(vat_number): "Calculate Italian VAT number check digit." - normalized_vat_number = smart_str(vat_number).zfill(10) + normalized_vat_number = smart_unicode(vat_number).zfill(10) total = 0 for i in range(0, 10, 2): total += int(normalized_vat_number[i]) diff --git a/django/contrib/localflavor/kw/forms.py b/django/contrib/localflavor/kw/forms.py index e671408ec8c..2c2b023e701 100644 --- a/django/contrib/localflavor/kw/forms.py +++ b/django/contrib/localflavor/kw/forms.py @@ -1,6 +1,8 @@ """ Kuwait-specific Form helpers """ +from __future__ import unicode_literals + import re from datetime import date @@ -40,7 +42,7 @@ class KWCivilIDNumberField(Field): def clean(self, value): super(KWCivilIDNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' if not re.match(r'^\d{12}$', value): raise ValidationError(self.error_messages['invalid']) diff --git a/django/contrib/localflavor/mk/forms.py b/django/contrib/localflavor/mk/forms.py index 33dbfc71a0f..3189f0dec6d 100644 --- a/django/contrib/localflavor/mk/forms.py +++ b/django/contrib/localflavor/mk/forms.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import datetime @@ -15,14 +15,14 @@ class MKIdentityCardNumberField(RegexField): A Macedonian ID card number. Accepts both old and new format. """ default_error_messages = { - 'invalid': _(u'Identity card numbers must contain' + 'invalid': _('Identity card numbers must contain' ' either 4 to 7 digits or an uppercase letter and 7 digits.'), } def __init__(self, *args, **kwargs): kwargs['min_length'] = None kwargs['max_length'] = 8 - regex = ur'(^[A-Z]{1}\d{7}$)|(^\d{4,7}$)' + regex = r'(^[A-Z]{1}\d{7}$)|(^\d{4,7}$)' super(MKIdentityCardNumberField, self).__init__(regex, *args, **kwargs) @@ -54,9 +54,9 @@ class UMCNField(RegexField): * The last digit of the UMCN passes a checksum test """ default_error_messages = { - 'invalid': _(u'This field should contain exactly 13 digits.'), - 'date': _(u'The first 7 digits of the UMCN must represent a valid past date.'), - 'checksum': _(u'The UMCN is not valid.'), + 'invalid': _('This field should contain exactly 13 digits.'), + 'date': _('The first 7 digits of the UMCN must represent a valid past date.'), + 'checksum': _('The UMCN is not valid.'), } def __init__(self, *args, **kwargs): @@ -68,7 +68,7 @@ class UMCNField(RegexField): value = super(UMCNField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' if not self._validate_date_part(value): raise ValidationError(self.error_messages['date']) diff --git a/django/contrib/localflavor/mk/mk_choices.py b/django/contrib/localflavor/mk/mk_choices.py index d6d1efa0491..fb705ca820a 100644 --- a/django/contrib/localflavor/mk/mk_choices.py +++ b/django/contrib/localflavor/mk/mk_choices.py @@ -2,91 +2,93 @@ """ Macedonian municipalities per the reorganization from 2004. """ +from __future__ import unicode_literals + from django.utils.translation import ugettext_lazy as _ MK_MUNICIPALITIES = ( - ('AD', _(u'Aerodrom')), - ('AR', _(u'Aračinovo')), - ('BR', _(u'Berovo')), - ('TL', _(u'Bitola')), - ('BG', _(u'Bogdanci')), - ('VJ', _(u'Bogovinje')), - ('BS', _(u'Bosilovo')), - ('BN', _(u'Brvenica')), - ('BU', _(u'Butel')), - ('VA', _(u'Valandovo')), - ('VL', _(u'Vasilevo')), - ('VV', _(u'Vevčani')), - ('VE', _(u'Veles')), - ('NI', _(u'Vinica')), - ('VC', _(u'Vraneštica')), - ('VH', _(u'Vrapčište')), - ('GB', _(u'Gazi Baba')), - ('GV', _(u'Gevgelija')), - ('GT', _(u'Gostivar')), - ('GR', _(u'Gradsko')), - ('DB', _(u'Debar')), - ('DA', _(u'Debarca')), - ('DL', _(u'Delčevo')), - ('DK', _(u'Demir Kapija')), - ('DM', _(u'Demir Hisar')), - ('DE', _(u'Dolneni')), - ('DR', _(u'Drugovo')), - ('GP', _(u'Gjorče Petrov')), - ('ZE', _(u'Želino')), - ('ZA', _(u'Zajas')), - ('ZK', _(u'Zelenikovo')), - ('ZR', _(u'Zrnovci')), - ('IL', _(u'Ilinden')), - ('JG', _(u'Jegunovce')), - ('AV', _(u'Kavadarci')), - ('KB', _(u'Karbinci')), - ('KX', _(u'Karpoš')), - ('VD', _(u'Kisela Voda')), - ('KH', _(u'Kičevo')), - ('KN', _(u'Konče')), - ('OC', _(u'Koćani')), - ('KY', _(u'Kratovo')), - ('KZ', _(u'Kriva Palanka')), - ('KG', _(u'Krivogaštani')), - ('KS', _(u'Kruševo')), - ('UM', _(u'Kumanovo')), - ('LI', _(u'Lipkovo')), - ('LO', _(u'Lozovo')), - ('MR', _(u'Mavrovo i Rostuša')), - ('MK', _(u'Makedonska Kamenica')), - ('MD', _(u'Makedonski Brod')), - ('MG', _(u'Mogila')), - ('NG', _(u'Negotino')), - ('NV', _(u'Novaci')), - ('NS', _(u'Novo Selo')), - ('OS', _(u'Oslomej')), - ('OD', _(u'Ohrid')), - ('PE', _(u'Petrovec')), - ('PH', _(u'Pehčevo')), - ('PN', _(u'Plasnica')), - ('PP', _(u'Prilep')), - ('PT', _(u'Probištip')), - ('RV', _(u'Radoviš')), - ('RN', _(u'Rankovce')), - ('RE', _(u'Resen')), - ('RO', _(u'Rosoman')), - ('AJ', _(u'Saraj')), - ('SL', _(u'Sveti Nikole')), - ('SS', _(u'Sopište')), - ('SD', _(u'Star Dojran')), - ('NA', _(u'Staro Nagoričane')), - ('UG', _(u'Struga')), - ('RU', _(u'Strumica')), - ('SU', _(u'Studeničani')), - ('TR', _(u'Tearce')), - ('ET', _(u'Tetovo')), - ('CE', _(u'Centar')), - ('CZ', _(u'Centar-Župa')), - ('CI', _(u'Čair')), - ('CA', _(u'Čaška')), - ('CH', _(u'Češinovo-Obleševo')), - ('CS', _(u'Čučer-Sandevo')), - ('ST', _(u'Štip')), - ('SO', _(u'Šuto Orizari')), + ('AD', _('Aerodrom')), + ('AR', _('Aračinovo')), + ('BR', _('Berovo')), + ('TL', _('Bitola')), + ('BG', _('Bogdanci')), + ('VJ', _('Bogovinje')), + ('BS', _('Bosilovo')), + ('BN', _('Brvenica')), + ('BU', _('Butel')), + ('VA', _('Valandovo')), + ('VL', _('Vasilevo')), + ('VV', _('Vevčani')), + ('VE', _('Veles')), + ('NI', _('Vinica')), + ('VC', _('Vraneštica')), + ('VH', _('Vrapčište')), + ('GB', _('Gazi Baba')), + ('GV', _('Gevgelija')), + ('GT', _('Gostivar')), + ('GR', _('Gradsko')), + ('DB', _('Debar')), + ('DA', _('Debarca')), + ('DL', _('Delčevo')), + ('DK', _('Demir Kapija')), + ('DM', _('Demir Hisar')), + ('DE', _('Dolneni')), + ('DR', _('Drugovo')), + ('GP', _('Gjorče Petrov')), + ('ZE', _('Želino')), + ('ZA', _('Zajas')), + ('ZK', _('Zelenikovo')), + ('ZR', _('Zrnovci')), + ('IL', _('Ilinden')), + ('JG', _('Jegunovce')), + ('AV', _('Kavadarci')), + ('KB', _('Karbinci')), + ('KX', _('Karpoš')), + ('VD', _('Kisela Voda')), + ('KH', _('Kičevo')), + ('KN', _('Konče')), + ('OC', _('Koćani')), + ('KY', _('Kratovo')), + ('KZ', _('Kriva Palanka')), + ('KG', _('Krivogaštani')), + ('KS', _('Kruševo')), + ('UM', _('Kumanovo')), + ('LI', _('Lipkovo')), + ('LO', _('Lozovo')), + ('MR', _('Mavrovo i Rostuša')), + ('MK', _('Makedonska Kamenica')), + ('MD', _('Makedonski Brod')), + ('MG', _('Mogila')), + ('NG', _('Negotino')), + ('NV', _('Novaci')), + ('NS', _('Novo Selo')), + ('OS', _('Oslomej')), + ('OD', _('Ohrid')), + ('PE', _('Petrovec')), + ('PH', _('Pehčevo')), + ('PN', _('Plasnica')), + ('PP', _('Prilep')), + ('PT', _('Probištip')), + ('RV', _('Radoviš')), + ('RN', _('Rankovce')), + ('RE', _('Resen')), + ('RO', _('Rosoman')), + ('AJ', _('Saraj')), + ('SL', _('Sveti Nikole')), + ('SS', _('Sopište')), + ('SD', _('Star Dojran')), + ('NA', _('Staro Nagoričane')), + ('UG', _('Struga')), + ('RU', _('Strumica')), + ('SU', _('Studeničani')), + ('TR', _('Tearce')), + ('ET', _('Tetovo')), + ('CE', _('Centar')), + ('CZ', _('Centar-Župa')), + ('CI', _('Čair')), + ('CA', _('Čaška')), + ('CH', _('Češinovo-Obleševo')), + ('CS', _('Čučer-Sandevo')), + ('ST', _('Štip')), + ('SO', _('Šuto Orizari')), ) diff --git a/django/contrib/localflavor/mx/forms.py b/django/contrib/localflavor/mx/forms.py index deecb4ea41a..2dcf17d26c8 100644 --- a/django/contrib/localflavor/mx/forms.py +++ b/django/contrib/localflavor/mx/forms.py @@ -2,6 +2,7 @@ """ Mexican-specific form helpers. """ +from __future__ import unicode_literals import re from django.forms import ValidationError @@ -19,12 +20,12 @@ document described in the next link: """ RFC_INCONVENIENT_WORDS = [ - u'BUEI', u'BUEY', u'CACA', u'CACO', u'CAGA', u'CAGO', u'CAKA', u'CAKO', - u'COGE', u'COJA', u'COJE', u'COJI', u'COJO', u'CULO', u'FETO', u'GUEY', - u'JOTO', u'KACA', u'KACO', u'KAGA', u'KAGO', u'KOGE', u'KOJO', u'KAKA', - u'KULO', u'MAME', u'MAMO', u'MEAR', u'MEAS', u'MEON', u'MION', u'MOCO', - u'MULA', u'PEDA', u'PEDO', u'PENE', u'PUTA', u'PUTO', u'QULO', u'RATA', - u'RUIN', + 'BUEI', 'BUEY', 'CACA', 'CACO', 'CAGA', 'CAGO', 'CAKA', 'CAKO', + 'COGE', 'COJA', 'COJE', 'COJI', 'COJO', 'CULO', 'FETO', 'GUEY', + 'JOTO', 'KACA', 'KACO', 'KAGA', 'KAGO', 'KOGE', 'KOJO', 'KAKA', + 'KULO', 'MAME', 'MAMO', 'MEAR', 'MEAS', 'MEON', 'MION', 'MOCO', + 'MULA', 'PEDA', 'PEDO', 'PENE', 'PUTA', 'PUTO', 'QULO', 'RATA', + 'RUIN', ] """ @@ -33,17 +34,17 @@ document described in the next link: http://portal.veracruz.gob.mx/pls/portal/url/ITEM/444112558A57C6E0E040A8C02E00695C """ CURP_INCONVENIENT_WORDS = [ - u'BACA', u'BAKA', u'BUEI', u'BUEY', u'CACA', u'CACO', u'CAGA', u'CAGO', - u'CAKA', u'CAKO', u'COGE', u'COGI', u'COJA', u'COJE', u'COJI', u'COJO', - u'COLA', u'CULO', u'FALO', u'FETO', u'GETA', u'GUEI', u'GUEY', u'JETA', - u'JOTO', u'KACA', u'KACO', u'KAGA', u'KAGO', u'KAKA', u'KAKO', u'KOGE', - u'KOGI', u'KOJA', u'KOJE', u'KOJI', u'KOJO', u'KOLA', u'KULO', u'LILO', - u'LOCA', u'LOCO', u'LOKA', u'LOKO', u'MAME', u'MAMO', u'MEAR', u'MEAS', - u'MEON', u'MIAR', u'MION', u'MOCO', u'MOKO', u'MULA', u'MULO', u'NACA', - u'NACO', u'PEDA', u'PEDO', u'PENE', u'PIPI', u'PITO', u'POPO', u'PUTA', - u'PUTO', u'QULO', u'RATA', u'ROBA', u'ROBE', u'ROBO', u'RUIN', u'SENO', - u'TETA', u'VACA', u'VAGA', u'VAGO', u'VAKA', u'VUEI', u'VUEY', u'WUEI', - u'WUEY', + 'BACA', 'BAKA', 'BUEI', 'BUEY', 'CACA', 'CACO', 'CAGA', 'CAGO', + 'CAKA', 'CAKO', 'COGE', 'COGI', 'COJA', 'COJE', 'COJI', 'COJO', + 'COLA', 'CULO', 'FALO', 'FETO', 'GETA', 'GUEI', 'GUEY', 'JETA', + 'JOTO', 'KACA', 'KACO', 'KAGA', 'KAGO', 'KAKA', 'KAKO', 'KOGE', + 'KOGI', 'KOJA', 'KOJE', 'KOJI', 'KOJO', 'KOLA', 'KULO', 'LILO', + 'LOCA', 'LOCO', 'LOKA', 'LOKO', 'MAME', 'MAMO', 'MEAR', 'MEAS', + 'MEON', 'MIAR', 'MION', 'MOCO', 'MOKO', 'MULA', 'MULO', 'NACA', + 'NACO', 'PEDA', 'PEDO', 'PENE', 'PIPI', 'PITO', 'POPO', 'PUTA', + 'PUTO', 'QULO', 'RATA', 'ROBA', 'ROBE', 'ROBO', 'RUIN', 'SENO', + 'TETA', 'VACA', 'VAGA', 'VAGO', 'VAKA', 'VUEI', 'VUEY', 'WUEI', + 'WUEY', ] class MXStateSelect(Select): @@ -62,11 +63,11 @@ class MXZipCodeField(RegexField): http://en.wikipedia.org/wiki/List_of_postal_codes_in_Mexico """ default_error_messages = { - 'invalid': _(u'Enter a valid zip code in the format XXXXX.'), + 'invalid': _('Enter a valid zip code in the format XXXXX.'), } def __init__(self, *args, **kwargs): - zip_code_re = ur'^(0[1-9]|[1][0-6]|[2-9]\d)(\d{3})$' + zip_code_re = r'^(0[1-9]|[1][0-6]|[2-9]\d)(\d{3})$' super(MXZipCodeField, self).__init__(zip_code_re, *args, **kwargs) @@ -110,7 +111,7 @@ class MXRFCField(RegexField): } def __init__(self, min_length=9, max_length=13, *args, **kwargs): - rfc_re = re.compile(ur'^([A-Z&Ññ]{3}|[A-Z][AEIOU][A-Z]{2})%s([A-Z0-9]{2}[0-9A])?$' % DATE_RE, + rfc_re = re.compile(r'^([A-Z&Ññ]{3}|[A-Z][AEIOU][A-Z]{2})%s([A-Z0-9]{2}[0-9A])?$' % DATE_RE, re.IGNORECASE) super(MXRFCField, self).__init__(rfc_re, min_length=min_length, max_length=max_length, *args, **kwargs) @@ -118,7 +119,7 @@ class MXRFCField(RegexField): def clean(self, value): value = super(MXRFCField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = value.upper() if self._has_homoclave(value): if not value[-1] == self._checksum(value[:-1]): @@ -133,7 +134,7 @@ class MXRFCField(RegexField): since the current algorithm to calculate it had not been created for the first RFCs ever in Mexico. """ - rfc_without_homoclave_re = re.compile(ur'^[A-Z&Ññ]{3,4}%s$' % DATE_RE, + rfc_without_homoclave_re = re.compile(r'^[A-Z&Ññ]{3,4}%s$' % DATE_RE, re.IGNORECASE) return not rfc_without_homoclave_re.match(rfc) @@ -142,7 +143,7 @@ class MXRFCField(RegexField): More info about this procedure: www.sisi.org.mx/jspsi/documentos/2005/seguimiento/06101/0610100162005_065.doc """ - chars = u'0123456789ABCDEFGHIJKLMN&OPQRSTUVWXYZ-Ñ' + chars = '0123456789ABCDEFGHIJKLMN&OPQRSTUVWXYZ-Ñ' if len(rfc) == 11: rfc = '-' + rfc @@ -150,9 +151,9 @@ class MXRFCField(RegexField): checksum = 11 - sum_ % 11 if checksum == 10: - return u'A' + return 'A' elif checksum == 11: - return u'0' + return '0' return unicode(checksum) @@ -187,13 +188,13 @@ class MXCURPField(RegexField): """ default_error_messages = { 'invalid': _('Enter a valid CURP.'), - 'invalid_checksum': _(u'Invalid checksum for CURP.'), + 'invalid_checksum': _('Invalid checksum for CURP.'), } def __init__(self, min_length=18, max_length=18, *args, **kwargs): states_re = r'(AS|BC|BS|CC|CL|CM|CS|CH|DF|DG|GT|GR|HG|JC|MC|MN|MS|NT|NL|OC|PL|QT|QR|SP|SL|SR|TC|TS|TL|VZ|YN|ZS|NE)' consonants_re = r'[B-DF-HJ-NP-TV-Z]' - curp_re = (ur'^[A-Z][AEIOU][A-Z]{2}%s[HM]%s%s{3}[0-9A-Z]\d$' % + curp_re = (r'^[A-Z][AEIOU][A-Z]{2}%s[HM]%s%s{3}[0-9A-Z]\d$' % (DATE_RE, states_re, consonants_re)) curp_re = re.compile(curp_re, re.IGNORECASE) super(MXCURPField, self).__init__(curp_re, min_length=min_length, @@ -202,7 +203,7 @@ class MXCURPField(RegexField): def clean(self, value): value = super(MXCURPField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = value.upper() if value[-1] != self._checksum(value[:-1]): raise ValidationError(self.default_error_messages['invalid_checksum']) @@ -211,13 +212,13 @@ class MXCURPField(RegexField): return value def _checksum(self, value): - chars = u'0123456789ABCDEFGHIJKLMN&OPQRSTUVWXYZ' + chars = '0123456789ABCDEFGHIJKLMN&OPQRSTUVWXYZ' s = sum(i * chars.index(c) for i, c in zip(reversed(xrange(19)), value)) checksum = 10 - s % 10 if checksum == 10: - return u'0' + return '0' return unicode(checksum) def _has_inconvenient_word(self, curp): diff --git a/django/contrib/localflavor/mx/mx_states.py b/django/contrib/localflavor/mx/mx_states.py index 2aba63ef261..6ae08ccb12f 100644 --- a/django/contrib/localflavor/mx/mx_states.py +++ b/django/contrib/localflavor/mx/mx_states.py @@ -5,41 +5,42 @@ A list of Mexican states for use as `choices` in a formfield. This exists in this standalone file so that it's only imported into memory when explicitly needed. """ +from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ # All 31 states, plus the `Distrito Federal`. STATE_CHOICES = ( - ('AGU', _(u'Aguascalientes')), - ('BCN', _(u'Baja California')), - ('BCS', _(u'Baja California Sur')), - ('CAM', _(u'Campeche')), - ('CHH', _(u'Chihuahua')), - ('CHP', _(u'Chiapas')), - ('COA', _(u'Coahuila')), - ('COL', _(u'Colima')), - ('DIF', _(u'Distrito Federal')), - ('DUR', _(u'Durango')), - ('GRO', _(u'Guerrero')), - ('GUA', _(u'Guanajuato')), - ('HID', _(u'Hidalgo')), - ('JAL', _(u'Jalisco')), - ('MEX', _(u'Estado de México')), - ('MIC', _(u'Michoacán')), - ('MOR', _(u'Morelos')), - ('NAY', _(u'Nayarit')), - ('NLE', _(u'Nuevo León')), - ('OAX', _(u'Oaxaca')), - ('PUE', _(u'Puebla')), - ('QUE', _(u'Querétaro')), - ('ROO', _(u'Quintana Roo')), - ('SIN', _(u'Sinaloa')), - ('SLP', _(u'San Luis Potosí')), - ('SON', _(u'Sonora')), - ('TAB', _(u'Tabasco')), - ('TAM', _(u'Tamaulipas')), - ('TLA', _(u'Tlaxcala')), - ('VER', _(u'Veracruz')), - ('YUC', _(u'Yucatán')), - ('ZAC', _(u'Zacatecas')), + ('AGU', _('Aguascalientes')), + ('BCN', _('Baja California')), + ('BCS', _('Baja California Sur')), + ('CAM', _('Campeche')), + ('CHH', _('Chihuahua')), + ('CHP', _('Chiapas')), + ('COA', _('Coahuila')), + ('COL', _('Colima')), + ('DIF', _('Distrito Federal')), + ('DUR', _('Durango')), + ('GRO', _('Guerrero')), + ('GUA', _('Guanajuato')), + ('HID', _('Hidalgo')), + ('JAL', _('Jalisco')), + ('MEX', _('Estado de México')), + ('MIC', _('Michoacán')), + ('MOR', _('Morelos')), + ('NAY', _('Nayarit')), + ('NLE', _('Nuevo León')), + ('OAX', _('Oaxaca')), + ('PUE', _('Puebla')), + ('QUE', _('Querétaro')), + ('ROO', _('Quintana Roo')), + ('SIN', _('Sinaloa')), + ('SLP', _('San Luis Potosí')), + ('SON', _('Sonora')), + ('TAB', _('Tabasco')), + ('TAM', _('Tamaulipas')), + ('TLA', _('Tlaxcala')), + ('VER', _('Veracruz')), + ('YUC', _('Yucatán')), + ('ZAC', _('Zacatecas')), ) diff --git a/django/contrib/localflavor/nl/forms.py b/django/contrib/localflavor/nl/forms.py index 66900808c2c..bdd769bd391 100644 --- a/django/contrib/localflavor/nl/forms.py +++ b/django/contrib/localflavor/nl/forms.py @@ -2,7 +2,7 @@ NL-specific Form helpers """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re @@ -29,7 +29,7 @@ class NLZipCodeField(Field): def clean(self, value): super(NLZipCodeField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = value.strip().upper().replace(' ', '') if not pc_re.search(value): @@ -38,7 +38,7 @@ class NLZipCodeField(Field): if int(value[:4]) < 1000: raise ValidationError(self.error_messages['invalid']) - return u'%s %s' % (value[:4], value[4:]) + return '%s %s' % (value[:4], value[4:]) class NLProvinceSelect(Select): """ @@ -59,7 +59,7 @@ class NLPhoneNumberField(Field): def clean(self, value): super(NLPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' phone_nr = re.sub('[\-\s\(\)]', '', smart_unicode(value)) @@ -85,7 +85,7 @@ class NLSoFiNumberField(Field): def clean(self, value): super(NLSoFiNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' if not sofi_re.search(value): raise ValidationError(self.error_messages['invalid']) diff --git a/django/contrib/localflavor/no/forms.py b/django/contrib/localflavor/no/forms.py index 3e5e58bd1c0..4bd780a3127 100644 --- a/django/contrib/localflavor/no/forms.py +++ b/django/contrib/localflavor/no/forms.py @@ -2,7 +2,7 @@ Norwegian-specific Form helpers """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re import datetime @@ -36,13 +36,13 @@ class NOSocialSecurityNumber(Field): Algorithm is documented at http://no.wikipedia.org/wiki/Personnummer """ default_error_messages = { - 'invalid': _(u'Enter a valid Norwegian social security number.'), + 'invalid': _('Enter a valid Norwegian social security number.'), } def clean(self, value): super(NOSocialSecurityNumber, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' if not re.match(r'^\d{11}$', value): raise ValidationError(self.error_messages['invalid']) diff --git a/django/contrib/localflavor/no/no_municipalities.py b/django/contrib/localflavor/no/no_municipalities.py index d6bacda2757..d84915caa22 100644 --- a/django/contrib/localflavor/no/no_municipalities.py +++ b/django/contrib/localflavor/no/no_municipalities.py @@ -6,27 +6,28 @@ in a formfield. This exists in this standalone file so that it's on ly imported into memory when explicitly needed. """ +from __future__ import unicode_literals MUNICIPALITY_CHOICES = ( - ('akershus', u'Akershus'), - ('austagder', u'Aust-Agder'), - ('buskerud', u'Buskerud'), - ('finnmark', u'Finnmark'), - ('hedmark', u'Hedmark'), - ('hordaland', u'Hordaland'), - ('janmayen', u'Jan Mayen'), - ('moreogromsdal', u'Møre og Romsdal'), - ('nordtrondelag', u'Nord-Trøndelag'), - ('nordland', u'Nordland'), - ('oppland', u'Oppland'), - ('oslo', u'Oslo'), - ('rogaland', u'Rogaland'), - ('sognogfjordane', u'Sogn og Fjordane'), - ('svalbard', u'Svalbard'), - ('sortrondelag', u'Sør-Trøndelag'), - ('telemark', u'Telemark'), - ('troms', u'Troms'), - ('vestagder', u'Vest-Agder'), - ('vestfold', u'Vestfold'), - ('ostfold', u'Østfold') + ('akershus', 'Akershus'), + ('austagder', 'Aust-Agder'), + ('buskerud', 'Buskerud'), + ('finnmark', 'Finnmark'), + ('hedmark', 'Hedmark'), + ('hordaland', 'Hordaland'), + ('janmayen', 'Jan Mayen'), + ('moreogromsdal', 'Møre og Romsdal'), + ('nordtrondelag', 'Nord-Trøndelag'), + ('nordland', 'Nordland'), + ('oppland', 'Oppland'), + ('oslo', 'Oslo'), + ('rogaland', 'Rogaland'), + ('sognogfjordane', 'Sogn og Fjordane'), + ('svalbard', 'Svalbard'), + ('sortrondelag', 'Sør-Trøndelag'), + ('telemark', 'Telemark'), + ('troms', 'Troms'), + ('vestagder', 'Vest-Agder'), + ('vestfold', 'Vestfold'), + ('ostfold', 'Østfold') ) diff --git a/django/contrib/localflavor/pe/forms.py b/django/contrib/localflavor/pe/forms.py index 0eca2b8ac75..5100bbf5753 100644 --- a/django/contrib/localflavor/pe/forms.py +++ b/django/contrib/localflavor/pe/forms.py @@ -3,7 +3,7 @@ PE-specific Form helpers. """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from django.contrib.localflavor.pe.pe_region import REGION_CHOICES from django.core.validators import EMPTY_VALUES @@ -38,7 +38,7 @@ class PEDNIField(CharField): """ value = super(PEDNIField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' if not value.isdigit(): raise ValidationError(self.error_messages['invalid']) if len(value) != 8: @@ -66,7 +66,7 @@ class PERUCField(RegexField): """ value = super(PERUCField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' if not value.isdigit(): raise ValidationError(self.error_messages['invalid']) if len(value) != 11: diff --git a/django/contrib/localflavor/pe/pe_region.py b/django/contrib/localflavor/pe/pe_region.py index 9863bd3d153..9270bcecf12 100644 --- a/django/contrib/localflavor/pe/pe_region.py +++ b/django/contrib/localflavor/pe/pe_region.py @@ -5,31 +5,32 @@ A list of Peru regions as `choices` in a formfield. This exists in this standalone file so that it's only imported into memory when explicitly needed. """ +from __future__ import unicode_literals REGION_CHOICES = ( - ('AMA', u'Amazonas'), - ('ANC', u'Ancash'), - ('APU', u'Apurímac'), - ('ARE', u'Arequipa'), - ('AYA', u'Ayacucho'), - ('CAJ', u'Cajamarca'), - ('CAL', u'Callao'), - ('CUS', u'Cusco'), - ('HUV', u'Huancavelica'), - ('HUC', u'Huánuco'), - ('ICA', u'Ica'), - ('JUN', u'Junín'), - ('LAL', u'La Libertad'), - ('LAM', u'Lambayeque'), - ('LIM', u'Lima'), - ('LOR', u'Loreto'), - ('MDD', u'Madre de Dios'), - ('MOQ', u'Moquegua'), - ('PAS', u'Pasco'), - ('PIU', u'Piura'), - ('PUN', u'Puno'), - ('SAM', u'San Martín'), - ('TAC', u'Tacna'), - ('TUM', u'Tumbes'), - ('UCA', u'Ucayali'), + ('AMA', 'Amazonas'), + ('ANC', 'Ancash'), + ('APU', 'Apurímac'), + ('ARE', 'Arequipa'), + ('AYA', 'Ayacucho'), + ('CAJ', 'Cajamarca'), + ('CAL', 'Callao'), + ('CUS', 'Cusco'), + ('HUV', 'Huancavelica'), + ('HUC', 'Huánuco'), + ('ICA', 'Ica'), + ('JUN', 'Junín'), + ('LAL', 'La Libertad'), + ('LAM', 'Lambayeque'), + ('LIM', 'Lima'), + ('LOR', 'Loreto'), + ('MDD', 'Madre de Dios'), + ('MOQ', 'Moquegua'), + ('PAS', 'Pasco'), + ('PIU', 'Piura'), + ('PUN', 'Puno'), + ('SAM', 'San Martín'), + ('TAC', 'Tacna'), + ('TUM', 'Tumbes'), + ('UCA', 'Ucayali'), ) diff --git a/django/contrib/localflavor/pl/forms.py b/django/contrib/localflavor/pl/forms.py index 3e8d73f0f25..12d9f3d763c 100644 --- a/django/contrib/localflavor/pl/forms.py +++ b/django/contrib/localflavor/pl/forms.py @@ -2,7 +2,7 @@ Polish-specific form helpers """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re @@ -39,8 +39,8 @@ class PLPESELField(RegexField): The algorithm is documented at http://en.wikipedia.org/wiki/PESEL. """ default_error_messages = { - 'invalid': _(u'National Identification Number consists of 11 digits.'), - 'checksum': _(u'Wrong checksum for the National Identification Number.'), + 'invalid': _('National Identification Number consists of 11 digits.'), + 'checksum': _('Wrong checksum for the National Identification Number.'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): @@ -50,10 +50,10 @@ class PLPESELField(RegexField): def clean(self, value): super(PLPESELField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' if not self.has_valid_checksum(value): raise ValidationError(self.error_messages['checksum']) - return u'%s' % value + return '%s' % value def has_valid_checksum(self, number): """ @@ -76,8 +76,8 @@ class PLNationalIDCardNumberField(RegexField): The algorithm is documented at http://en.wikipedia.org/wiki/Polish_identity_card. """ default_error_messages = { - 'invalid': _(u'National ID Card Number consists of 3 letters and 6 digits.'), - 'checksum': _(u'Wrong checksum for the National ID Card Number.'), + 'invalid': _('National ID Card Number consists of 3 letters and 6 digits.'), + 'checksum': _('Wrong checksum for the National ID Card Number.'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): @@ -87,13 +87,13 @@ class PLNationalIDCardNumberField(RegexField): def clean(self,value): super(PLNationalIDCardNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = value.upper() if not self.has_valid_checksum(value): raise ValidationError(self.error_messages['checksum']) - return u'%s' % value + return '%s' % value def has_valid_checksum(self, number): """ @@ -128,8 +128,8 @@ class PLNIPField(RegexField): http://wipos.p.lodz.pl/zylla/ut/nip-rego.html """ default_error_messages = { - 'invalid': _(u'Enter a tax number field (NIP) in the format XXX-XXX-XX-XX, XXX-XX-XX-XXX or XXXXXXXXXX.'), - 'checksum': _(u'Wrong checksum for the Tax Number (NIP).'), + 'invalid': _('Enter a tax number field (NIP) in the format XXX-XXX-XX-XX, XXX-XX-XX-XXX or XXXXXXXXXX.'), + 'checksum': _('Wrong checksum for the Tax Number (NIP).'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): @@ -139,11 +139,11 @@ class PLNIPField(RegexField): def clean(self,value): super(PLNIPField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = re.sub("[-]", "", value) if not self.has_valid_checksum(value): raise ValidationError(self.error_messages['checksum']) - return u'%s' % value + return '%s' % value def has_valid_checksum(self, number): """ @@ -168,8 +168,8 @@ class PLREGONField(RegexField): See http://www.stat.gov.pl/bip/regon_ENG_HTML.htm for more information. """ default_error_messages = { - 'invalid': _(u'National Business Register Number (REGON) consists of 9 or 14 digits.'), - 'checksum': _(u'Wrong checksum for the National Business Register Number (REGON).'), + 'invalid': _('National Business Register Number (REGON) consists of 9 or 14 digits.'), + 'checksum': _('Wrong checksum for the National Business Register Number (REGON).'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): @@ -179,10 +179,10 @@ class PLREGONField(RegexField): def clean(self,value): super(PLREGONField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' if not self.has_valid_checksum(value): raise ValidationError(self.error_messages['checksum']) - return u'%s' % value + return '%s' % value def has_valid_checksum(self, number): """ @@ -209,7 +209,7 @@ class PLPostalCodeField(RegexField): Valid code is XX-XXX where X is digit. """ default_error_messages = { - 'invalid': _(u'Enter a postal code in the format XX-XXX.'), + 'invalid': _('Enter a postal code in the format XX-XXX.'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): diff --git a/django/contrib/localflavor/pl/pl_administrativeunits.py b/django/contrib/localflavor/pl/pl_administrativeunits.py index 9777ea2b619..f5263f19d2d 100644 --- a/django/contrib/localflavor/pl/pl_administrativeunits.py +++ b/django/contrib/localflavor/pl/pl_administrativeunits.py @@ -2,384 +2,385 @@ """ Polish administrative units as in http://pl.wikipedia.org/wiki/Podzia%C5%82_administracyjny_Polski """ +from __future__ import unicode_literals ADMINISTRATIVE_UNIT_CHOICES = ( - ('wroclaw', u'Wrocław'), - ('jeleniagora', u'Jelenia Góra'), - ('legnica', u'Legnica'), - ('boleslawiecki', u'bolesławiecki'), - ('dzierzoniowski', u'dzierżoniowski'), - ('glogowski', u'głogowski'), - ('gorowski', u'górowski'), - ('jaworski', u'jaworski'), - ('jeleniogorski', u'jeleniogórski'), - ('kamiennogorski', u'kamiennogórski'), - ('klodzki', u'kłodzki'), - ('legnicki', u'legnicki'), - ('lubanski', u'lubański'), - ('lubinski', u'lubiński'), - ('lwowecki', u'lwówecki'), - ('milicki', u'milicki'), - ('olesnicki', u'oleśnicki'), - ('olawski', u'oławski'), - ('polkowicki', u'polkowicki'), - ('strzelinski', u'strzeliński'), - ('sredzki', u'średzki'), - ('swidnicki', u'świdnicki'), - ('trzebnicki', u'trzebnicki'), - ('walbrzyski', u'wałbrzyski'), - ('wolowski', u'wołowski'), - ('wroclawski', u'wrocławski'), - ('zabkowicki', u'ząbkowicki'), - ('zgorzelecki', u'zgorzelecki'), - ('zlotoryjski', u'złotoryjski'), - ('bydgoszcz', u'Bydgoszcz'), - ('torun', u'Toruń'), - ('wloclawek', u'Włocławek'), - ('grudziadz', u'Grudziądz'), - ('aleksandrowski', u'aleksandrowski'), - ('brodnicki', u'brodnicki'), - ('bydgoski', u'bydgoski'), - ('chelminski', u'chełmiński'), - ('golubsko-dobrzynski', u'golubsko-dobrzyński'), - ('grudziadzki', u'grudziądzki'), - ('inowroclawski', u'inowrocławski'), - ('lipnowski', u'lipnowski'), - ('mogilenski', u'mogileński'), - ('nakielski', u'nakielski'), - ('radziejowski', u'radziejowski'), - ('rypinski', u'rypiński'), - ('sepolenski', u'sępoleński'), - ('swiecki', u'świecki'), - ('torunski', u'toruński'), - ('tucholski', u'tucholski'), - ('wabrzeski', u'wąbrzeski'), - ('wloclawski', u'wrocławski'), - ('zninski', u'źniński'), - ('lublin', u'Lublin'), - ('biala-podlaska', u'Biała Podlaska'), - ('chelm', u'Chełm'), - ('zamosc', u'Zamość'), - ('bialski', u'bialski'), - ('bilgorajski', u'biłgorajski'), - ('chelmski', u'chełmski'), - ('hrubieszowski', u'hrubieszowski'), - ('janowski', u'janowski'), - ('krasnostawski', u'krasnostawski'), - ('krasnicki', u'kraśnicki'), - ('lubartowski', u'lubartowski'), - ('lubelski', u'lubelski'), - ('leczynski', u'łęczyński'), - ('lukowski', u'łukowski'), - ('opolski', u'opolski'), - ('parczewski', u'parczewski'), - ('pulawski', u'puławski'), - ('radzynski', u'radzyński'), - ('rycki', u'rycki'), - ('swidnicki', u'świdnicki'), - ('tomaszowski', u'tomaszowski'), - ('wlodawski', u'włodawski'), - ('zamojski', u'zamojski'), - ('gorzow-wielkopolski', u'Gorzów Wielkopolski'), - ('zielona-gora', u'Zielona Góra'), - ('gorzowski', u'gorzowski'), - ('krosnienski', u'krośnieński'), - ('miedzyrzecki', u'międzyrzecki'), - ('nowosolski', u'nowosolski'), - ('slubicki', u'słubicki'), - ('strzelecko-drezdenecki', u'strzelecko-drezdenecki'), - ('sulecinski', u'suleńciński'), - ('swiebodzinski', u'świebodziński'), - ('wschowski', u'wschowski'), - ('zielonogorski', u'zielonogórski'), - ('zaganski', u'żagański'), - ('zarski', u'żarski'), - ('lodz', u'Łódź'), - ('piotrkow-trybunalski', u'Piotrków Trybunalski'), - ('skierniewice', u'Skierniewice'), - ('belchatowski', u'bełchatowski'), - ('brzezinski', u'brzeziński'), - ('kutnowski', u'kutnowski'), - ('laski', u'łaski'), - ('leczycki', u'łęczycki'), - ('lowicki', u'łowicki'), - ('lodzki wschodni', u'łódzki wschodni'), - ('opoczynski', u'opoczyński'), - ('pabianicki', u'pabianicki'), - ('pajeczanski', u'pajęczański'), - ('piotrkowski', u'piotrkowski'), - ('poddebicki', u'poddębicki'), - ('radomszczanski', u'radomszczański'), - ('rawski', u'rawski'), - ('sieradzki', u'sieradzki'), - ('skierniewicki', u'skierniewicki'), - ('tomaszowski', u'tomaszowski'), - ('wielunski', u'wieluński'), - ('wieruszowski', u'wieruszowski'), - ('zdunskowolski', u'zduńskowolski'), - ('zgierski', u'zgierski'), - ('krakow', u'Kraków'), - ('tarnow', u'Tarnów'), - ('nowy-sacz', u'Nowy Sącz'), - ('bochenski', u'bocheński'), - ('brzeski', u'brzeski'), - ('chrzanowski', u'chrzanowski'), - ('dabrowski', u'dąbrowski'), - ('gorlicki', u'gorlicki'), - ('krakowski', u'krakowski'), - ('limanowski', u'limanowski'), - ('miechowski', u'miechowski'), - ('myslenicki', u'myślenicki'), - ('nowosadecki', u'nowosądecki'), - ('nowotarski', u'nowotarski'), - ('olkuski', u'olkuski'), - ('oswiecimski', u'oświęcimski'), - ('proszowicki', u'proszowicki'), - ('suski', u'suski'), - ('tarnowski', u'tarnowski'), - ('tatrzanski', u'tatrzański'), - ('wadowicki', u'wadowicki'), - ('wielicki', u'wielicki'), - ('warszawa', u'Warszawa'), - ('ostroleka', u'Ostrołęka'), - ('plock', u'Płock'), - ('radom', u'Radom'), - ('siedlce', u'Siedlce'), - ('bialobrzeski', u'białobrzeski'), - ('ciechanowski', u'ciechanowski'), - ('garwolinski', u'garwoliński'), - ('gostyninski', u'gostyniński'), - ('grodziski', u'grodziski'), - ('grojecki', u'grójecki'), - ('kozienicki', u'kozenicki'), - ('legionowski', u'legionowski'), - ('lipski', u'lipski'), - ('losicki', u'łosicki'), - ('makowski', u'makowski'), - ('minski', u'miński'), - ('mlawski', u'mławski'), - ('nowodworski', u'nowodworski'), - ('ostrolecki', u'ostrołęcki'), - ('ostrowski', u'ostrowski'), - ('otwocki', u'otwocki'), - ('piaseczynski', u'piaseczyński'), - ('plocki', u'płocki'), - ('plonski', u'płoński'), - ('pruszkowski', u'pruszkowski'), - ('przasnyski', u'przasnyski'), - ('przysuski', u'przysuski'), - ('pultuski', u'pułtuski'), - ('radomski', u'radomski'), - ('siedlecki', u'siedlecki'), - ('sierpecki', u'sierpecki'), - ('sochaczewski', u'sochaczewski'), - ('sokolowski', u'sokołowski'), - ('szydlowiecki', u'szydłowiecki'), - ('warszawski-zachodni', u'warszawski zachodni'), - ('wegrowski', u'węgrowski'), - ('wolominski', u'wołomiński'), - ('wyszkowski', u'wyszkowski'), - ('zwolenski', u'zwoleński'), - ('zurominski', u'żuromiński'), - ('zyrardowski', u'żyrardowski'), - ('opole', u'Opole'), - ('brzeski', u'brzeski'), - ('glubczycki', u'głubczyski'), - ('kedzierzynsko-kozielski', u'kędzierzyński-kozielski'), - ('kluczborski', u'kluczborski'), - ('krapkowicki', u'krapkowicki'), - ('namyslowski', u'namysłowski'), - ('nyski', u'nyski'), - ('oleski', u'oleski'), - ('opolski', u'opolski'), - ('prudnicki', u'prudnicki'), - ('strzelecki', u'strzelecki'), - ('rzeszow', u'Rzeszów'), - ('krosno', u'Krosno'), - ('przemysl', u'Przemyśl'), - ('tarnobrzeg', u'Tarnobrzeg'), - ('bieszczadzki', u'bieszczadzki'), - ('brzozowski', u'brzozowski'), - ('debicki', u'dębicki'), - ('jaroslawski', u'jarosławski'), - ('jasielski', u'jasielski'), - ('kolbuszowski', u'kolbuszowski'), - ('krosnienski', u'krośnieński'), - ('leski', u'leski'), - ('lezajski', u'leżajski'), - ('lubaczowski', u'lubaczowski'), - ('lancucki', u'łańcucki'), - ('mielecki', u'mielecki'), - ('nizanski', u'niżański'), - ('przemyski', u'przemyski'), - ('przeworski', u'przeworski'), - ('ropczycko-sedziszowski', u'ropczycko-sędziszowski'), - ('rzeszowski', u'rzeszowski'), - ('sanocki', u'sanocki'), - ('stalowowolski', u'stalowowolski'), - ('strzyzowski', u'strzyżowski'), - ('tarnobrzeski', u'tarnobrzeski'), - ('bialystok', u'Białystok'), - ('lomza', u'Łomża'), - ('suwalki', u'Suwałki'), - ('augustowski', u'augustowski'), - ('bialostocki', u'białostocki'), - ('bielski', u'bielski'), - ('grajewski', u'grajewski'), - ('hajnowski', u'hajnowski'), - ('kolnenski', u'kolneński'), - ('łomzynski', u'łomżyński'), - ('moniecki', u'moniecki'), - ('sejnenski', u'sejneński'), - ('siemiatycki', u'siematycki'), - ('sokolski', u'sokólski'), - ('suwalski', u'suwalski'), - ('wysokomazowiecki', u'wysokomazowiecki'), - ('zambrowski', u'zambrowski'), - ('gdansk', u'Gdańsk'), - ('gdynia', u'Gdynia'), - ('slupsk', u'Słupsk'), - ('sopot', u'Sopot'), - ('bytowski', u'bytowski'), - ('chojnicki', u'chojnicki'), - ('czluchowski', u'człuchowski'), - ('kartuski', u'kartuski'), - ('koscierski', u'kościerski'), - ('kwidzynski', u'kwidzyński'), - ('leborski', u'lęborski'), - ('malborski', u'malborski'), - ('nowodworski', u'nowodworski'), - ('gdanski', u'gdański'), - ('pucki', u'pucki'), - ('slupski', u'słupski'), - ('starogardzki', u'starogardzki'), - ('sztumski', u'sztumski'), - ('tczewski', u'tczewski'), - ('wejherowski', u'wejcherowski'), - ('katowice', u'Katowice'), - ('bielsko-biala', u'Bielsko-Biała'), - ('bytom', u'Bytom'), - ('chorzow', u'Chorzów'), - ('czestochowa', u'Częstochowa'), - ('dabrowa-gornicza', u'Dąbrowa Górnicza'), - ('gliwice', u'Gliwice'), - ('jastrzebie-zdroj', u'Jastrzębie Zdrój'), - ('jaworzno', u'Jaworzno'), - ('myslowice', u'Mysłowice'), - ('piekary-slaskie', u'Piekary Śląskie'), - ('ruda-slaska', u'Ruda Śląska'), - ('rybnik', u'Rybnik'), - ('siemianowice-slaskie', u'Siemianowice Śląskie'), - ('sosnowiec', u'Sosnowiec'), - ('swietochlowice', u'Świętochłowice'), - ('tychy', u'Tychy'), - ('zabrze', u'Zabrze'), - ('zory', u'Żory'), - ('bedzinski', u'będziński'), - ('bielski', u'bielski'), - ('bierunsko-ledzinski', u'bieruńsko-lędziński'), - ('cieszynski', u'cieszyński'), - ('czestochowski', u'częstochowski'), - ('gliwicki', u'gliwicki'), - ('klobucki', u'kłobucki'), - ('lubliniecki', u'lubliniecki'), - ('mikolowski', u'mikołowski'), - ('myszkowski', u'myszkowski'), - ('pszczynski', u'pszczyński'), - ('raciborski', u'raciborski'), - ('rybnicki', u'rybnicki'), - ('tarnogorski', u'tarnogórski'), - ('wodzislawski', u'wodzisławski'), - ('zawiercianski', u'zawierciański'), - ('zywiecki', u'żywiecki'), - ('kielce', u'Kielce'), - ('buski', u'buski'), - ('jedrzejowski', u'jędrzejowski'), - ('kazimierski', u'kazimierski'), - ('kielecki', u'kielecki'), - ('konecki', u'konecki'), - ('opatowski', u'opatowski'), - ('ostrowiecki', u'ostrowiecki'), - ('pinczowski', u'pińczowski'), - ('sandomierski', u'sandomierski'), - ('skarzyski', u'skarżyski'), - ('starachowicki', u'starachowicki'), - ('staszowski', u'staszowski'), - ('wloszczowski', u'włoszczowski'), - ('olsztyn', u'Olsztyn'), - ('elblag', u'Elbląg'), - ('bartoszycki', u'bartoszycki'), - ('braniewski', u'braniewski'), - ('dzialdowski', u'działdowski'), - ('elblaski', u'elbląski'), - ('elcki', u'ełcki'), - ('gizycki', u'giżycki'), - ('goldapski', u'gołdapski'), - ('ilawski', u'iławski'), - ('ketrzynski', u'kętrzyński'), - ('lidzbarski', u'lidzbarski'), - ('mragowski', u'mrągowski'), - ('nidzicki', u'nidzicki'), - ('nowomiejski', u'nowomiejski'), - ('olecki', u'olecki'), - ('olsztynski', u'olsztyński'), - ('ostrodzki', u'ostródzki'), - ('piski', u'piski'), - ('szczycienski', u'szczycieński'), - ('wegorzewski', u'węgorzewski'), - ('poznan', u'Poznań'), - ('kalisz', u'Kalisz'), - ('konin', u'Konin'), - ('leszno', u'Leszno'), - ('chodzieski', u'chodziejski'), - ('czarnkowsko-trzcianecki', u'czarnkowsko-trzcianecki'), - ('gnieznienski', u'gnieźnieński'), - ('gostynski', u'gostyński'), - ('grodziski', u'grodziski'), - ('jarocinski', u'jarociński'), - ('kaliski', u'kaliski'), - ('kepinski', u'kępiński'), - ('kolski', u'kolski'), - ('koninski', u'koniński'), - ('koscianski', u'kościański'), - ('krotoszynski', u'krotoszyński'), - ('leszczynski', u'leszczyński'), - ('miedzychodzki', u'międzychodzki'), - ('nowotomyski', u'nowotomyski'), - ('obornicki', u'obornicki'), - ('ostrowski', u'ostrowski'), - ('ostrzeszowski', u'ostrzeszowski'), - ('pilski', u'pilski'), - ('pleszewski', u'pleszewski'), - ('poznanski', u'poznański'), - ('rawicki', u'rawicki'), - ('slupecki', u'słupecki'), - ('szamotulski', u'szamotulski'), - ('sredzki', u'średzki'), - ('sremski', u'śremski'), - ('turecki', u'turecki'), - ('wagrowiecki', u'wągrowiecki'), - ('wolsztynski', u'wolsztyński'), - ('wrzesinski', u'wrzesiński'), - ('zlotowski', u'złotowski'), - ('bialogardzki', u'białogardzki'), - ('choszczenski', u'choszczeński'), - ('drawski', u'drawski'), - ('goleniowski', u'goleniowski'), - ('gryficki', u'gryficki'), - ('gryfinski', u'gryfiński'), - ('kamienski', u'kamieński'), - ('kolobrzeski', u'kołobrzeski'), - ('koszalinski', u'koszaliński'), - ('lobeski', u'łobeski'), - ('mysliborski', u'myśliborski'), - ('policki', u'policki'), - ('pyrzycki', u'pyrzycki'), - ('slawienski', u'sławieński'), - ('stargardzki', u'stargardzki'), - ('szczecinecki', u'szczecinecki'), - ('swidwinski', u'świdwiński'), - ('walecki', u'wałecki'), + ('wroclaw', 'Wrocław'), + ('jeleniagora', 'Jelenia Góra'), + ('legnica', 'Legnica'), + ('boleslawiecki', 'bolesławiecki'), + ('dzierzoniowski', 'dzierżoniowski'), + ('glogowski', 'głogowski'), + ('gorowski', 'górowski'), + ('jaworski', 'jaworski'), + ('jeleniogorski', 'jeleniogórski'), + ('kamiennogorski', 'kamiennogórski'), + ('klodzki', 'kłodzki'), + ('legnicki', 'legnicki'), + ('lubanski', 'lubański'), + ('lubinski', 'lubiński'), + ('lwowecki', 'lwówecki'), + ('milicki', 'milicki'), + ('olesnicki', 'oleśnicki'), + ('olawski', 'oławski'), + ('polkowicki', 'polkowicki'), + ('strzelinski', 'strzeliński'), + ('sredzki', 'średzki'), + ('swidnicki', 'świdnicki'), + ('trzebnicki', 'trzebnicki'), + ('walbrzyski', 'wałbrzyski'), + ('wolowski', 'wołowski'), + ('wroclawski', 'wrocławski'), + ('zabkowicki', 'ząbkowicki'), + ('zgorzelecki', 'zgorzelecki'), + ('zlotoryjski', 'złotoryjski'), + ('bydgoszcz', 'Bydgoszcz'), + ('torun', 'Toruń'), + ('wloclawek', 'Włocławek'), + ('grudziadz', 'Grudziądz'), + ('aleksandrowski', 'aleksandrowski'), + ('brodnicki', 'brodnicki'), + ('bydgoski', 'bydgoski'), + ('chelminski', 'chełmiński'), + ('golubsko-dobrzynski', 'golubsko-dobrzyński'), + ('grudziadzki', 'grudziądzki'), + ('inowroclawski', 'inowrocławski'), + ('lipnowski', 'lipnowski'), + ('mogilenski', 'mogileński'), + ('nakielski', 'nakielski'), + ('radziejowski', 'radziejowski'), + ('rypinski', 'rypiński'), + ('sepolenski', 'sępoleński'), + ('swiecki', 'świecki'), + ('torunski', 'toruński'), + ('tucholski', 'tucholski'), + ('wabrzeski', 'wąbrzeski'), + ('wloclawski', 'wrocławski'), + ('zninski', 'źniński'), + ('lublin', 'Lublin'), + ('biala-podlaska', 'Biała Podlaska'), + ('chelm', 'Chełm'), + ('zamosc', 'Zamość'), + ('bialski', 'bialski'), + ('bilgorajski', 'biłgorajski'), + ('chelmski', 'chełmski'), + ('hrubieszowski', 'hrubieszowski'), + ('janowski', 'janowski'), + ('krasnostawski', 'krasnostawski'), + ('krasnicki', 'kraśnicki'), + ('lubartowski', 'lubartowski'), + ('lubelski', 'lubelski'), + ('leczynski', 'łęczyński'), + ('lukowski', 'łukowski'), + ('opolski', 'opolski'), + ('parczewski', 'parczewski'), + ('pulawski', 'puławski'), + ('radzynski', 'radzyński'), + ('rycki', 'rycki'), + ('swidnicki', 'świdnicki'), + ('tomaszowski', 'tomaszowski'), + ('wlodawski', 'włodawski'), + ('zamojski', 'zamojski'), + ('gorzow-wielkopolski', 'Gorzów Wielkopolski'), + ('zielona-gora', 'Zielona Góra'), + ('gorzowski', 'gorzowski'), + ('krosnienski', 'krośnieński'), + ('miedzyrzecki', 'międzyrzecki'), + ('nowosolski', 'nowosolski'), + ('slubicki', 'słubicki'), + ('strzelecko-drezdenecki', 'strzelecko-drezdenecki'), + ('sulecinski', 'suleńciński'), + ('swiebodzinski', 'świebodziński'), + ('wschowski', 'wschowski'), + ('zielonogorski', 'zielonogórski'), + ('zaganski', 'żagański'), + ('zarski', 'żarski'), + ('lodz', 'Łódź'), + ('piotrkow-trybunalski', 'Piotrków Trybunalski'), + ('skierniewice', 'Skierniewice'), + ('belchatowski', 'bełchatowski'), + ('brzezinski', 'brzeziński'), + ('kutnowski', 'kutnowski'), + ('laski', 'łaski'), + ('leczycki', 'łęczycki'), + ('lowicki', 'łowicki'), + ('lodzki wschodni', 'łódzki wschodni'), + ('opoczynski', 'opoczyński'), + ('pabianicki', 'pabianicki'), + ('pajeczanski', 'pajęczański'), + ('piotrkowski', 'piotrkowski'), + ('poddebicki', 'poddębicki'), + ('radomszczanski', 'radomszczański'), + ('rawski', 'rawski'), + ('sieradzki', 'sieradzki'), + ('skierniewicki', 'skierniewicki'), + ('tomaszowski', 'tomaszowski'), + ('wielunski', 'wieluński'), + ('wieruszowski', 'wieruszowski'), + ('zdunskowolski', 'zduńskowolski'), + ('zgierski', 'zgierski'), + ('krakow', 'Kraków'), + ('tarnow', 'Tarnów'), + ('nowy-sacz', 'Nowy Sącz'), + ('bochenski', 'bocheński'), + ('brzeski', 'brzeski'), + ('chrzanowski', 'chrzanowski'), + ('dabrowski', 'dąbrowski'), + ('gorlicki', 'gorlicki'), + ('krakowski', 'krakowski'), + ('limanowski', 'limanowski'), + ('miechowski', 'miechowski'), + ('myslenicki', 'myślenicki'), + ('nowosadecki', 'nowosądecki'), + ('nowotarski', 'nowotarski'), + ('olkuski', 'olkuski'), + ('oswiecimski', 'oświęcimski'), + ('proszowicki', 'proszowicki'), + ('suski', 'suski'), + ('tarnowski', 'tarnowski'), + ('tatrzanski', 'tatrzański'), + ('wadowicki', 'wadowicki'), + ('wielicki', 'wielicki'), + ('warszawa', 'Warszawa'), + ('ostroleka', 'Ostrołęka'), + ('plock', 'Płock'), + ('radom', 'Radom'), + ('siedlce', 'Siedlce'), + ('bialobrzeski', 'białobrzeski'), + ('ciechanowski', 'ciechanowski'), + ('garwolinski', 'garwoliński'), + ('gostyninski', 'gostyniński'), + ('grodziski', 'grodziski'), + ('grojecki', 'grójecki'), + ('kozienicki', 'kozenicki'), + ('legionowski', 'legionowski'), + ('lipski', 'lipski'), + ('losicki', 'łosicki'), + ('makowski', 'makowski'), + ('minski', 'miński'), + ('mlawski', 'mławski'), + ('nowodworski', 'nowodworski'), + ('ostrolecki', 'ostrołęcki'), + ('ostrowski', 'ostrowski'), + ('otwocki', 'otwocki'), + ('piaseczynski', 'piaseczyński'), + ('plocki', 'płocki'), + ('plonski', 'płoński'), + ('pruszkowski', 'pruszkowski'), + ('przasnyski', 'przasnyski'), + ('przysuski', 'przysuski'), + ('pultuski', 'pułtuski'), + ('radomski', 'radomski'), + ('siedlecki', 'siedlecki'), + ('sierpecki', 'sierpecki'), + ('sochaczewski', 'sochaczewski'), + ('sokolowski', 'sokołowski'), + ('szydlowiecki', 'szydłowiecki'), + ('warszawski-zachodni', 'warszawski zachodni'), + ('wegrowski', 'węgrowski'), + ('wolominski', 'wołomiński'), + ('wyszkowski', 'wyszkowski'), + ('zwolenski', 'zwoleński'), + ('zurominski', 'żuromiński'), + ('zyrardowski', 'żyrardowski'), + ('opole', 'Opole'), + ('brzeski', 'brzeski'), + ('glubczycki', 'głubczyski'), + ('kedzierzynsko-kozielski', 'kędzierzyński-kozielski'), + ('kluczborski', 'kluczborski'), + ('krapkowicki', 'krapkowicki'), + ('namyslowski', 'namysłowski'), + ('nyski', 'nyski'), + ('oleski', 'oleski'), + ('opolski', 'opolski'), + ('prudnicki', 'prudnicki'), + ('strzelecki', 'strzelecki'), + ('rzeszow', 'Rzeszów'), + ('krosno', 'Krosno'), + ('przemysl', 'Przemyśl'), + ('tarnobrzeg', 'Tarnobrzeg'), + ('bieszczadzki', 'bieszczadzki'), + ('brzozowski', 'brzozowski'), + ('debicki', 'dębicki'), + ('jaroslawski', 'jarosławski'), + ('jasielski', 'jasielski'), + ('kolbuszowski', 'kolbuszowski'), + ('krosnienski', 'krośnieński'), + ('leski', 'leski'), + ('lezajski', 'leżajski'), + ('lubaczowski', 'lubaczowski'), + ('lancucki', 'łańcucki'), + ('mielecki', 'mielecki'), + ('nizanski', 'niżański'), + ('przemyski', 'przemyski'), + ('przeworski', 'przeworski'), + ('ropczycko-sedziszowski', 'ropczycko-sędziszowski'), + ('rzeszowski', 'rzeszowski'), + ('sanocki', 'sanocki'), + ('stalowowolski', 'stalowowolski'), + ('strzyzowski', 'strzyżowski'), + ('tarnobrzeski', 'tarnobrzeski'), + ('bialystok', 'Białystok'), + ('lomza', 'Łomża'), + ('suwalki', 'Suwałki'), + ('augustowski', 'augustowski'), + ('bialostocki', 'białostocki'), + ('bielski', 'bielski'), + ('grajewski', 'grajewski'), + ('hajnowski', 'hajnowski'), + ('kolnenski', 'kolneński'), + ('łomzynski', 'łomżyński'), + ('moniecki', 'moniecki'), + ('sejnenski', 'sejneński'), + ('siemiatycki', 'siematycki'), + ('sokolski', 'sokólski'), + ('suwalski', 'suwalski'), + ('wysokomazowiecki', 'wysokomazowiecki'), + ('zambrowski', 'zambrowski'), + ('gdansk', 'Gdańsk'), + ('gdynia', 'Gdynia'), + ('slupsk', 'Słupsk'), + ('sopot', 'Sopot'), + ('bytowski', 'bytowski'), + ('chojnicki', 'chojnicki'), + ('czluchowski', 'człuchowski'), + ('kartuski', 'kartuski'), + ('koscierski', 'kościerski'), + ('kwidzynski', 'kwidzyński'), + ('leborski', 'lęborski'), + ('malborski', 'malborski'), + ('nowodworski', 'nowodworski'), + ('gdanski', 'gdański'), + ('pucki', 'pucki'), + ('slupski', 'słupski'), + ('starogardzki', 'starogardzki'), + ('sztumski', 'sztumski'), + ('tczewski', 'tczewski'), + ('wejherowski', 'wejcherowski'), + ('katowice', 'Katowice'), + ('bielsko-biala', 'Bielsko-Biała'), + ('bytom', 'Bytom'), + ('chorzow', 'Chorzów'), + ('czestochowa', 'Częstochowa'), + ('dabrowa-gornicza', 'Dąbrowa Górnicza'), + ('gliwice', 'Gliwice'), + ('jastrzebie-zdroj', 'Jastrzębie Zdrój'), + ('jaworzno', 'Jaworzno'), + ('myslowice', 'Mysłowice'), + ('piekary-slaskie', 'Piekary Śląskie'), + ('ruda-slaska', 'Ruda Śląska'), + ('rybnik', 'Rybnik'), + ('siemianowice-slaskie', 'Siemianowice Śląskie'), + ('sosnowiec', 'Sosnowiec'), + ('swietochlowice', 'Świętochłowice'), + ('tychy', 'Tychy'), + ('zabrze', 'Zabrze'), + ('zory', 'Żory'), + ('bedzinski', 'będziński'), + ('bielski', 'bielski'), + ('bierunsko-ledzinski', 'bieruńsko-lędziński'), + ('cieszynski', 'cieszyński'), + ('czestochowski', 'częstochowski'), + ('gliwicki', 'gliwicki'), + ('klobucki', 'kłobucki'), + ('lubliniecki', 'lubliniecki'), + ('mikolowski', 'mikołowski'), + ('myszkowski', 'myszkowski'), + ('pszczynski', 'pszczyński'), + ('raciborski', 'raciborski'), + ('rybnicki', 'rybnicki'), + ('tarnogorski', 'tarnogórski'), + ('wodzislawski', 'wodzisławski'), + ('zawiercianski', 'zawierciański'), + ('zywiecki', 'żywiecki'), + ('kielce', 'Kielce'), + ('buski', 'buski'), + ('jedrzejowski', 'jędrzejowski'), + ('kazimierski', 'kazimierski'), + ('kielecki', 'kielecki'), + ('konecki', 'konecki'), + ('opatowski', 'opatowski'), + ('ostrowiecki', 'ostrowiecki'), + ('pinczowski', 'pińczowski'), + ('sandomierski', 'sandomierski'), + ('skarzyski', 'skarżyski'), + ('starachowicki', 'starachowicki'), + ('staszowski', 'staszowski'), + ('wloszczowski', 'włoszczowski'), + ('olsztyn', 'Olsztyn'), + ('elblag', 'Elbląg'), + ('bartoszycki', 'bartoszycki'), + ('braniewski', 'braniewski'), + ('dzialdowski', 'działdowski'), + ('elblaski', 'elbląski'), + ('elcki', 'ełcki'), + ('gizycki', 'giżycki'), + ('goldapski', 'gołdapski'), + ('ilawski', 'iławski'), + ('ketrzynski', 'kętrzyński'), + ('lidzbarski', 'lidzbarski'), + ('mragowski', 'mrągowski'), + ('nidzicki', 'nidzicki'), + ('nowomiejski', 'nowomiejski'), + ('olecki', 'olecki'), + ('olsztynski', 'olsztyński'), + ('ostrodzki', 'ostródzki'), + ('piski', 'piski'), + ('szczycienski', 'szczycieński'), + ('wegorzewski', 'węgorzewski'), + ('poznan', 'Poznań'), + ('kalisz', 'Kalisz'), + ('konin', 'Konin'), + ('leszno', 'Leszno'), + ('chodzieski', 'chodziejski'), + ('czarnkowsko-trzcianecki', 'czarnkowsko-trzcianecki'), + ('gnieznienski', 'gnieźnieński'), + ('gostynski', 'gostyński'), + ('grodziski', 'grodziski'), + ('jarocinski', 'jarociński'), + ('kaliski', 'kaliski'), + ('kepinski', 'kępiński'), + ('kolski', 'kolski'), + ('koninski', 'koniński'), + ('koscianski', 'kościański'), + ('krotoszynski', 'krotoszyński'), + ('leszczynski', 'leszczyński'), + ('miedzychodzki', 'międzychodzki'), + ('nowotomyski', 'nowotomyski'), + ('obornicki', 'obornicki'), + ('ostrowski', 'ostrowski'), + ('ostrzeszowski', 'ostrzeszowski'), + ('pilski', 'pilski'), + ('pleszewski', 'pleszewski'), + ('poznanski', 'poznański'), + ('rawicki', 'rawicki'), + ('slupecki', 'słupecki'), + ('szamotulski', 'szamotulski'), + ('sredzki', 'średzki'), + ('sremski', 'śremski'), + ('turecki', 'turecki'), + ('wagrowiecki', 'wągrowiecki'), + ('wolsztynski', 'wolsztyński'), + ('wrzesinski', 'wrzesiński'), + ('zlotowski', 'złotowski'), + ('bialogardzki', 'białogardzki'), + ('choszczenski', 'choszczeński'), + ('drawski', 'drawski'), + ('goleniowski', 'goleniowski'), + ('gryficki', 'gryficki'), + ('gryfinski', 'gryfiński'), + ('kamienski', 'kamieński'), + ('kolobrzeski', 'kołobrzeski'), + ('koszalinski', 'koszaliński'), + ('lobeski', 'łobeski'), + ('mysliborski', 'myśliborski'), + ('policki', 'policki'), + ('pyrzycki', 'pyrzycki'), + ('slawienski', 'sławieński'), + ('stargardzki', 'stargardzki'), + ('szczecinecki', 'szczecinecki'), + ('swidwinski', 'świdwiński'), + ('walecki', 'wałecki'), ) diff --git a/django/contrib/localflavor/pt/forms.py b/django/contrib/localflavor/pt/forms.py index 3de7376eacd..b27fb577bd7 100644 --- a/django/contrib/localflavor/pt/forms.py +++ b/django/contrib/localflavor/pt/forms.py @@ -1,6 +1,8 @@ """ PT-specific Form helpers """ +from __future__ import unicode_literals + import re from django.core.validators import EMPTY_VALUES @@ -24,7 +26,7 @@ class PTZipCodeField(RegexField): def clean(self,value): cleaned = super(PTZipCodeField, self).clean(value) if len(cleaned) == 7: - return u'%s-%s' % (cleaned[:4],cleaned[4:]) + return '%s-%s' % (cleaned[:4],cleaned[4:]) else: return cleaned @@ -40,9 +42,9 @@ class PTPhoneNumberField(Field): def clean(self, value): super(PTPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = re.sub('(\.|\s)', '', smart_unicode(value)) m = phone_digits_re.search(value) if m: - return u'%s' % value + return '%s' % value raise ValidationError(self.error_messages['invalid']) diff --git a/django/contrib/localflavor/py/py_department.py b/django/contrib/localflavor/py/py_department.py index 28c613b9a06..619bae3edb7 100644 --- a/django/contrib/localflavor/py/py_department.py +++ b/django/contrib/localflavor/py/py_department.py @@ -1,45 +1,46 @@ # -*- coding: utf-8 -*- # http://www.statoids.com/upy.html +from __future__ import unicode_literals DEPARTMENT_CHOICES = ( - ('AG', u'Alto Paraguay'), - ('AA', u'Alto Paraná'), - ('AM', u'Amambay'), - ('AS', u'Asunción'), - ('BQ', u'Boquerón'), - ('CG', u'Caaguazú'), - ('CZ', u'Caazapá'), - ('CY', u'Canindeyú'), - ('CE', u'Central'), - ('CN', u'Concepción'), - ('CR', u'Cordillera'), - ('GU', u'Guairá'), - ('IT', u'Itapúa'), - ('MI', u'Misiones'), - ('NE', u'Ñeembucú'), - ('PG', u'Paraguarí'), - ('PH', u'Pdte. Hayes'), - ('SP', u'San Pedro'), + ('AG', 'Alto Paraguay'), + ('AA', 'Alto Paraná'), + ('AM', 'Amambay'), + ('AS', 'Asunción'), + ('BQ', 'Boquerón'), + ('CG', 'Caaguazú'), + ('CZ', 'Caazapá'), + ('CY', 'Canindeyú'), + ('CE', 'Central'), + ('CN', 'Concepción'), + ('CR', 'Cordillera'), + ('GU', 'Guairá'), + ('IT', 'Itapúa'), + ('MI', 'Misiones'), + ('NE', 'Ñeembucú'), + ('PG', 'Paraguarí'), + ('PH', 'Pdte. Hayes'), + ('SP', 'San Pedro'), ) DEPARTMENT_ROMAN_CHOICES = ( - ('CN', u'I Concepción'), - ('SP', u'II San Pedro'), - ('CR', u'III Cordillera'), - ('GU', u'IV Guairá'), - ('CG', u'V Caaguazú'), - ('CZ', u'VI Caazapá'), - ('IT', u'VII Itapúa'), - ('MI', u'VIII Misiones'), - ('PG', u'IX Paraguarí'), - ('AA', u'X Alto Paraná'), - ('CE', u'XI Central'), - ('NE', u'XII Ñeembucú'), - ('AM', u'XIII Amambay'), - ('CY', u'XIV Canindeyú'), - ('PH', u'XV Pdte. Hayes'), - ('AG', u'XVI Alto Paraguay'), - ('BQ', u'XVII Boquerón'), - ('AS', u'XVIII Asunción'), + ('CN', 'I Concepción'), + ('SP', 'II San Pedro'), + ('CR', 'III Cordillera'), + ('GU', 'IV Guairá'), + ('CG', 'V Caaguazú'), + ('CZ', 'VI Caazapá'), + ('IT', 'VII Itapúa'), + ('MI', 'VIII Misiones'), + ('PG', 'IX Paraguarí'), + ('AA', 'X Alto Paraná'), + ('CE', 'XI Central'), + ('NE', 'XII Ñeembucú'), + ('AM', 'XIII Amambay'), + ('CY', 'XIV Canindeyú'), + ('PH', 'XV Pdte. Hayes'), + ('AG', 'XVI Alto Paraguay'), + ('BQ', 'XVII Boquerón'), + ('AS', 'XVIII Asunción'), ) diff --git a/django/contrib/localflavor/ro/forms.py b/django/contrib/localflavor/ro/forms.py index 5c458390b28..bdbed5c476c 100644 --- a/django/contrib/localflavor/ro/forms.py +++ b/django/contrib/localflavor/ro/forms.py @@ -2,7 +2,7 @@ """ Romanian specific form helpers. """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from django.contrib.localflavor.ro.ro_counties import COUNTIES_CHOICES from django.core.validators import EMPTY_VALUES @@ -30,7 +30,7 @@ class ROCIFField(RegexField): """ value = super(ROCIFField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' # strip RO part if value[0:2] == 'RO': value = value[2:] @@ -67,7 +67,7 @@ class ROCNPField(RegexField): """ value = super(ROCNPField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' # check birthdate digits import datetime try: @@ -100,13 +100,13 @@ class ROCountyField(Field): Arges => invalid """ default_error_messages = { - 'invalid': u'Enter a Romanian county code or name.', + 'invalid': 'Enter a Romanian county code or name.', } def clean(self, value): super(ROCountyField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' try: value = value.strip().upper() except AttributeError: @@ -152,7 +152,7 @@ class ROIBANField(RegexField): """ value = super(ROIBANField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = value.replace('-','') value = value.replace(' ','') value = value.upper() @@ -184,7 +184,7 @@ class ROPhoneNumberField(RegexField): """ value = super(ROPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = value.replace('-','') value = value.replace('(','') value = value.replace(')','') diff --git a/django/contrib/localflavor/ro/ro_counties.py b/django/contrib/localflavor/ro/ro_counties.py index 40423ddc870..282cfc51937 100644 --- a/django/contrib/localflavor/ro/ro_counties.py +++ b/django/contrib/localflavor/ro/ro_counties.py @@ -5,48 +5,49 @@ A list of Romanian counties as `choices` in a formfield. This exists as a standalone file so that it's only imported into memory when explicitly needed. """ +from __future__ import unicode_literals COUNTIES_CHOICES = ( - ('AB', u'Alba'), - ('AR', u'Arad'), - ('AG', u'Argeş'), - ('BC', u'Bacău'), - ('BH', u'Bihor'), - ('BN', u'Bistriţa-Năsăud'), - ('BT', u'Botoşani'), - ('BV', u'Braşov'), - ('BR', u'Brăila'), - ('B', u'Bucureşti'), - ('BZ', u'Buzău'), - ('CS', u'Caraş-Severin'), - ('CL', u'Călăraşi'), - ('CJ', u'Cluj'), - ('CT', u'Constanţa'), - ('CV', u'Covasna'), - ('DB', u'Dâmboviţa'), - ('DJ', u'Dolj'), - ('GL', u'Galaţi'), - ('GR', u'Giurgiu'), - ('GJ', u'Gorj'), - ('HR', u'Harghita'), - ('HD', u'Hunedoara'), - ('IL', u'Ialomiţa'), - ('IS', u'Iaşi'), - ('IF', u'Ilfov'), - ('MM', u'Maramureş'), - ('MH', u'Mehedinţi'), - ('MS', u'Mureş'), - ('NT', u'Neamţ'), - ('OT', u'Olt'), - ('PH', u'Prahova'), - ('SM', u'Satu Mare'), - ('SJ', u'Sălaj'), - ('SB', u'Sibiu'), - ('SV', u'Suceava'), - ('TR', u'Teleorman'), - ('TM', u'Timiş'), - ('TL', u'Tulcea'), - ('VS', u'Vaslui'), - ('VL', u'Vâlcea'), - ('VN', u'Vrancea'), + ('AB', 'Alba'), + ('AR', 'Arad'), + ('AG', 'Argeş'), + ('BC', 'Bacău'), + ('BH', 'Bihor'), + ('BN', 'Bistriţa-Năsăud'), + ('BT', 'Botoşani'), + ('BV', 'Braşov'), + ('BR', 'Brăila'), + ('B', 'Bucureşti'), + ('BZ', 'Buzău'), + ('CS', 'Caraş-Severin'), + ('CL', 'Călăraşi'), + ('CJ', 'Cluj'), + ('CT', 'Constanţa'), + ('CV', 'Covasna'), + ('DB', 'Dâmboviţa'), + ('DJ', 'Dolj'), + ('GL', 'Galaţi'), + ('GR', 'Giurgiu'), + ('GJ', 'Gorj'), + ('HR', 'Harghita'), + ('HD', 'Hunedoara'), + ('IL', 'Ialomiţa'), + ('IS', 'Iaşi'), + ('IF', 'Ilfov'), + ('MM', 'Maramureş'), + ('MH', 'Mehedinţi'), + ('MS', 'Mureş'), + ('NT', 'Neamţ'), + ('OT', 'Olt'), + ('PH', 'Prahova'), + ('SM', 'Satu Mare'), + ('SJ', 'Sălaj'), + ('SB', 'Sibiu'), + ('SV', 'Suceava'), + ('TR', 'Teleorman'), + ('TM', 'Timiş'), + ('TL', 'Tulcea'), + ('VS', 'Vaslui'), + ('VL', 'Vâlcea'), + ('VN', 'Vrancea'), ) diff --git a/django/contrib/localflavor/ru/forms.py b/django/contrib/localflavor/ru/forms.py index d01f5a1e3b5..03114d0629a 100644 --- a/django/contrib/localflavor/ru/forms.py +++ b/django/contrib/localflavor/ru/forms.py @@ -1,7 +1,7 @@ """ Russian-specific forms helpers """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re @@ -34,7 +34,7 @@ class RUPostalCodeField(RegexField): Format: XXXXXX, where X is any digit, and first digit is not zero. """ default_error_messages = { - 'invalid': _(u'Enter a postal code in the format XXXXXX.'), + 'invalid': _('Enter a postal code in the format XXXXXX.'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): super(RUPostalCodeField, self).__init__(r'^\d{6}$', @@ -47,7 +47,7 @@ class RUPassportNumberField(RegexField): XXXX XXXXXX where X - any digit. """ default_error_messages = { - 'invalid': _(u'Enter a passport number in the format XXXX XXXXXX.'), + 'invalid': _('Enter a passport number in the format XXXX XXXXXX.'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): super(RUPassportNumberField, self).__init__(r'^\d{4} \d{6}$', @@ -60,7 +60,7 @@ class RUAlienPassportNumberField(RegexField): XX XXXXXXX where X - any digit. """ default_error_messages = { - 'invalid': _(u'Enter a passport number in the format XX XXXXXXX.'), + 'invalid': _('Enter a passport number in the format XX XXXXXXX.'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): super(RUAlienPassportNumberField, self).__init__(r'^\d{2} \d{7}$', diff --git a/django/contrib/localflavor/se/forms.py b/django/contrib/localflavor/se/forms.py index 5c4e2325a9d..43d06a08ec5 100644 --- a/django/contrib/localflavor/se/forms.py +++ b/django/contrib/localflavor/se/forms.py @@ -2,7 +2,7 @@ """ Swedish specific Form helpers """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re @@ -58,7 +58,7 @@ class SEOrganisationNumberField(forms.CharField): value = super(SEOrganisationNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' match = SWEDISH_ID_NUMBER.match(value) if not match: @@ -116,7 +116,7 @@ class SEPersonalIdentityNumberField(forms.CharField): value = super(SEPersonalIdentityNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' match = SWEDISH_ID_NUMBER.match(value) if match is None: diff --git a/django/contrib/localflavor/se/se_counties.py b/django/contrib/localflavor/se/se_counties.py index db54fb9f39b..20090d3b300 100644 --- a/django/contrib/localflavor/se/se_counties.py +++ b/django/contrib/localflavor/se/se_counties.py @@ -8,29 +8,30 @@ This exists in this standalone file so that it's only imported into memory when explicitly needed. """ +from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ COUNTY_CHOICES = ( - ('AB', _(u'Stockholm')), - ('AC', _(u'Västerbotten')), - ('BD', _(u'Norrbotten')), - ('C', _(u'Uppsala')), - ('D', _(u'Södermanland')), - ('E', _(u'Östergötland')), - ('F', _(u'Jönköping')), - ('G', _(u'Kronoberg')), - ('H', _(u'Kalmar')), - ('I', _(u'Gotland')), - ('K', _(u'Blekinge')), - ('M', _(u'Skåne')), - ('N', _(u'Halland')), - ('O', _(u'Västra Götaland')), - ('S', _(u'Värmland')), - ('T', _(u'Örebro')), - ('U', _(u'Västmanland')), - ('W', _(u'Dalarna')), - ('X', _(u'Gävleborg')), - ('Y', _(u'Västernorrland')), - ('Z', _(u'Jämtland')), + ('AB', _('Stockholm')), + ('AC', _('Västerbotten')), + ('BD', _('Norrbotten')), + ('C', _('Uppsala')), + ('D', _('Södermanland')), + ('E', _('Östergötland')), + ('F', _('Jönköping')), + ('G', _('Kronoberg')), + ('H', _('Kalmar')), + ('I', _('Gotland')), + ('K', _('Blekinge')), + ('M', _('Skåne')), + ('N', _('Halland')), + ('O', _('Västra Götaland')), + ('S', _('Värmland')), + ('T', _('Örebro')), + ('U', _('Västmanland')), + ('W', _('Dalarna')), + ('X', _('Gävleborg')), + ('Y', _('Västernorrland')), + ('Z', _('Jämtland')), ) diff --git a/django/contrib/localflavor/si/forms.py b/django/contrib/localflavor/si/forms.py index f1188dd2227..aa4b9dac5a8 100644 --- a/django/contrib/localflavor/si/forms.py +++ b/django/contrib/localflavor/si/forms.py @@ -2,7 +2,7 @@ Slovenian specific form helpers. """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import datetime import re @@ -21,16 +21,16 @@ class SIEMSOField(CharField): """ default_error_messages = { - 'invalid': _(u'This field should contain exactly 13 digits.'), - 'date': _(u'The first 7 digits of the EMSO must represent a valid past date.'), - 'checksum': _(u'The EMSO is not valid.'), + 'invalid': _('This field should contain exactly 13 digits.'), + 'date': _('The first 7 digits of the EMSO must represent a valid past date.'), + 'checksum': _('The EMSO is not valid.'), } emso_regex = re.compile('^(\d{2})(\d{2})(\d{3})(\d{2})(\d{3})(\d)$') def clean(self, value): super(SIEMSOField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = value.strip() @@ -83,14 +83,14 @@ class SITaxNumberField(CharField): """ default_error_messages = { - 'invalid': _(u'Enter a valid tax number in form SIXXXXXXXX'), + 'invalid': _('Enter a valid tax number in form SIXXXXXXXX'), } sitax_regex = re.compile('^(?:SI)?([1-9]\d{7})$') def clean(self, value): super(SITaxNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = value.strip() @@ -148,14 +148,14 @@ class SIPhoneNumberField(CharField): """ default_error_messages = { - 'invalid': _(u'Enter phone number in form +386XXXXXXXX or 0XXXXXXXX.'), + 'invalid': _('Enter phone number in form +386XXXXXXXX or 0XXXXXXXX.'), } phone_regex = re.compile('^(?:(?:00|\+)386|0)(\d{7,8})$') def clean(self, value): super(SIPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = value.replace(' ', '').replace('-', '').replace('/', '') m = self.phone_regex.match(value) diff --git a/django/contrib/localflavor/si/si_postalcodes.py b/django/contrib/localflavor/si/si_postalcodes.py index 7baac94e036..4d027afcffb 100644 --- a/django/contrib/localflavor/si/si_postalcodes.py +++ b/django/contrib/localflavor/si/si_postalcodes.py @@ -1,469 +1,470 @@ # *-* coding: utf-8 *-* +from __future__ import unicode_literals SI_POSTALCODES = [ - (1000, u'Ljubljana'), - (1215, u'Medvode'), - (1216, u'Smlednik'), - (1217, u'Vodice'), - (1218, u'Komenda'), - (1219, u'Laze v Tuhinju'), - (1221, u'Motnik'), - (1222, u'Trojane'), - (1223, u'Blagovica'), - (1225, u'Lukovica'), - (1230, u'Dom\u017eale'), - (1233, u'Dob'), - (1234, u'Menge\u0161'), - (1235, u'Radomlje'), - (1236, u'Trzin'), - (1241, u'Kamnik'), - (1242, u'Stahovica'), - (1251, u'Morav\u010de'), - (1252, u'Va\u010de'), - (1262, u'Dol pri Ljubljani'), - (1270, u'Litija'), - (1272, u'Pol\u0161nik'), - (1273, u'Dole pri Litiji'), - (1274, u'Gabrovka'), - (1275, u'\u0160martno pri Litiji'), - (1276, u'Primskovo'), - (1281, u'Kresnice'), - (1282, u'Sava'), - (1290, u'Grosuplje'), - (1291, u'\u0160kofljica'), - (1292, u'Ig'), - (1293, u'\u0160marje - Sap'), - (1294, u'Vi\u0161nja Gora'), - (1295, u'Ivan\u010dna Gorica'), - (1296, u'\u0160entvid pri Sti\u010dni'), - (1301, u'Krka'), - (1303, u'Zagradec'), - (1310, u'Ribnica'), - (1311, u'Turjak'), - (1312, u'Videm - Dobrepolje'), - (1313, u'Struge'), - (1314, u'Rob'), - (1315, u'Velike La\u0161\u010de'), - (1316, u'Ortnek'), - (1317, u'Sodra\u017eica'), - (1318, u'Lo\u0161ki Potok'), - (1319, u'Draga'), - (1330, u'Ko\u010devje'), - (1331, u'Dolenja vas'), - (1332, u'Stara Cerkev'), - (1336, u'Kostel'), - (1337, u'Osilnica'), - (1338, u'Ko\u010devska Reka'), - (1351, u'Brezovica pri Ljubljani'), - (1352, u'Preserje'), - (1353, u'Borovnica'), - (1354, u'Horjul'), - (1355, u'Polhov Gradec'), - (1356, u'Dobrova'), - (1357, u'Notranje Gorice'), - (1358, u'Log pri Brezovici'), - (1360, u'Vrhnika'), - (1370, u'Logatec'), - (1372, u'Hotedr\u0161ica'), - (1373, u'Rovte'), - (1380, u'Cerknica'), - (1381, u'Rakek'), - (1382, u'Begunje pri Cerknici'), - (1384, u'Grahovo'), - (1385, u'Nova vas'), - (1386, u'Stari trg pri Lo\u017eu'), - (1410, u'Zagorje ob Savi'), - (1411, u'Izlake'), - (1412, u'Kisovec'), - (1413, u'\u010cem\u0161enik'), - (1414, u'Podkum'), - (1420, u'Trbovlje'), - (1423, u'Dobovec'), - (1430, u'Hrastnik'), - (1431, u'Dol pri Hrastniku'), - (1432, u'Zidani Most'), - (1433, u'Rade\u010de'), - (1434, u'Loka pri Zidanem Mostu'), - (2000, u'Maribor'), - (2201, u'Zgornja Kungota'), - (2204, u'Miklav\u017e na Dravskem polju'), - (2205, u'Star\u0161e'), - (2206, u'Marjeta na Dravskem polju'), - (2208, u'Pohorje'), - (2211, u'Pesnica pri Mariboru'), - (2212, u'\u0160entilj v Slovenskih goricah'), - (2213, u'Zgornja Velka'), - (2214, u'Sladki vrh'), - (2215, u'Cer\u0161ak'), - (2221, u'Jarenina'), - (2222, u'Jakobski Dol'), - (2223, u'Jurovski Dol'), - (2229, u'Male\u010dnik'), - (2230, u'Lenart v Slovenskih goricah'), - (2231, u'Pernica'), - (2232, u'Voli\u010dina'), - (2233, u'Sveta Ana v Slovenskih goricah'), - (2234, u'Benedikt'), - (2235, u'Sveta Trojica v Slovenskih goricah'), - (2236, u'Cerkvenjak'), - (2241, u'Spodnji Duplek'), - (2242, u'Zgornja Korena'), - (2250, u'Ptuj'), - (2252, u'Dornava'), - (2253, u'Destrnik'), - (2254, u'Trnovska vas'), - (2255, u'Vitomarci'), - (2256, u'Jur\u0161inci'), - (2257, u'Polen\u0161ak'), - (2258, u'Sveti Toma\u017e'), - (2259, u'Ivanjkovci'), - (2270, u'Ormo\u017e'), - (2272, u'Gori\u0161nica'), - (2273, u'Podgorci'), - (2274, u'Velika Nedelja'), - (2275, u'Miklav\u017e pri Ormo\u017eu'), - (2276, u'Kog'), - (2277, u'Sredi\u0161\u010de ob Dravi'), - (2281, u'Markovci'), - (2282, u'Cirkulane'), - (2283, u'Zavr\u010d'), - (2284, u'Videm pri Ptuju'), - (2285, u'Zgornji Leskovec'), - (2286, u'Podlehnik'), - (2287, u'\u017detale'), - (2288, u'Hajdina'), - (2289, u'Stoperce'), - (2310, u'Slovenska Bistrica'), - (2311, u'Ho\u010de'), - (2312, u'Orehova vas'), - (2313, u'Fram'), - (2314, u'Zgornja Polskava'), - (2315, u'\u0160martno na Pohorju'), - (2316, u'Zgornja Lo\u017enica'), - (2317, u'Oplotnica'), - (2318, u'Laporje'), - (2319, u'Polj\u010dane'), - (2321, u'Makole'), - (2322, u'Maj\u0161perk'), - (2323, u'Ptujska Gora'), - (2324, u'Lovrenc na Dravskem polju'), - (2325, u'Kidri\u010devo'), - (2326, u'Cirkovce'), - (2327, u'Ra\u010de'), - (2331, u'Pragersko'), - (2341, u'Limbu\u0161'), - (2342, u'Ru\u0161e'), - (2343, u'Fala'), - (2344, u'Lovrenc na Pohorju'), - (2345, u'Bistrica ob Dravi'), - (2351, u'Kamnica'), - (2352, u'Selnica ob Dravi'), - (2353, u'Sv. Duh na Ostrem Vrhu'), - (2354, u'Bresternica'), - (2360, u'Radlje ob Dravi'), - (2361, u'O\u017ebalt'), - (2362, u'Kapla'), - (2363, u'Podvelka'), - (2364, u'Ribnica na Pohorju'), - (2365, u'Vuhred'), - (2366, u'Muta'), - (2367, u'Vuzenica'), - (2370, u'Dravograd'), - (2371, u'Trbonje'), - (2372, u'Libeli\u010de'), - (2373, u'\u0160entjan\u017e pri Dravogradu'), - (2380, u'Slovenj Gradec'), - (2381, u'Podgorje pri Slovenj Gradcu'), - (2382, u'Mislinja'), - (2383, u'\u0160martno pri Slovenj Gradcu'), - (2390, u'Ravne na Koro\u0161kem'), - (2391, u'Prevalje'), - (2392, u'Me\u017eica'), - (2393, u'\u010crna na Koro\u0161kem'), - (2394, u'Kotlje'), - (3000, u'Celje'), - (3201, u'\u0160martno v Ro\u017eni dolini'), - (3202, u'Ljube\u010dna'), - (3203, u'Nova Cerkev'), - (3204, u'Dobrna'), - (3205, u'Vitanje'), - (3206, u'Stranice'), - (3210, u'Slovenske Konjice'), - (3211, u'\u0160kofja vas'), - (3212, u'Vojnik'), - (3213, u'Frankolovo'), - (3214, u'Zre\u010de'), - (3215, u'Lo\u010de'), - (3220, u'\u0160tore'), - (3221, u'Teharje'), - (3222, u'Dramlje'), - (3223, u'Loka pri \u017dusmu'), - (3224, u'Dobje pri Planini'), - (3225, u'Planina pri Sevnici'), - (3230, u'\u0160entjur'), - (3231, u'Grobelno'), - (3232, u'Ponikva'), - (3233, u'Kalobje'), - (3240, u'\u0160marje pri Jel\u0161ah'), - (3241, u'Podplat'), - (3250, u'Roga\u0161ka Slatina'), - (3252, u'Rogatec'), - (3253, u'Pristava pri Mestinju'), - (3254, u'Pod\u010detrtek'), - (3255, u'Bu\u010de'), - (3256, u'Bistrica ob Sotli'), - (3257, u'Podsreda'), - (3260, u'Kozje'), - (3261, u'Lesi\u010dno'), - (3262, u'Prevorje'), - (3263, u'Gorica pri Slivnici'), - (3264, u'Sveti \u0160tefan'), - (3270, u'La\u0161ko'), - (3271, u'\u0160entrupert'), - (3272, u'Rimske Toplice'), - (3273, u'Jurklo\u0161ter'), - (3301, u'Petrov\u010de'), - (3302, u'Gri\u017ee'), - (3303, u'Gomilsko'), - (3304, u'Tabor'), - (3305, u'Vransko'), - (3310, u'\u017dalec'), - (3311, u'\u0160empeter v Savinjski dolini'), - (3312, u'Prebold'), - (3313, u'Polzela'), - (3314, u'Braslov\u010de'), - (3320, u'Velenje - dostava'), - (3322, u'Velenje - po\u0161tni predali'), - (3325, u'\u0160o\u0161tanj'), - (3326, u'Topol\u0161ica'), - (3327, u'\u0160martno ob Paki'), - (3330, u'Mozirje'), - (3331, u'Nazarje'), - (3332, u'Re\u010dica ob Savinji'), - (3333, u'Ljubno ob Savinji'), - (3334, u'Lu\u010de'), - (3335, u'Sol\u010dava'), - (3341, u'\u0160martno ob Dreti'), - (3342, u'Gornji Grad'), - (4000, u'Kranj'), - (4201, u'Zgornja Besnica'), - (4202, u'Naklo'), - (4203, u'Duplje'), - (4204, u'Golnik'), - (4205, u'Preddvor'), - (4206, u'Zgornje Jezersko'), - (4207, u'Cerklje na Gorenjskem'), - (4208, u'\u0160en\u010dur'), - (4209, u'\u017dabnica'), - (4210, u'Brnik - aerodrom'), - (4211, u'Mav\u010di\u010de'), - (4212, u'Visoko'), - (4220, u'\u0160kofja Loka'), - (4223, u'Poljane nad \u0160kofjo Loko'), - (4224, u'Gorenja vas'), - (4225, u'Sovodenj'), - (4226, u'\u017diri'), - (4227, u'Selca'), - (4228, u'\u017delezniki'), - (4229, u'Sorica'), - (4240, u'Radovljica'), - (4243, u'Brezje'), - (4244, u'Podnart'), - (4245, u'Kropa'), - (4246, u'Kamna Gorica'), - (4247, u'Zgornje Gorje'), - (4248, u'Lesce'), - (4260, u'Bled'), - (4263, u'Bohinjska Bela'), - (4264, u'Bohinjska Bistrica'), - (4265, u'Bohinjsko jezero'), - (4267, u'Srednja vas v Bohinju'), - (4270, u'Jesenice'), - (4273, u'Blejska Dobrava'), - (4274, u'\u017dirovnica'), - (4275, u'Begunje na Gorenjskem'), - (4276, u'Hru\u0161ica'), - (4280, u'Kranjska Gora'), - (4281, u'Mojstrana'), - (4282, u'Gozd Martuljek'), - (4283, u'Rate\u010de - Planica'), - (4290, u'Tr\u017ei\u010d'), - (4294, u'Kri\u017ee'), - (5000, u'Nova Gorica'), - (5210, u'Deskle'), - (5211, u'Kojsko'), - (5212, u'Dobrovo v Brdih'), - (5213, u'Kanal'), - (5214, u'Kal nad Kanalom'), - (5215, u'Ro\u010dinj'), - (5216, u'Most na So\u010di'), - (5220, u'Tolmin'), - (5222, u'Kobarid'), - (5223, u'Breginj'), - (5224, u'Srpenica'), - (5230, u'Bovec'), - (5231, u'Log pod Mangartom'), - (5232, u'So\u010da'), - (5242, u'Grahovo ob Ba\u010di'), - (5243, u'Podbrdo'), - (5250, u'Solkan'), - (5251, u'Grgar'), - (5252, u'Trnovo pri Gorici'), - (5253, u'\u010cepovan'), - (5261, u'\u0160empas'), - (5262, u'\u010crni\u010de'), - (5263, u'Dobravlje'), - (5270, u'Ajdov\u0161\u010dina'), - (5271, u'Vipava'), - (5272, u'Podnanos'), - (5273, u'Col'), - (5274, u'\u010crni Vrh nad Idrijo'), - (5275, u'Godovi\u010d'), - (5280, u'Idrija'), - (5281, u'Spodnja Idrija'), - (5282, u'Cerkno'), - (5283, u'Slap ob Idrijci'), - (5290, u'\u0160empeter pri Gorici'), - (5291, u'Miren'), - (5292, u'Ren\u010de'), - (5293, u'Vol\u010dja Draga'), - (5294, u'Dornberk'), - (5295, u'Branik'), - (5296, u'Kostanjevica na Krasu'), - (5297, u'Prva\u010dina'), - (6000, u'Koper'), - (6210, u'Se\u017eana'), - (6215, u'Diva\u010da'), - (6216, u'Podgorje'), - (6217, u'Vremski Britof'), - (6219, u'Lokev'), - (6221, u'Dutovlje'), - (6222, u'\u0160tanjel'), - (6223, u'Komen'), - (6224, u'Seno\u017ee\u010de'), - (6225, u'Hru\u0161evje'), - (6230, u'Postojna'), - (6232, u'Planina'), - (6240, u'Kozina'), - (6242, u'Materija'), - (6243, u'Obrov'), - (6244, u'Podgrad'), - (6250, u'Ilirska Bistrica'), - (6251, u'Ilirska Bistrica - Trnovo'), - (6253, u'Kne\u017eak'), - (6254, u'Jel\u0161ane'), - (6255, u'Prem'), - (6256, u'Ko\u0161ana'), - (6257, u'Pivka'), - (6258, u'Prestranek'), - (6271, u'Dekani'), - (6272, u'Gra\u010di\u0161\u010de'), - (6273, u'Marezige'), - (6274, u'\u0160marje'), - (6275, u'\u010crni Kal'), - (6276, u'Pobegi'), - (6280, u'Ankaran - Ancarano'), - (6281, u'\u0160kofije'), - (6310, u'Izola - Isola'), - (6320, u'Portoro\u017e - Portorose'), - (6330, u'Piran - Pirano'), - (6333, u'Se\u010dovlje - Sicciole'), - (8000, u'Novo mesto'), - (8210, u'Trebnje'), - (8211, u'Dobrni\u010d'), - (8212, u'Velika Loka'), - (8213, u'Veliki Gaber'), - (8216, u'Mirna Pe\u010d'), - (8220, u'\u0160marje\u0161ke Toplice'), - (8222, u'Oto\u010dec'), - (8230, u'Mokronog'), - (8231, u'Trebelno'), - (8232, u'\u0160entrupert'), - (8233, u'Mirna'), - (8250, u'Bre\u017eice'), - (8251, u'\u010cate\u017e ob Savi'), - (8253, u'Arti\u010de'), - (8254, u'Globoko'), - (8255, u'Pi\u0161ece'), - (8256, u'Sromlje'), - (8257, u'Dobova'), - (8258, u'Kapele'), - (8259, u'Bizeljsko'), - (8261, u'Jesenice na Dolenjskem'), - (8262, u'Kr\u0161ka vas'), - (8263, u'Cerklje ob Krki'), - (8270, u'Kr\u0161ko'), - (8272, u'Zdole'), - (8273, u'Leskovec pri Kr\u0161kem'), - (8274, u'Raka'), - (8275, u'\u0160kocjan'), - (8276, u'Bu\u010dka'), - (8280, u'Brestanica'), - (8281, u'Senovo'), - (8282, u'Koprivnica'), - (8283, u'Blanca'), - (8290, u'Sevnica'), - (8292, u'Zabukovje'), - (8293, u'Studenec'), - (8294, u'Bo\u0161tanj'), - (8295, u'Tr\u017ei\u0161\u010de'), - (8296, u'Krmelj'), - (8297, u'\u0160entjan\u017e'), - (8310, u'\u0160entjernej'), - (8311, u'Kostanjevica na Krki'), - (8312, u'Podbo\u010dje'), - (8321, u'Brusnice'), - (8322, u'Stopi\u010de'), - (8323, u'Ur\u0161na sela'), - (8330, u'Metlika'), - (8331, u'Suhor'), - (8332, u'Gradac'), - (8333, u'Semi\u010d'), - (8340, u'\u010crnomelj'), - (8341, u'Adle\u0161i\u010di'), - (8342, u'Stari trg ob Kolpi'), - (8343, u'Dragatu\u0161'), - (8344, u'Vinica pri \u010crnomlju'), - (8350, u'Dolenjske Toplice'), - (8351, u'Stra\u017ea'), - (8360, u'\u017du\u017eemberk'), - (8361, u'Dvor'), - (8362, u'Hinje'), - (9000, u'Murska Sobota'), - (9201, u'Puconci'), - (9202, u'Ma\u010dkovci'), - (9203, u'Petrovci'), - (9204, u'\u0160alovci'), - (9205, u'Hodo\u0161 - Hodos'), - (9206, u'Kri\u017eevci'), - (9207, u'Prosenjakovci - Partosfalva'), - (9208, u'Fokovci'), - (9220, u'Lendava - Lendva'), - (9221, u'Martjanci'), - (9222, u'Bogojina'), - (9223, u'Dobrovnik - Dobronak'), - (9224, u'Turni\u0161\u010de'), - (9225, u'Velika Polana'), - (9226, u'Moravske Toplice'), - (9227, u'Kobilje'), - (9231, u'Beltinci'), - (9232, u'\u010cren\u0161ovci'), - (9233, u'Odranci'), - (9240, u'Ljutomer'), - (9241, u'Ver\u017eej'), - (9242, u'Kri\u017eevci pri Ljutomeru'), - (9243, u'Mala Nedelja'), - (9244, u'Sveti Jurij ob \u0160\u010davnici'), - (9245, u'Spodnji Ivanjci'), - (9250, u'Gornja Radgona'), - (9251, u'Ti\u0161ina'), - (9252, u'Radenci'), - (9253, u'Apa\u010de'), - (9261, u'Cankova'), - (9262, u'Roga\u0161ovci'), - (9263, u'Kuzma'), - (9264, u'Grad'), - (9265, u'Bodonci'), + (1000, 'Ljubljana'), + (1215, 'Medvode'), + (1216, 'Smlednik'), + (1217, 'Vodice'), + (1218, 'Komenda'), + (1219, 'Laze v Tuhinju'), + (1221, 'Motnik'), + (1222, 'Trojane'), + (1223, 'Blagovica'), + (1225, 'Lukovica'), + (1230, 'Dom\u017eale'), + (1233, 'Dob'), + (1234, 'Menge\u0161'), + (1235, 'Radomlje'), + (1236, 'Trzin'), + (1241, 'Kamnik'), + (1242, 'Stahovica'), + (1251, 'Morav\u010de'), + (1252, 'Va\u010de'), + (1262, 'Dol pri Ljubljani'), + (1270, 'Litija'), + (1272, 'Pol\u0161nik'), + (1273, 'Dole pri Litiji'), + (1274, 'Gabrovka'), + (1275, '\u0160martno pri Litiji'), + (1276, 'Primskovo'), + (1281, 'Kresnice'), + (1282, 'Sava'), + (1290, 'Grosuplje'), + (1291, '\u0160kofljica'), + (1292, 'Ig'), + (1293, '\u0160marje - Sap'), + (1294, 'Vi\u0161nja Gora'), + (1295, 'Ivan\u010dna Gorica'), + (1296, '\u0160entvid pri Sti\u010dni'), + (1301, 'Krka'), + (1303, 'Zagradec'), + (1310, 'Ribnica'), + (1311, 'Turjak'), + (1312, 'Videm - Dobrepolje'), + (1313, 'Struge'), + (1314, 'Rob'), + (1315, 'Velike La\u0161\u010de'), + (1316, 'Ortnek'), + (1317, 'Sodra\u017eica'), + (1318, 'Lo\u0161ki Potok'), + (1319, 'Draga'), + (1330, 'Ko\u010devje'), + (1331, 'Dolenja vas'), + (1332, 'Stara Cerkev'), + (1336, 'Kostel'), + (1337, 'Osilnica'), + (1338, 'Ko\u010devska Reka'), + (1351, 'Brezovica pri Ljubljani'), + (1352, 'Preserje'), + (1353, 'Borovnica'), + (1354, 'Horjul'), + (1355, 'Polhov Gradec'), + (1356, 'Dobrova'), + (1357, 'Notranje Gorice'), + (1358, 'Log pri Brezovici'), + (1360, 'Vrhnika'), + (1370, 'Logatec'), + (1372, 'Hotedr\u0161ica'), + (1373, 'Rovte'), + (1380, 'Cerknica'), + (1381, 'Rakek'), + (1382, 'Begunje pri Cerknici'), + (1384, 'Grahovo'), + (1385, 'Nova vas'), + (1386, 'Stari trg pri Lo\u017eu'), + (1410, 'Zagorje ob Savi'), + (1411, 'Izlake'), + (1412, 'Kisovec'), + (1413, '\u010cem\u0161enik'), + (1414, 'Podkum'), + (1420, 'Trbovlje'), + (1423, 'Dobovec'), + (1430, 'Hrastnik'), + (1431, 'Dol pri Hrastniku'), + (1432, 'Zidani Most'), + (1433, 'Rade\u010de'), + (1434, 'Loka pri Zidanem Mostu'), + (2000, 'Maribor'), + (2201, 'Zgornja Kungota'), + (2204, 'Miklav\u017e na Dravskem polju'), + (2205, 'Star\u0161e'), + (2206, 'Marjeta na Dravskem polju'), + (2208, 'Pohorje'), + (2211, 'Pesnica pri Mariboru'), + (2212, '\u0160entilj v Slovenskih goricah'), + (2213, 'Zgornja Velka'), + (2214, 'Sladki vrh'), + (2215, 'Cer\u0161ak'), + (2221, 'Jarenina'), + (2222, 'Jakobski Dol'), + (2223, 'Jurovski Dol'), + (2229, 'Male\u010dnik'), + (2230, 'Lenart v Slovenskih goricah'), + (2231, 'Pernica'), + (2232, 'Voli\u010dina'), + (2233, 'Sveta Ana v Slovenskih goricah'), + (2234, 'Benedikt'), + (2235, 'Sveta Trojica v Slovenskih goricah'), + (2236, 'Cerkvenjak'), + (2241, 'Spodnji Duplek'), + (2242, 'Zgornja Korena'), + (2250, 'Ptuj'), + (2252, 'Dornava'), + (2253, 'Destrnik'), + (2254, 'Trnovska vas'), + (2255, 'Vitomarci'), + (2256, 'Jur\u0161inci'), + (2257, 'Polen\u0161ak'), + (2258, 'Sveti Toma\u017e'), + (2259, 'Ivanjkovci'), + (2270, 'Ormo\u017e'), + (2272, 'Gori\u0161nica'), + (2273, 'Podgorci'), + (2274, 'Velika Nedelja'), + (2275, 'Miklav\u017e pri Ormo\u017eu'), + (2276, 'Kog'), + (2277, 'Sredi\u0161\u010de ob Dravi'), + (2281, 'Markovci'), + (2282, 'Cirkulane'), + (2283, 'Zavr\u010d'), + (2284, 'Videm pri Ptuju'), + (2285, 'Zgornji Leskovec'), + (2286, 'Podlehnik'), + (2287, '\u017detale'), + (2288, 'Hajdina'), + (2289, 'Stoperce'), + (2310, 'Slovenska Bistrica'), + (2311, 'Ho\u010de'), + (2312, 'Orehova vas'), + (2313, 'Fram'), + (2314, 'Zgornja Polskava'), + (2315, '\u0160martno na Pohorju'), + (2316, 'Zgornja Lo\u017enica'), + (2317, 'Oplotnica'), + (2318, 'Laporje'), + (2319, 'Polj\u010dane'), + (2321, 'Makole'), + (2322, 'Maj\u0161perk'), + (2323, 'Ptujska Gora'), + (2324, 'Lovrenc na Dravskem polju'), + (2325, 'Kidri\u010devo'), + (2326, 'Cirkovce'), + (2327, 'Ra\u010de'), + (2331, 'Pragersko'), + (2341, 'Limbu\u0161'), + (2342, 'Ru\u0161e'), + (2343, 'Fala'), + (2344, 'Lovrenc na Pohorju'), + (2345, 'Bistrica ob Dravi'), + (2351, 'Kamnica'), + (2352, 'Selnica ob Dravi'), + (2353, 'Sv. Duh na Ostrem Vrhu'), + (2354, 'Bresternica'), + (2360, 'Radlje ob Dravi'), + (2361, 'O\u017ebalt'), + (2362, 'Kapla'), + (2363, 'Podvelka'), + (2364, 'Ribnica na Pohorju'), + (2365, 'Vuhred'), + (2366, 'Muta'), + (2367, 'Vuzenica'), + (2370, 'Dravograd'), + (2371, 'Trbonje'), + (2372, 'Libeli\u010de'), + (2373, '\u0160entjan\u017e pri Dravogradu'), + (2380, 'Slovenj Gradec'), + (2381, 'Podgorje pri Slovenj Gradcu'), + (2382, 'Mislinja'), + (2383, '\u0160martno pri Slovenj Gradcu'), + (2390, 'Ravne na Koro\u0161kem'), + (2391, 'Prevalje'), + (2392, 'Me\u017eica'), + (2393, '\u010crna na Koro\u0161kem'), + (2394, 'Kotlje'), + (3000, 'Celje'), + (3201, '\u0160martno v Ro\u017eni dolini'), + (3202, 'Ljube\u010dna'), + (3203, 'Nova Cerkev'), + (3204, 'Dobrna'), + (3205, 'Vitanje'), + (3206, 'Stranice'), + (3210, 'Slovenske Konjice'), + (3211, '\u0160kofja vas'), + (3212, 'Vojnik'), + (3213, 'Frankolovo'), + (3214, 'Zre\u010de'), + (3215, 'Lo\u010de'), + (3220, '\u0160tore'), + (3221, 'Teharje'), + (3222, 'Dramlje'), + (3223, 'Loka pri \u017dusmu'), + (3224, 'Dobje pri Planini'), + (3225, 'Planina pri Sevnici'), + (3230, '\u0160entjur'), + (3231, 'Grobelno'), + (3232, 'Ponikva'), + (3233, 'Kalobje'), + (3240, '\u0160marje pri Jel\u0161ah'), + (3241, 'Podplat'), + (3250, 'Roga\u0161ka Slatina'), + (3252, 'Rogatec'), + (3253, 'Pristava pri Mestinju'), + (3254, 'Pod\u010detrtek'), + (3255, 'Bu\u010de'), + (3256, 'Bistrica ob Sotli'), + (3257, 'Podsreda'), + (3260, 'Kozje'), + (3261, 'Lesi\u010dno'), + (3262, 'Prevorje'), + (3263, 'Gorica pri Slivnici'), + (3264, 'Sveti \u0160tefan'), + (3270, 'La\u0161ko'), + (3271, '\u0160entrupert'), + (3272, 'Rimske Toplice'), + (3273, 'Jurklo\u0161ter'), + (3301, 'Petrov\u010de'), + (3302, 'Gri\u017ee'), + (3303, 'Gomilsko'), + (3304, 'Tabor'), + (3305, 'Vransko'), + (3310, '\u017dalec'), + (3311, '\u0160empeter v Savinjski dolini'), + (3312, 'Prebold'), + (3313, 'Polzela'), + (3314, 'Braslov\u010de'), + (3320, 'Velenje - dostava'), + (3322, 'Velenje - po\u0161tni predali'), + (3325, '\u0160o\u0161tanj'), + (3326, 'Topol\u0161ica'), + (3327, '\u0160martno ob Paki'), + (3330, 'Mozirje'), + (3331, 'Nazarje'), + (3332, 'Re\u010dica ob Savinji'), + (3333, 'Ljubno ob Savinji'), + (3334, 'Lu\u010de'), + (3335, 'Sol\u010dava'), + (3341, '\u0160martno ob Dreti'), + (3342, 'Gornji Grad'), + (4000, 'Kranj'), + (4201, 'Zgornja Besnica'), + (4202, 'Naklo'), + (4203, 'Duplje'), + (4204, 'Golnik'), + (4205, 'Preddvor'), + (4206, 'Zgornje Jezersko'), + (4207, 'Cerklje na Gorenjskem'), + (4208, '\u0160en\u010dur'), + (4209, '\u017dabnica'), + (4210, 'Brnik - aerodrom'), + (4211, 'Mav\u010di\u010de'), + (4212, 'Visoko'), + (4220, '\u0160kofja Loka'), + (4223, 'Poljane nad \u0160kofjo Loko'), + (4224, 'Gorenja vas'), + (4225, 'Sovodenj'), + (4226, '\u017diri'), + (4227, 'Selca'), + (4228, '\u017delezniki'), + (4229, 'Sorica'), + (4240, 'Radovljica'), + (4243, 'Brezje'), + (4244, 'Podnart'), + (4245, 'Kropa'), + (4246, 'Kamna Gorica'), + (4247, 'Zgornje Gorje'), + (4248, 'Lesce'), + (4260, 'Bled'), + (4263, 'Bohinjska Bela'), + (4264, 'Bohinjska Bistrica'), + (4265, 'Bohinjsko jezero'), + (4267, 'Srednja vas v Bohinju'), + (4270, 'Jesenice'), + (4273, 'Blejska Dobrava'), + (4274, '\u017dirovnica'), + (4275, 'Begunje na Gorenjskem'), + (4276, 'Hru\u0161ica'), + (4280, 'Kranjska Gora'), + (4281, 'Mojstrana'), + (4282, 'Gozd Martuljek'), + (4283, 'Rate\u010de - Planica'), + (4290, 'Tr\u017ei\u010d'), + (4294, 'Kri\u017ee'), + (5000, 'Nova Gorica'), + (5210, 'Deskle'), + (5211, 'Kojsko'), + (5212, 'Dobrovo v Brdih'), + (5213, 'Kanal'), + (5214, 'Kal nad Kanalom'), + (5215, 'Ro\u010dinj'), + (5216, 'Most na So\u010di'), + (5220, 'Tolmin'), + (5222, 'Kobarid'), + (5223, 'Breginj'), + (5224, 'Srpenica'), + (5230, 'Bovec'), + (5231, 'Log pod Mangartom'), + (5232, 'So\u010da'), + (5242, 'Grahovo ob Ba\u010di'), + (5243, 'Podbrdo'), + (5250, 'Solkan'), + (5251, 'Grgar'), + (5252, 'Trnovo pri Gorici'), + (5253, '\u010cepovan'), + (5261, '\u0160empas'), + (5262, '\u010crni\u010de'), + (5263, 'Dobravlje'), + (5270, 'Ajdov\u0161\u010dina'), + (5271, 'Vipava'), + (5272, 'Podnanos'), + (5273, 'Col'), + (5274, '\u010crni Vrh nad Idrijo'), + (5275, 'Godovi\u010d'), + (5280, 'Idrija'), + (5281, 'Spodnja Idrija'), + (5282, 'Cerkno'), + (5283, 'Slap ob Idrijci'), + (5290, '\u0160empeter pri Gorici'), + (5291, 'Miren'), + (5292, 'Ren\u010de'), + (5293, 'Vol\u010dja Draga'), + (5294, 'Dornberk'), + (5295, 'Branik'), + (5296, 'Kostanjevica na Krasu'), + (5297, 'Prva\u010dina'), + (6000, 'Koper'), + (6210, 'Se\u017eana'), + (6215, 'Diva\u010da'), + (6216, 'Podgorje'), + (6217, 'Vremski Britof'), + (6219, 'Lokev'), + (6221, 'Dutovlje'), + (6222, '\u0160tanjel'), + (6223, 'Komen'), + (6224, 'Seno\u017ee\u010de'), + (6225, 'Hru\u0161evje'), + (6230, 'Postojna'), + (6232, 'Planina'), + (6240, 'Kozina'), + (6242, 'Materija'), + (6243, 'Obrov'), + (6244, 'Podgrad'), + (6250, 'Ilirska Bistrica'), + (6251, 'Ilirska Bistrica - Trnovo'), + (6253, 'Kne\u017eak'), + (6254, 'Jel\u0161ane'), + (6255, 'Prem'), + (6256, 'Ko\u0161ana'), + (6257, 'Pivka'), + (6258, 'Prestranek'), + (6271, 'Dekani'), + (6272, 'Gra\u010di\u0161\u010de'), + (6273, 'Marezige'), + (6274, '\u0160marje'), + (6275, '\u010crni Kal'), + (6276, 'Pobegi'), + (6280, 'Ankaran - Ancarano'), + (6281, '\u0160kofije'), + (6310, 'Izola - Isola'), + (6320, 'Portoro\u017e - Portorose'), + (6330, 'Piran - Pirano'), + (6333, 'Se\u010dovlje - Sicciole'), + (8000, 'Novo mesto'), + (8210, 'Trebnje'), + (8211, 'Dobrni\u010d'), + (8212, 'Velika Loka'), + (8213, 'Veliki Gaber'), + (8216, 'Mirna Pe\u010d'), + (8220, '\u0160marje\u0161ke Toplice'), + (8222, 'Oto\u010dec'), + (8230, 'Mokronog'), + (8231, 'Trebelno'), + (8232, '\u0160entrupert'), + (8233, 'Mirna'), + (8250, 'Bre\u017eice'), + (8251, '\u010cate\u017e ob Savi'), + (8253, 'Arti\u010de'), + (8254, 'Globoko'), + (8255, 'Pi\u0161ece'), + (8256, 'Sromlje'), + (8257, 'Dobova'), + (8258, 'Kapele'), + (8259, 'Bizeljsko'), + (8261, 'Jesenice na Dolenjskem'), + (8262, 'Kr\u0161ka vas'), + (8263, 'Cerklje ob Krki'), + (8270, 'Kr\u0161ko'), + (8272, 'Zdole'), + (8273, 'Leskovec pri Kr\u0161kem'), + (8274, 'Raka'), + (8275, '\u0160kocjan'), + (8276, 'Bu\u010dka'), + (8280, 'Brestanica'), + (8281, 'Senovo'), + (8282, 'Koprivnica'), + (8283, 'Blanca'), + (8290, 'Sevnica'), + (8292, 'Zabukovje'), + (8293, 'Studenec'), + (8294, 'Bo\u0161tanj'), + (8295, 'Tr\u017ei\u0161\u010de'), + (8296, 'Krmelj'), + (8297, '\u0160entjan\u017e'), + (8310, '\u0160entjernej'), + (8311, 'Kostanjevica na Krki'), + (8312, 'Podbo\u010dje'), + (8321, 'Brusnice'), + (8322, 'Stopi\u010de'), + (8323, 'Ur\u0161na sela'), + (8330, 'Metlika'), + (8331, 'Suhor'), + (8332, 'Gradac'), + (8333, 'Semi\u010d'), + (8340, '\u010crnomelj'), + (8341, 'Adle\u0161i\u010di'), + (8342, 'Stari trg ob Kolpi'), + (8343, 'Dragatu\u0161'), + (8344, 'Vinica pri \u010crnomlju'), + (8350, 'Dolenjske Toplice'), + (8351, 'Stra\u017ea'), + (8360, '\u017du\u017eemberk'), + (8361, 'Dvor'), + (8362, 'Hinje'), + (9000, 'Murska Sobota'), + (9201, 'Puconci'), + (9202, 'Ma\u010dkovci'), + (9203, 'Petrovci'), + (9204, '\u0160alovci'), + (9205, 'Hodo\u0161 - Hodos'), + (9206, 'Kri\u017eevci'), + (9207, 'Prosenjakovci - Partosfalva'), + (9208, 'Fokovci'), + (9220, 'Lendava - Lendva'), + (9221, 'Martjanci'), + (9222, 'Bogojina'), + (9223, 'Dobrovnik - Dobronak'), + (9224, 'Turni\u0161\u010de'), + (9225, 'Velika Polana'), + (9226, 'Moravske Toplice'), + (9227, 'Kobilje'), + (9231, 'Beltinci'), + (9232, '\u010cren\u0161ovci'), + (9233, 'Odranci'), + (9240, 'Ljutomer'), + (9241, 'Ver\u017eej'), + (9242, 'Kri\u017eevci pri Ljutomeru'), + (9243, 'Mala Nedelja'), + (9244, 'Sveti Jurij ob \u0160\u010davnici'), + (9245, 'Spodnji Ivanjci'), + (9250, 'Gornja Radgona'), + (9251, 'Ti\u0161ina'), + (9252, 'Radenci'), + (9253, 'Apa\u010de'), + (9261, 'Cankova'), + (9262, 'Roga\u0161ovci'), + (9263, 'Kuzma'), + (9264, 'Grad'), + (9265, 'Bodonci'), ] SI_POSTALCODES_CHOICES = sorted(SI_POSTALCODES, key=lambda k: k[1]) diff --git a/django/contrib/localflavor/sk/forms.py b/django/contrib/localflavor/sk/forms.py index 83afeb41b98..11d44cc4d25 100644 --- a/django/contrib/localflavor/sk/forms.py +++ b/django/contrib/localflavor/sk/forms.py @@ -2,7 +2,7 @@ Slovak-specific form helpers """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from django.contrib.localflavor.sk.sk_districts import DISTRICT_CHOICES from django.contrib.localflavor.sk.sk_regions import REGION_CHOICES @@ -30,7 +30,7 @@ class SKPostalCodeField(RegexField): Valid form is XXXXX or XXX XX, where X represents integer. """ default_error_messages = { - 'invalid': _(u'Enter a postal code in the format XXXXX or XXX XX.'), + 'invalid': _('Enter a postal code in the format XXXXX or XXX XX.'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): diff --git a/django/contrib/localflavor/tr/forms.py b/django/contrib/localflavor/tr/forms.py index 77a2b419861..1ffbc173619 100644 --- a/django/contrib/localflavor/tr/forms.py +++ b/django/contrib/localflavor/tr/forms.py @@ -2,7 +2,7 @@ TR-specific Form helpers """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re @@ -18,7 +18,7 @@ phone_digits_re = re.compile(r'^(\+90|0)? ?(([1-9]\d{2})|\([1-9]\d{2}\)) ?([2-9] class TRPostalCodeField(RegexField): default_error_messages = { - 'invalid': _(u'Enter a postal code in the format XXXXX.'), + 'invalid': _('Enter a postal code in the format XXXXX.'), } def __init__(self, max_length=5, min_length=5, *args, **kwargs): @@ -28,7 +28,7 @@ class TRPostalCodeField(RegexField): def clean(self, value): value = super(TRPostalCodeField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' if len(value) != 5: raise ValidationError(self.error_messages['invalid']) province_code = int(value[:2]) @@ -39,17 +39,17 @@ class TRPostalCodeField(RegexField): class TRPhoneNumberField(CharField): default_error_messages = { - 'invalid': _(u'Phone numbers must be in 0XXX XXX XXXX format.'), + 'invalid': _('Phone numbers must be in 0XXX XXX XXXX format.'), } def clean(self, value): super(TRPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = re.sub('(\(|\)|\s+)', '', smart_unicode(value)) m = phone_digits_re.search(value) if m: - return u'%s%s' % (m.group(2), m.group(4)) + return '%s%s' % (m.group(2), m.group(4)) raise ValidationError(self.error_messages['invalid']) class TRIdentificationNumberField(Field): @@ -66,14 +66,14 @@ class TRIdentificationNumberField(Field): sum(1st to 10th) % 10 = 11th digit """ default_error_messages = { - 'invalid': _(u'Enter a valid Turkish Identification number.'), - 'not_11': _(u'Turkish Identification number must be 11 digits.'), + 'invalid': _('Enter a valid Turkish Identification number.'), + 'not_11': _('Turkish Identification number must be 11 digits.'), } def clean(self, value): super(TRIdentificationNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' if len(value) != 11: raise ValidationError(self.error_messages['not_11']) if not re.match(r'^\d{11}$', value): diff --git a/django/contrib/localflavor/us/forms.py b/django/contrib/localflavor/us/forms.py index 0a79c40a47d..33e533b4cea 100644 --- a/django/contrib/localflavor/us/forms.py +++ b/django/contrib/localflavor/us/forms.py @@ -2,7 +2,7 @@ USA-specific Form helpers """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re @@ -33,11 +33,11 @@ class USPhoneNumberField(CharField): def clean(self, value): super(USPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' value = re.sub('(\(|\)|\s+)', '', smart_unicode(value)) m = phone_digits_re.search(value) if m: - return u'%s-%s-%s' % (m.group(1), m.group(2), m.group(3)) + return '%s-%s-%s' % (m.group(1), m.group(2), m.group(3)) raise ValidationError(self.error_messages['invalid']) class USSocialSecurityNumberField(Field): @@ -62,7 +62,7 @@ class USSocialSecurityNumberField(Field): def clean(self, value): super(USSocialSecurityNumberField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' match = re.match(ssn_re, value) if not match: raise ValidationError(self.error_messages['invalid']) @@ -80,7 +80,7 @@ class USSocialSecurityNumberField(Field): value == '078-05-1120' or \ value == '219-09-9999': raise ValidationError(self.error_messages['invalid']) - return u'%s-%s-%s' % (area, group, serial) + return '%s-%s-%s' % (area, group, serial) class USStateField(Field): """ @@ -96,7 +96,7 @@ class USStateField(Field): from django.contrib.localflavor.us.us_states import STATES_NORMALIZED super(USStateField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' try: value = value.strip().lower() except AttributeError: diff --git a/django/contrib/localflavor/uy/forms.py b/django/contrib/localflavor/uy/forms.py index 211216222d8..658defc0f00 100644 --- a/django/contrib/localflavor/uy/forms.py +++ b/django/contrib/localflavor/uy/forms.py @@ -3,7 +3,7 @@ UY-specific form helpers. """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from django.core.validators import EMPTY_VALUES from django.forms.fields import Select, RegexField @@ -47,7 +47,7 @@ class UYCIField(RegexField): value = super(UYCIField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' match = self.regex.match(value) if not match: raise ValidationError(self.error_messages['invalid']) diff --git a/django/contrib/localflavor/uy/uy_departaments.py b/django/contrib/localflavor/uy/uy_departaments.py index 97795f8e82c..800937c582c 100644 --- a/django/contrib/localflavor/uy/uy_departaments.py +++ b/django/contrib/localflavor/uy/uy_departaments.py @@ -1,24 +1,25 @@ # -*- coding: utf-8 -*- """A list of Urguayan departaments as `choices` in a formfield.""" +from __future__ import unicode_literals DEPARTAMENT_CHOICES = ( - ('G', u'Artigas'), - ('A', u'Canelones'), - ('E', u'Cerro Largo'), - ('L', u'Colonia'), - ('Q', u'Durazno'), - ('N', u'Flores'), - ('O', u'Florida'), - ('P', u'Lavalleja'), - ('B', u'Maldonado'), - ('S', u'Montevideo'), - ('I', u'Paysandú'), - ('J', u'Río Negro'), - ('F', u'Rivera'), - ('C', u'Rocha'), - ('H', u'Salto'), - ('M', u'San José'), - ('K', u'Soriano'), - ('R', u'Tacuarembó'), - ('D', u'Treinta y Tres'), + ('G', 'Artigas'), + ('A', 'Canelones'), + ('E', 'Cerro Largo'), + ('L', 'Colonia'), + ('Q', 'Durazno'), + ('N', 'Flores'), + ('O', 'Florida'), + ('P', 'Lavalleja'), + ('B', 'Maldonado'), + ('S', 'Montevideo'), + ('I', 'Paysandú'), + ('J', 'Río Negro'), + ('F', 'Rivera'), + ('C', 'Rocha'), + ('H', 'Salto'), + ('M', 'San José'), + ('K', 'Soriano'), + ('R', 'Tacuarembó'), + ('D', 'Treinta y Tres'), ) diff --git a/django/contrib/localflavor/za/forms.py b/django/contrib/localflavor/za/forms.py index a9e2cd60c89..a818c144282 100644 --- a/django/contrib/localflavor/za/forms.py +++ b/django/contrib/localflavor/za/forms.py @@ -1,6 +1,7 @@ """ South Africa-specific Form helpers """ +from __future__ import unicode_literals from django.core.validators import EMPTY_VALUES from django.forms import ValidationError @@ -18,14 +19,14 @@ class ZAIDField(CharField): check for the birthdate """ default_error_messages = { - 'invalid': _(u'Enter a valid South African ID number'), + 'invalid': _('Enter a valid South African ID number'), } def clean(self, value): super(ZAIDField, self).clean(value) if value in EMPTY_VALUES: - return u'' + return '' # strip spaces and dashes value = value.strip().replace(' ', '').replace('-', '') @@ -52,7 +53,7 @@ class ZAIDField(CharField): class ZAPostCodeField(RegexField): default_error_messages = { - 'invalid': _(u'Enter a valid South African postal code'), + 'invalid': _('Enter a valid South African postal code'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): diff --git a/django/contrib/messages/storage/base.py b/django/contrib/messages/storage/base.py index 65e8526b5c5..e80818e84e7 100644 --- a/django/contrib/messages/storage/base.py +++ b/django/contrib/messages/storage/base.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.conf import settings from django.utils.encoding import force_unicode, StrAndUnicode from django.contrib.messages import constants, utils @@ -41,7 +43,7 @@ class Message(StrAndUnicode): strings_only=True) extra_tags = force_unicode(self.extra_tags, strings_only=True) if extra_tags and label_tag: - return u' '.join([extra_tags, label_tag]) + return ' '.join([extra_tags, label_tag]) elif extra_tags: return extra_tags elif label_tag: diff --git a/django/contrib/sitemaps/tests/flatpages.py b/django/contrib/sitemaps/tests/flatpages.py index a40876e8596..930f24f22ce 100644 --- a/django/contrib/sitemaps/tests/flatpages.py +++ b/django/contrib/sitemaps/tests/flatpages.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.conf import settings from django.utils.unittest import skipUnless @@ -17,15 +19,15 @@ class FlatpagesSitemapTests(SitemapTestsBase): from django.contrib.flatpages.models import FlatPage public = FlatPage.objects.create( - url=u'/public/', - title=u'Public Page', + url='/public/', + title='Public Page', enable_comments=True, registration_required=False, ) public.sites.add(settings.SITE_ID) private = FlatPage.objects.create( - url=u'/private/', - title=u'Private Page', + url='/private/', + title='Private Page', enable_comments=True, registration_required=True ) diff --git a/django/contrib/sitemaps/tests/http.py b/django/contrib/sitemaps/tests/http.py index 5786aa48d57..d71907e09a4 100644 --- a/django/contrib/sitemaps/tests/http.py +++ b/django/contrib/sitemaps/tests/http.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import os from datetime import date @@ -74,7 +76,7 @@ class HTTPSitemapTests(SitemapTestsBase): def test_localized_priority(self): "The priority value should not be localized (Refs #14164)" activate('fr') - self.assertEqual(u'0,3', localize(0.3)) + self.assertEqual('0,3', localize(0.3)) # Retrieve the sitemap. Check that priorities # haven't been rendered in localized format diff --git a/django/contrib/sites/tests.py b/django/contrib/sites/tests.py index 828badb3867..1bb2495e6b8 100644 --- a/django/contrib/sites/tests.py +++ b/django/contrib/sites/tests.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.conf import settings from django.contrib.sites.models import Site, RequestSite, get_current_site from django.core.exceptions import ObjectDoesNotExist @@ -32,12 +34,12 @@ class SitesFrameworkTests(TestCase): # After updating a Site object (e.g. via the admin), we shouldn't return a # bogus value from the SITE_CACHE. site = Site.objects.get_current() - self.assertEqual(u"example.com", site.name) + self.assertEqual("example.com", site.name) s2 = Site.objects.get(id=settings.SITE_ID) s2.name = "Example site" s2.save() site = Site.objects.get_current() - self.assertEqual(u"Example site", site.name) + self.assertEqual("Example site", site.name) def test_get_current_site(self): # Test that the correct Site object is returned @@ -59,4 +61,4 @@ class SitesFrameworkTests(TestCase): Site._meta.installed = False site = get_current_site(request) self.assertTrue(isinstance(site, RequestSite)) - self.assertEqual(site.name, u"example.com") + self.assertEqual(site.name, "example.com") diff --git a/django/contrib/staticfiles/management/commands/collectstatic.py b/django/contrib/staticfiles/management/commands/collectstatic.py index 669c04043bb..d3977213a9b 100644 --- a/django/contrib/staticfiles/management/commands/collectstatic.py +++ b/django/contrib/staticfiles/management/commands/collectstatic.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import os import sys from optparse import make_option @@ -117,11 +119,11 @@ class Command(NoArgsCommand): dry_run=self.dry_run) for original_path, processed_path, processed in processor: if processed: - self.log(u"Post-processed '%s' as '%s" % + self.log("Post-processed '%s' as '%s" % (original_path, processed_path), level=1) self.post_processed_files.append(original_path) else: - self.log(u"Skipped post-processing '%s'" % original_path) + self.log("Skipped post-processing '%s'" % original_path) return { 'modified': self.copied_files + self.symlinked_files, @@ -146,7 +148,7 @@ class Command(NoArgsCommand): clear_display = 'This will overwrite existing files!' if self.interactive: - confirm = raw_input(u""" + confirm = raw_input(""" You have requested to collect static files at the destination location as specified in your settings%s @@ -195,10 +197,10 @@ Type 'yes' to continue, or 'no' to cancel: """ for f in files: fpath = os.path.join(path, f) if self.dry_run: - self.log(u"Pretending to delete '%s'" % + self.log("Pretending to delete '%s'" % smart_unicode(fpath), level=1) else: - self.log(u"Deleting '%s'" % smart_unicode(fpath), level=1) + self.log("Deleting '%s'" % smart_unicode(fpath), level=1) self.storage.delete(fpath) for d in dirs: self.clear_dir(os.path.join(path, d)) @@ -235,13 +237,13 @@ Type 'yes' to continue, or 'no' to cancel: """ and os.path.islink(full_path))): if prefixed_path not in self.unmodified_files: self.unmodified_files.append(prefixed_path) - self.log(u"Skipping '%s' (not modified)" % path) + self.log("Skipping '%s' (not modified)" % path) return False # Then delete the existing file if really needed if self.dry_run: - self.log(u"Pretending to delete '%s'" % path) + self.log("Pretending to delete '%s'" % path) else: - self.log(u"Deleting '%s'" % path) + self.log("Deleting '%s'" % path) self.storage.delete(prefixed_path) return True @@ -251,7 +253,7 @@ Type 'yes' to continue, or 'no' to cancel: """ """ # Skip this file if it was already copied earlier if prefixed_path in self.symlinked_files: - return self.log(u"Skipping '%s' (already linked earlier)" % path) + return self.log("Skipping '%s' (already linked earlier)" % path) # Delete the target file if needed or break if not self.delete_file(path, prefixed_path, source_storage): return @@ -259,9 +261,9 @@ Type 'yes' to continue, or 'no' to cancel: """ source_path = source_storage.path(path) # Finally link the file if self.dry_run: - self.log(u"Pretending to link '%s'" % source_path, level=1) + self.log("Pretending to link '%s'" % source_path, level=1) else: - self.log(u"Linking '%s'" % source_path, level=1) + self.log("Linking '%s'" % source_path, level=1) full_path = self.storage.path(prefixed_path) try: os.makedirs(os.path.dirname(full_path)) @@ -277,7 +279,7 @@ Type 'yes' to continue, or 'no' to cancel: """ """ # Skip this file if it was already copied earlier if prefixed_path in self.copied_files: - return self.log(u"Skipping '%s' (already copied earlier)" % path) + return self.log("Skipping '%s' (already copied earlier)" % path) # Delete the target file if needed or break if not self.delete_file(path, prefixed_path, source_storage): return @@ -285,9 +287,9 @@ Type 'yes' to continue, or 'no' to cancel: """ source_path = source_storage.path(path) # Finally start copying if self.dry_run: - self.log(u"Pretending to copy '%s'" % source_path, level=1) + self.log("Pretending to copy '%s'" % source_path, level=1) else: - self.log(u"Copying '%s'" % source_path, level=1) + self.log("Copying '%s'" % source_path, level=1) if self.local: full_path = self.storage.path(prefixed_path) try: diff --git a/django/contrib/staticfiles/management/commands/findstatic.py b/django/contrib/staticfiles/management/commands/findstatic.py index dc4406e4584..772220b3427 100644 --- a/django/contrib/staticfiles/management/commands/findstatic.py +++ b/django/contrib/staticfiles/management/commands/findstatic.py @@ -1,7 +1,9 @@ +from __future__ import unicode_literals + import os from optparse import make_option from django.core.management.base import LabelCommand -from django.utils.encoding import smart_str, smart_unicode +from django.utils.encoding import smart_unicode from django.contrib.staticfiles import finders @@ -21,9 +23,9 @@ class Command(LabelCommand): if result: if not isinstance(result, (list, tuple)): result = [result] - output = u'\n '.join( + output = '\n '.join( (smart_unicode(os.path.realpath(path)) for path in result)) - self.stdout.write(u"Found '%s' here:\n %s" % (path, output)) + self.stdout.write("Found '%s' here:\n %s" % (path, output)) else: if verbosity >= 1: self.stderr.write("No matching file found for '%s'." % path) diff --git a/django/contrib/staticfiles/storage.py b/django/contrib/staticfiles/storage.py index fd8f9efb027..e02fec8ec05 100644 --- a/django/contrib/staticfiles/storage.py +++ b/django/contrib/staticfiles/storage.py @@ -1,3 +1,4 @@ +from __future__ import unicode_literals import hashlib import os import posixpath @@ -46,8 +47,8 @@ class StaticFilesStorage(FileSystemStorage): class CachedFilesMixin(object): patterns = ( ("*.css", ( - r"""(url\(['"]{0,1}\s*(.*?)["']{0,1}\))""", - r"""(@import\s*["']\s*(.*?)["'])""", + br"""(url\(['"]{0,1}\s*(.*?)["']{0,1}\))""", + br"""(@import\s*["']\s*(.*?)["'])""", )), ) @@ -91,8 +92,8 @@ class CachedFilesMixin(object): root, ext = os.path.splitext(filename) file_hash = self.file_hash(clean_name, content) if file_hash is not None: - file_hash = u".%s" % file_hash - hashed_name = os.path.join(path, u"%s%s%s" % + file_hash = ".%s" % file_hash + hashed_name = os.path.join(path, "%s%s%s" % (root, file_hash, ext)) unparsed_name = list(parsed_name) unparsed_name[2] = hashed_name @@ -103,7 +104,7 @@ class CachedFilesMixin(object): return urlunsplit(unparsed_name) def cache_key(self, name): - return u'staticfiles:%s' % hashlib.md5(smart_str(name)).hexdigest() + return 'staticfiles:%s' % hashlib.md5(smart_str(name)).hexdigest() def url(self, name, force=False): """ diff --git a/django/contrib/syndication/views.py b/django/contrib/syndication/views.py index 462b3e94cf0..af767e1867a 100644 --- a/django/contrib/syndication/views.py +++ b/django/contrib/syndication/views.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.conf import settings from django.contrib.sites.models import get_current_site from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist @@ -18,7 +20,7 @@ def add_domain(domain, url, secure=False): or url.startswith('mailto:')): # 'url' must already be ASCII and URL-quoted, so no need for encoding # conversions here. - url = iri_to_uri(u'%s://%s%s' % (protocol, domain, url)) + url = iri_to_uri('%s://%s%s' % (protocol, domain, url)) return url class FeedDoesNotExist(ObjectDoesNotExist): diff --git a/django/contrib/webdesign/lorem_ipsum.py b/django/contrib/webdesign/lorem_ipsum.py index 4ad175d033e..01d8f220f5c 100644 --- a/django/contrib/webdesign/lorem_ipsum.py +++ b/django/contrib/webdesign/lorem_ipsum.py @@ -2,6 +2,8 @@ Utility functions for generating "lorem ipsum" Latin text. """ +from __future__ import unicode_literals + import random COMMON_P = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' @@ -49,10 +51,10 @@ def sentence(): """ # Determine the number of comma-separated sections and number of words in # each section for this sentence. - sections = [u' '.join(random.sample(WORDS, random.randint(3, 12))) for i in range(random.randint(1, 5))] - s = u', '.join(sections) + sections = [' '.join(random.sample(WORDS, random.randint(3, 12))) for i in range(random.randint(1, 5))] + s = ', '.join(sections) # Convert to sentence case and add end punctuation. - return u'%s%s%s' % (s[0].upper(), s[1:], random.choice('?.')) + return '%s%s%s' % (s[0].upper(), s[1:], random.choice('?.')) def paragraph(): """ @@ -60,7 +62,7 @@ def paragraph(): The paragraph consists of between 1 and 4 sentences, inclusive. """ - return u' '.join([sentence() for i in range(random.randint(1, 4))]) + return ' '.join([sentence() for i in range(random.randint(1, 4))]) def paragraphs(count, common=True): """ @@ -98,4 +100,4 @@ def words(count, common=True): word_list += random.sample(WORDS, c) else: word_list = word_list[:count] - return u' '.join(word_list) + return ' '.join(word_list) diff --git a/django/contrib/webdesign/templatetags/webdesign.py b/django/contrib/webdesign/templatetags/webdesign.py index 05d8dc7f54f..b870299cdae 100644 --- a/django/contrib/webdesign/templatetags/webdesign.py +++ b/django/contrib/webdesign/templatetags/webdesign.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.contrib.webdesign.lorem_ipsum import words, paragraphs from django import template @@ -18,7 +20,7 @@ class LoremNode(template.Node): paras = paragraphs(count, common=self.common) if self.method == 'p': paras = ['

    %s

    ' % p for p in paras] - return u'\n\n'.join(paras) + return '\n\n'.join(paras) @register.tag def lorem(parser, token): diff --git a/django/contrib/webdesign/tests.py b/django/contrib/webdesign/tests.py index 8907ea3ba7b..16ec501e447 100644 --- a/django/contrib/webdesign/tests.py +++ b/django/contrib/webdesign/tests.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +from __future__ import unicode_literals import unittest @@ -9,7 +10,7 @@ from django.template import loader, Context class WebdesignTest(unittest.TestCase): def test_words(self): - self.assertEqual(words(7), u'lorem ipsum dolor sit amet consectetur adipisicing') + self.assertEqual(words(7), 'lorem ipsum dolor sit amet consectetur adipisicing') def test_paragraphs(self): self.assertEqual(paragraphs(1), @@ -18,4 +19,4 @@ class WebdesignTest(unittest.TestCase): def test_lorem_tag(self): t = loader.get_template_from_string("{% load webdesign %}{% lorem 3 w %}") self.assertEqual(t.render(Context({})), - u'lorem ipsum dolor') + 'lorem ipsum dolor') diff --git a/django/core/context_processors.py b/django/core/context_processors.py index 3ba519188bf..325f64d224e 100644 --- a/django/core/context_processors.py +++ b/django/core/context_processors.py @@ -9,6 +9,7 @@ RequestContext. from django.conf import settings from django.middleware.csrf import get_token +from django.utils.encoding import smart_str from django.utils.functional import lazy def csrf(request): @@ -24,7 +25,7 @@ def csrf(request): # instead of returning an empty dict. return b'NOTPROVIDED' else: - return token + return smart_str(token) _get_val = lazy(_get_val, str) return {'csrf_token': _get_val() } diff --git a/django/core/files/base.py b/django/core/files/base.py index a2d703c963f..04853fad0c3 100644 --- a/django/core/files/base.py +++ b/django/core/files/base.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import os from io import BytesIO @@ -19,7 +21,7 @@ class File(FileProxyMixin): return smart_str(self.name or '') def __unicode__(self): - return smart_unicode(self.name or u'') + return smart_unicode(self.name or '') def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self or "None") diff --git a/django/core/files/uploadhandler.py b/django/core/files/uploadhandler.py index 88f78904bb4..68d540e595e 100644 --- a/django/core/files/uploadhandler.py +++ b/django/core/files/uploadhandler.py @@ -2,6 +2,8 @@ Base file upload handler classes, and the built-in concrete subclasses """ +from __future__ import unicode_literals + from io import BytesIO from django.conf import settings @@ -33,9 +35,9 @@ class StopUpload(UploadFileException): def __unicode__(self): if self.connection_reset: - return u'StopUpload: Halt current upload.' + return 'StopUpload: Halt current upload.' else: - return u'StopUpload: Consume request data, then halt.' + return 'StopUpload: Consume request data, then halt.' class SkipFile(UploadFileException): """ diff --git a/django/core/handlers/base.py b/django/core/handlers/base.py index 4c9dfc07bc5..4c07524ecc8 100644 --- a/django/core/handlers/base.py +++ b/django/core/handlers/base.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import sys from django import http @@ -254,9 +256,9 @@ def get_script_name(environ): # rewrites. Unfortunately not every Web server (lighttpd!) passes this # information through all the time, so FORCE_SCRIPT_NAME, above, is still # needed. - script_url = environ.get('SCRIPT_URL', u'') + script_url = environ.get('SCRIPT_URL', '') if not script_url: - script_url = environ.get('REDIRECT_URL', u'') + script_url = environ.get('REDIRECT_URL', '') if script_url: return force_unicode(script_url[:-len(environ.get('PATH_INFO', ''))]) - return force_unicode(environ.get('SCRIPT_NAME', u'')) + return force_unicode(environ.get('SCRIPT_NAME', '')) diff --git a/django/core/handlers/wsgi.py b/django/core/handlers/wsgi.py index 128ff7ac64f..5215101a355 100644 --- a/django/core/handlers/wsgi.py +++ b/django/core/handlers/wsgi.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import sys from io import BytesIO from threading import Lock @@ -7,7 +9,7 @@ from django.core import signals from django.core.handlers import base from django.core.urlresolvers import set_script_prefix from django.utils import datastructures -from django.utils.encoding import force_unicode, iri_to_uri +from django.utils.encoding import force_unicode, smart_str, iri_to_uri from django.utils.log import getLogger logger = getLogger('django.request') @@ -125,7 +127,7 @@ class LimitedStream(object): class WSGIRequest(http.HttpRequest): def __init__(self, environ): script_name = base.get_script_name(environ) - path_info = force_unicode(environ.get('PATH_INFO', u'/')) + path_info = force_unicode(environ.get('PATH_INFO', '/')) if not path_info or path_info == script_name: # Sometimes PATH_INFO exists, but is empty (e.g. accessing # the SCRIPT_NAME URL without a trailing slash). We really need to @@ -134,7 +136,7 @@ class WSGIRequest(http.HttpRequest): # # (The comparison of path_info to script_name is to work around an # apparent bug in flup 1.0.1. See Django ticket #8490). - path_info = u'/' + path_info = '/' self.environ = environ self.path_info = path_info self.path = '%s%s' % (script_name, path_info) @@ -246,6 +248,6 @@ class WSGIHandler(base.BaseHandler): status = '%s %s' % (response.status_code, status_text) response_headers = [(str(k), str(v)) for k, v in response.items()] for c in response.cookies.values(): - response_headers.append(('Set-Cookie', str(c.output(header='')))) - start_response(status, response_headers) + response_headers.append((b'Set-Cookie', str(c.output(header='')))) + start_response(smart_str(status), response_headers) return response diff --git a/django/core/mail/__init__.py b/django/core/mail/__init__.py index 1bee0cac9fd..08f9702934d 100644 --- a/django/core/mail/__init__.py +++ b/django/core/mail/__init__.py @@ -1,6 +1,7 @@ """ Tools for sending email. """ +from __future__ import unicode_literals from django.conf import settings from django.core.exceptions import ImproperlyConfigured @@ -89,7 +90,7 @@ def mail_admins(subject, message, fail_silently=False, connection=None, """Sends a message to the admins, as defined by the ADMINS setting.""" if not settings.ADMINS: return - mail = EmailMultiAlternatives(u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), + mail = EmailMultiAlternatives('%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), message, settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS], connection=connection) if html_message: @@ -102,7 +103,7 @@ def mail_managers(subject, message, fail_silently=False, connection=None, """Sends a message to the managers, as defined by the MANAGERS setting.""" if not settings.MANAGERS: return - mail = EmailMultiAlternatives(u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), + mail = EmailMultiAlternatives('%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), message, settings.SERVER_EMAIL, [a[1] for a in settings.MANAGERS], connection=connection) if html_message: diff --git a/django/core/mail/message.py b/django/core/mail/message.py index 2618c7f17da..82f6b6900fc 100644 --- a/django/core/mail/message.py +++ b/django/core/mail/message.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import mimetypes import os import random @@ -90,7 +92,7 @@ def forbid_multi_line_headers(name, val, encoding): else: if name.lower() == 'subject': val = Header(val) - return name, val + return smart_str(name), val def sanitize_address(addr, encoding): @@ -101,8 +103,8 @@ def sanitize_address(addr, encoding): try: addr = addr.encode('ascii') except UnicodeEncodeError: # IDN - if u'@' in addr: - localpart, domain = addr.split(u'@', 1) + if '@' in addr: + localpart, domain = addr.split('@', 1) localpart = str(Header(localpart, encoding)) domain = domain.encode('idna') addr = '@'.join([localpart, domain]) diff --git a/django/core/management/commands/createcachetable.py b/django/core/management/commands/createcachetable.py index bcc47e17c80..fd6dbbbd2c5 100644 --- a/django/core/management/commands/createcachetable.py +++ b/django/core/management/commands/createcachetable.py @@ -4,6 +4,8 @@ from django.core.cache.backends.db import BaseDatabaseCache from django.core.management.base import LabelCommand, CommandError from django.db import connections, router, transaction, models, DEFAULT_DB_ALIAS from django.db.utils import DatabaseError +from django.utils.encoding import force_unicode + class Command(LabelCommand): help = "Creates the table needed to use the SQL cache backend." @@ -58,7 +60,7 @@ class Command(LabelCommand): transaction.rollback_unless_managed(using=db) raise CommandError( "Cache table '%s' could not be created.\nThe error was: %s." % - (tablename, e)) + (tablename, force_unicode(e))) for statement in index_output: curs.execute(statement) transaction.commit_unless_managed(using=db) diff --git a/django/core/management/commands/loaddata.py b/django/core/management/commands/loaddata.py index 078fd6fa27a..34f8041d338 100644 --- a/django/core/management/commands/loaddata.py +++ b/django/core/management/commands/loaddata.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import sys import os import gzip @@ -12,6 +14,7 @@ from django.core.management.color import no_style from django.db import (connections, router, transaction, DEFAULT_DB_ALIAS, IntegrityError, DatabaseError) from django.db.models import get_apps +from django.utils.encoding import force_unicode from itertools import product try: @@ -186,7 +189,7 @@ class Command(BaseCommand): 'app_label': obj.object._meta.app_label, 'object_name': obj.object._meta.object_name, 'pk': obj.object.pk, - 'error_msg': e + 'error_msg': force_unicode(e) },) raise diff --git a/django/core/management/commands/sql.py b/django/core/management/commands/sql.py index 59b2e77b692..52b2058650d 100644 --- a/django/core/management/commands/sql.py +++ b/django/core/management/commands/sql.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from optparse import make_option from django.core.management.base import AppCommand @@ -16,4 +18,4 @@ class Command(AppCommand): output_transaction = True def handle_app(self, app, **options): - return u'\n'.join(sql_create(app, self.style, connections[options.get('database')])).encode('utf-8') + return '\n'.join(sql_create(app, self.style, connections[options.get('database')])) diff --git a/django/core/management/commands/sqlall.py b/django/core/management/commands/sqlall.py index ab702bfffb0..6d0735a6f9e 100644 --- a/django/core/management/commands/sqlall.py +++ b/django/core/management/commands/sqlall.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from optparse import make_option from django.core.management.base import AppCommand @@ -16,4 +18,4 @@ class Command(AppCommand): output_transaction = True def handle_app(self, app, **options): - return u'\n'.join(sql_all(app, self.style, connections[options.get('database')])).encode('utf-8') + return '\n'.join(sql_all(app, self.style, connections[options.get('database')])) diff --git a/django/core/management/commands/sqlclear.py b/django/core/management/commands/sqlclear.py index b8f491392b7..ec2602d2a38 100644 --- a/django/core/management/commands/sqlclear.py +++ b/django/core/management/commands/sqlclear.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from optparse import make_option from django.core.management.base import AppCommand @@ -16,4 +18,4 @@ class Command(AppCommand): output_transaction = True def handle_app(self, app, **options): - return u'\n'.join(sql_delete(app, self.style, connections[options.get('database')])).encode('utf-8') + return '\n'.join(sql_delete(app, self.style, connections[options.get('database')])) diff --git a/django/core/management/commands/sqlcustom.py b/django/core/management/commands/sqlcustom.py index 6a984560de7..0d46c4ec705 100644 --- a/django/core/management/commands/sqlcustom.py +++ b/django/core/management/commands/sqlcustom.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from optparse import make_option from django.core.management.base import AppCommand @@ -16,4 +18,4 @@ class Command(AppCommand): output_transaction = True def handle_app(self, app, **options): - return u'\n'.join(sql_custom(app, self.style, connections[options.get('database')])).encode('utf-8') + return '\n'.join(sql_custom(app, self.style, connections[options.get('database')])) diff --git a/django/core/management/commands/sqlflush.py b/django/core/management/commands/sqlflush.py index 19054fbfa96..b98ecfd8ff3 100644 --- a/django/core/management/commands/sqlflush.py +++ b/django/core/management/commands/sqlflush.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from optparse import make_option from django.core.management.base import NoArgsCommand @@ -16,4 +18,4 @@ class Command(NoArgsCommand): output_transaction = True def handle_noargs(self, **options): - return u'\n'.join(sql_flush(self.style, connections[options.get('database')], only_django=True)).encode('utf-8') + return '\n'.join(sql_flush(self.style, connections[options.get('database')], only_django=True)) diff --git a/django/core/management/commands/sqlindexes.py b/django/core/management/commands/sqlindexes.py index bf55b0dffcc..f95d4f158c8 100644 --- a/django/core/management/commands/sqlindexes.py +++ b/django/core/management/commands/sqlindexes.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from optparse import make_option from django.core.management.base import AppCommand @@ -17,4 +19,4 @@ class Command(AppCommand): output_transaction = True def handle_app(self, app, **options): - return u'\n'.join(sql_indexes(app, self.style, connections[options.get('database')])).encode('utf-8') + return '\n'.join(sql_indexes(app, self.style, connections[options.get('database')])) diff --git a/django/core/management/commands/sqlsequencereset.py b/django/core/management/commands/sqlsequencereset.py index 6460f000626..7b9e85a9ee0 100644 --- a/django/core/management/commands/sqlsequencereset.py +++ b/django/core/management/commands/sqlsequencereset.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from optparse import make_option from django.core.management.base import AppCommand @@ -17,4 +19,4 @@ class Command(AppCommand): def handle_app(self, app, **options): connection = connections[options.get('database')] - return u'\n'.join(connection.ops.sequence_reset_sql(self.style, models.get_models(app, include_auto_created=True))).encode('utf-8') + return '\n'.join(connection.ops.sequence_reset_sql(self.style, models.get_models(app, include_auto_created=True))) diff --git a/django/core/management/sql.py b/django/core/management/sql.py index 53d97362934..993d75aa6bb 100644 --- a/django/core/management/sql.py +++ b/django/core/management/sql.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import os import re @@ -160,9 +162,9 @@ def custom_sql_for_model(model, style, connection): with open(sql_file, 'U') as fp: for statement in statements.split(fp.read().decode(settings.FILE_CHARSET)): # Remove any comments from the file - statement = re.sub(ur"--.*([\n\Z]|$)", "", statement) + statement = re.sub(r"--.*([\n\Z]|$)", "", statement) if statement.strip(): - output.append(statement + u";") + output.append(statement + ";") return output diff --git a/django/core/management/validation.py b/django/core/management/validation.py index 272ac5be419..7cd6958abf2 100644 --- a/django/core/management/validation.py +++ b/django/core/management/validation.py @@ -1,6 +1,7 @@ import sys from django.core.management.color import color_style +from django.utils.encoding import smart_str from django.utils.itercompat import is_iterable class ModelErrorCollection: @@ -11,7 +12,7 @@ class ModelErrorCollection: def add(self, context, error): self.errors.append((context, error)) - self.outfile.write(self.style.ERROR("%s: %s\n" % (context, error))) + self.outfile.write(self.style.ERROR(smart_str("%s: %s\n" % (context, error)))) def get_validation_errors(outfile, app=None): """ diff --git a/django/core/serializers/json.py b/django/core/serializers/json.py index fce00600f4a..1b9a61750df 100644 --- a/django/core/serializers/json.py +++ b/django/core/serializers/json.py @@ -13,6 +13,7 @@ from io import BytesIO from django.core.serializers.base import DeserializationError from django.core.serializers.python import Serializer as PythonSerializer from django.core.serializers.python import Deserializer as PythonDeserializer +from django.utils.encoding import smart_str from django.utils.timezone import is_aware class Serializer(PythonSerializer): @@ -61,8 +62,10 @@ def Deserializer(stream_or_string, **options): """ Deserialize a stream or string of JSON data. """ - if isinstance(stream_or_string, basestring): + if isinstance(stream_or_string, bytes): stream = BytesIO(stream_or_string) + elif isinstance(stream_or_string, unicode): + stream = BytesIO(smart_str(stream_or_string)) else: stream = stream_or_string try: diff --git a/django/core/serializers/python.py b/django/core/serializers/python.py index 49120434ebe..333161c9295 100644 --- a/django/core/serializers/python.py +++ b/django/core/serializers/python.py @@ -3,6 +3,7 @@ A Python "serializer". Doesn't do much serializing per se -- just converts to and from basic Python data types (lists, dicts, strings, etc.). Useful as a basis for other serializers. """ +from __future__ import unicode_literals from django.conf import settings from django.core.serializers import base @@ -138,5 +139,5 @@ def _get_model(model_identifier): except TypeError: Model = None if Model is None: - raise base.DeserializationError(u"Invalid model identifier: '%s'" % model_identifier) + raise base.DeserializationError("Invalid model identifier: '%s'" % model_identifier) return Model diff --git a/django/core/serializers/xml_serializer.py b/django/core/serializers/xml_serializer.py index a5edeac5af0..9d9c023b647 100644 --- a/django/core/serializers/xml_serializer.py +++ b/django/core/serializers/xml_serializer.py @@ -2,6 +2,8 @@ XML serializer. """ +from __future__ import unicode_literals + from django.conf import settings from django.core.serializers import base from django.db import models, DEFAULT_DB_ALIAS @@ -289,4 +291,4 @@ def getInnerText(node): inner_text.extend(getInnerText(child)) else: pass - return u"".join(inner_text) + return "".join(inner_text) diff --git a/django/core/urlresolvers.py b/django/core/urlresolvers.py index 78ce00511ce..625ec6348b8 100644 --- a/django/core/urlresolvers.py +++ b/django/core/urlresolvers.py @@ -6,6 +6,7 @@ a string) and returns a tuple in this format: (view_function, function_args, function_kwargs) """ +from __future__ import unicode_literals import re from threading import local @@ -182,7 +183,7 @@ class RegexURLPattern(LocaleRegexProvider): self.name = name def __repr__(self): - return smart_str(u'<%s %s %s>' % (self.__class__.__name__, self.name, self.regex.pattern)) + return smart_str('<%s %s %s>' % (self.__class__.__name__, self.name, self.regex.pattern)) def add_prefix(self, prefix): """ @@ -232,7 +233,7 @@ class RegexURLResolver(LocaleRegexProvider): self._app_dict = {} def __repr__(self): - return smart_str(u'<%s %s (%s:%s) %s>' % (self.__class__.__name__, self.urlconf_name, self.app_name, self.namespace, self.regex.pattern)) + return smart_str('<%s %s (%s:%s) %s>' % (self.__class__.__name__, self.urlconf_name, self.app_name, self.namespace, self.regex.pattern)) def _populate(self): lookups = MultiValueDict() @@ -379,7 +380,7 @@ class RegexURLResolver(LocaleRegexProvider): continue unicode_kwargs = dict([(k, force_unicode(v)) for (k, v) in kwargs.items()]) candidate = (prefix_norm + result) % unicode_kwargs - if re.search(u'^%s%s' % (_prefix, pattern), candidate, re.UNICODE): + if re.search('^%s%s' % (_prefix, pattern), candidate, re.UNICODE): return candidate # lookup_view can be URL label, or dotted path, or callable, Any of # these can be passed in at the top, but callables are not friendly in @@ -497,7 +498,7 @@ def get_script_prefix(): wishes to construct their own URLs manually (although accessing the request instance is normally going to be a lot cleaner). """ - return getattr(_prefixes, "value", u'/') + return getattr(_prefixes, "value", '/') def set_urlconf(urlconf_name): """ diff --git a/django/core/validators.py b/django/core/validators.py index 3d4bcc86c8f..c7c89786da4 100644 --- a/django/core/validators.py +++ b/django/core/validators.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import re import urlparse @@ -11,7 +13,7 @@ EMPTY_VALUES = (None, '', [], (), {}) class RegexValidator(object): regex = '' - message = _(u'Enter a valid value.') + message = _('Enter a valid value.') code = 'invalid' def __init__(self, regex=None, message=None, code=None): @@ -75,13 +77,13 @@ class EmailValidator(RegexValidator): super(EmailValidator, self).__call__(value) except ValidationError as e: # Trivial case failed. Try for possible IDN domain-part - if value and u'@' in value: - parts = value.split(u'@') + if value and '@' in value: + parts = value.split('@') try: parts[-1] = parts[-1].encode('idna') except UnicodeError: raise e - super(EmailValidator, self).__call__(u'@'.join(parts)) + super(EmailValidator, self).__call__('@'.join(parts)) else: raise @@ -91,17 +93,17 @@ email_re = re.compile( r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"' r')@((?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$)' # domain r'|\[(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\]$', re.IGNORECASE) # literal form, ipv4 address (SMTP 4.1.3) -validate_email = EmailValidator(email_re, _(u'Enter a valid e-mail address.'), 'invalid') +validate_email = EmailValidator(email_re, _('Enter a valid e-mail address.'), 'invalid') slug_re = re.compile(r'^[-\w]+$') -validate_slug = RegexValidator(slug_re, _(u"Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."), 'invalid') +validate_slug = RegexValidator(slug_re, _("Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."), 'invalid') ipv4_re = re.compile(r'^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$') -validate_ipv4_address = RegexValidator(ipv4_re, _(u'Enter a valid IPv4 address.'), 'invalid') +validate_ipv4_address = RegexValidator(ipv4_re, _('Enter a valid IPv4 address.'), 'invalid') def validate_ipv6_address(value): if not is_valid_ipv6_address(value): - raise ValidationError(_(u'Enter a valid IPv6 address.'), code='invalid') + raise ValidationError(_('Enter a valid IPv6 address.'), code='invalid') def validate_ipv46_address(value): try: @@ -110,7 +112,7 @@ def validate_ipv46_address(value): try: validate_ipv6_address(value) except ValidationError: - raise ValidationError(_(u'Enter a valid IPv4 or IPv6 address.'), code='invalid') + raise ValidationError(_('Enter a valid IPv4 or IPv6 address.'), code='invalid') ip_address_validator_map = { 'both': ([validate_ipv46_address], _('Enter a valid IPv4 or IPv6 address.')), @@ -135,13 +137,13 @@ def ip_address_validators(protocol, unpack_ipv4): % (protocol, ip_address_validator_map.keys())) comma_separated_int_list_re = re.compile('^[\d,]+$') -validate_comma_separated_integer_list = RegexValidator(comma_separated_int_list_re, _(u'Enter only digits separated by commas.'), 'invalid') +validate_comma_separated_integer_list = RegexValidator(comma_separated_int_list_re, _('Enter only digits separated by commas.'), 'invalid') class BaseValidator(object): compare = lambda self, a, b: a is not b clean = lambda self, x: x - message = _(u'Ensure this value is %(limit_value)s (it is %(show_value)s).') + message = _('Ensure this value is %(limit_value)s (it is %(show_value)s).') code = 'limit_value' def __init__(self, limit_value): @@ -159,23 +161,23 @@ class BaseValidator(object): class MaxValueValidator(BaseValidator): compare = lambda self, a, b: a > b - message = _(u'Ensure this value is less than or equal to %(limit_value)s.') + message = _('Ensure this value is less than or equal to %(limit_value)s.') code = 'max_value' class MinValueValidator(BaseValidator): compare = lambda self, a, b: a < b - message = _(u'Ensure this value is greater than or equal to %(limit_value)s.') + message = _('Ensure this value is greater than or equal to %(limit_value)s.') code = 'min_value' class MinLengthValidator(BaseValidator): compare = lambda self, a, b: a < b clean = lambda self, x: len(x) - message = _(u'Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).') + message = _('Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).') code = 'min_length' class MaxLengthValidator(BaseValidator): compare = lambda self, a, b: a > b clean = lambda self, x: len(x) - message = _(u'Ensure this value has at most %(limit_value)d characters (it has %(show_value)d).') + message = _('Ensure this value has at most %(limit_value)d characters (it has %(show_value)d).') code = 'max_length' diff --git a/django/db/backends/mysql/base.py b/django/db/backends/mysql/base.py index 1df487bd928..ff227b6e7e6 100644 --- a/django/db/backends/mysql/base.py +++ b/django/db/backends/mysql/base.py @@ -3,6 +3,7 @@ MySQL database backend for Django. Requires MySQLdb: http://sourceforge.net/projects/mysql-python """ +from __future__ import unicode_literals import datetime import re @@ -61,8 +62,8 @@ def adapt_datetime_with_timezone_support(value, conv): # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL. if settings.USE_TZ: if timezone.is_naive(value): - warnings.warn(u"SQLite received a naive datetime (%s)" - u" while time zone support is active." % value, + warnings.warn("SQLite received a naive datetime (%s)" + " while time zone support is active." % value, RuntimeWarning) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) diff --git a/django/db/backends/oracle/base.py b/django/db/backends/oracle/base.py index fe512dfee57..785e4b72a60 100644 --- a/django/db/backends/oracle/base.py +++ b/django/db/backends/oracle/base.py @@ -3,7 +3,7 @@ Oracle database backend for Django. Requires cx_Oracle: http://cx-oracle.sourceforge.net/ """ - +from __future__ import unicode_literals import datetime import decimal @@ -160,7 +160,7 @@ WHEN (new.%(col_name)s IS NULL) # string instead of null, but only if the field accepts the # empty string. if value is None and field and field.empty_strings_allowed: - value = u'' + value = '' # Convert 1 or 0 to True or False elif value in (1, 0) and field and field.get_internal_type() in ('BooleanField', 'NullBooleanField'): value = bool(value) @@ -235,7 +235,7 @@ WHEN (new.%(col_name)s IS NULL) def process_clob(self, value): if value is None: - return u'' + return '' return force_unicode(value.read()) def quote_name(self, name): @@ -567,8 +567,8 @@ class OracleParam(object): # without being converted by DateTimeField.get_db_prep_value. if settings.USE_TZ and isinstance(param, datetime.datetime): if timezone.is_naive(param): - warnings.warn(u"Oracle received a naive datetime (%s)" - u" while time zone support is active." % param, + warnings.warn("Oracle received a naive datetime (%s)" + " while time zone support is active." % param, RuntimeWarning) default_timezone = timezone.get_default_timezone() param = timezone.make_aware(param, default_timezone) diff --git a/django/db/backends/postgresql_psycopg2/introspection.py b/django/db/backends/postgresql_psycopg2/introspection.py index fbf7a22769a..99573b90191 100644 --- a/django/db/backends/postgresql_psycopg2/introspection.py +++ b/django/db/backends/postgresql_psycopg2/introspection.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.db.backends import BaseDatabaseIntrospection @@ -43,7 +45,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection): WHERE table_name = %s""", [table_name]) null_map = dict(cursor.fetchall()) cursor.execute("SELECT * FROM %s LIMIT 1" % self.connection.ops.quote_name(table_name)) - return [tuple([item for item in line[:6]] + [null_map[line[0]]==u'YES']) + return [tuple([item for item in line[:6]] + [null_map[line[0]]=='YES']) for line in cursor.description] def get_relations(self, cursor, table_name): diff --git a/django/db/backends/postgresql_psycopg2/operations.py b/django/db/backends/postgresql_psycopg2/operations.py index 395cd92047f..46b464b551f 100644 --- a/django/db/backends/postgresql_psycopg2/operations.py +++ b/django/db/backends/postgresql_psycopg2/operations.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.db.backends import BaseDatabaseOperations @@ -21,14 +23,14 @@ class DatabaseOperations(BaseDatabaseOperations): """ modifiers = [] if timedelta.days: - modifiers.append(u'%s days' % timedelta.days) + modifiers.append('%s days' % timedelta.days) if timedelta.seconds: - modifiers.append(u'%s seconds' % timedelta.seconds) + modifiers.append('%s seconds' % timedelta.seconds) if timedelta.microseconds: - modifiers.append(u'%s microseconds' % timedelta.microseconds) - mods = u' '.join(modifiers) - conn = u' %s ' % connector - return u'(%s)' % conn.join([sql, u'interval \'%s\'' % mods]) + modifiers.append('%s microseconds' % timedelta.microseconds) + mods = ' '.join(modifiers) + conn = ' %s ' % connector + return '(%s)' % conn.join([sql, 'interval \'%s\'' % mods]) def date_trunc_sql(self, lookup_type, field_name): # http://www.postgresql.org/docs/8.0/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC diff --git a/django/db/backends/sqlite3/base.py b/django/db/backends/sqlite3/base.py index 4fba304e237..75e1d9792c2 100644 --- a/django/db/backends/sqlite3/base.py +++ b/django/db/backends/sqlite3/base.py @@ -4,6 +4,7 @@ SQLite3 backend for django. Works with either the pysqlite2 module or the sqlite3 module in the standard library. """ +from __future__ import unicode_literals import datetime import decimal @@ -45,8 +46,8 @@ def adapt_datetime_with_timezone_support(value): # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL. if settings.USE_TZ: if timezone.is_naive(value): - warnings.warn(u"SQLite received a naive datetime (%s)" - u" while time zone support is active." % value, + warnings.warn("SQLite received a naive datetime (%s)" + " while time zone support is active." % value, RuntimeWarning) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) @@ -118,7 +119,7 @@ class DatabaseOperations(BaseDatabaseOperations): # values differently. So instead we register our own function that # formats the datetime combined with the delta in a manner suitable # for comparisons. - return u'django_format_dtdelta(%s, "%s", "%d", "%d", "%d")' % (sql, + return 'django_format_dtdelta(%s, "%s", "%d", "%d", "%d")' % (sql, connector, timedelta.days, timedelta.seconds, timedelta.microseconds) def date_trunc_sql(self, lookup_type, field_name): diff --git a/django/db/backends/util.py b/django/db/backends/util.py index 32e0f4f7023..775bb3e1823 100644 --- a/django/db/backends/util.py +++ b/django/db/backends/util.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import datetime import decimal import hashlib @@ -146,6 +148,6 @@ def format_number(value, max_digits, decimal_places): if isinstance(value, decimal.Decimal): context = decimal.getcontext().copy() context.prec = max_digits - return u'%s' % str(value.quantize(decimal.Decimal(".1") ** decimal_places, context=context)) + return '%s' % str(value.quantize(decimal.Decimal(".1") ** decimal_places, context=context)) else: - return u"%.*f" % (decimal_places, value) + return "%.*f" % (decimal_places, value) diff --git a/django/db/models/base.py b/django/db/models/base.py index 13238fc9dcf..f52a626d8bd 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import copy import sys from functools import update_wrapper @@ -373,7 +375,7 @@ class Model(object): u = unicode(self) except (UnicodeEncodeError, UnicodeDecodeError): u = '[Bad Unicode data]' - return smart_str(u'<%s: %s>' % (self.__class__.__name__, u)) + return smart_str('<%s: %s>' % (self.__class__.__name__, u)) def __str__(self): if hasattr(self, '__unicode__'): @@ -786,7 +788,7 @@ class Model(object): def date_error_message(self, lookup_type, field, unique_for): opts = self._meta - return _(u"%(field_name)s must be unique for %(date_field)s %(lookup)s.") % { + return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % { 'field_name': unicode(capfirst(opts.get_field(field).verbose_name)), 'date_field': unicode(capfirst(opts.get_field(unique_for).verbose_name)), 'lookup': lookup_type, @@ -810,7 +812,7 @@ class Model(object): else: field_labels = map(lambda f: capfirst(opts.get_field(f).verbose_name), unique_check) field_labels = get_text_list(field_labels, _('and')) - return _(u"%(model_name)s with this %(field_label)s already exists.") % { + return _("%(model_name)s with this %(field_label)s already exists.") % { 'model_name': unicode(model_name), 'field_label': unicode(field_labels) } diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py index d572cce28f8..9db76a617b2 100644 --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import collections import copy import datetime @@ -61,16 +63,16 @@ class Field(object): auto_creation_counter = -1 default_validators = [] # Default set of validators default_error_messages = { - 'invalid_choice': _(u'Value %r is not a valid choice.'), - 'null': _(u'This field cannot be null.'), - 'blank': _(u'This field cannot be blank.'), - 'unique': _(u'%(model_name)s with this %(field_label)s ' - u'already exists.'), + 'invalid_choice': _('Value %r is not a valid choice.'), + 'null': _('This field cannot be null.'), + 'blank': _('This field cannot be blank.'), + 'unique': _('%(model_name)s with this %(field_label)s ' + 'already exists.'), } # Generic field type description, usually overriden by subclasses def _description(self): - return _(u'Field of type: %(field_type)s') % { + return _('Field of type: %(field_type)s') % { 'field_type': self.__class__.__name__ } description = property(_description) @@ -512,7 +514,7 @@ class AutoField(Field): empty_strings_allowed = False default_error_messages = { - 'invalid': _(u"'%s' value must be an integer."), + 'invalid': _("'%s' value must be an integer."), } def __init__(self, *args, **kwargs): @@ -560,7 +562,7 @@ class AutoField(Field): class BooleanField(Field): empty_strings_allowed = False default_error_messages = { - 'invalid': _(u"'%s' value must be either True or False."), + 'invalid': _("'%s' value must be either True or False."), } description = _("Boolean (Either True or False)") @@ -646,7 +648,7 @@ class CommaSeparatedIntegerField(CharField): def formfield(self, **kwargs): defaults = { 'error_messages': { - 'invalid': _(u'Enter only digits separated by commas.'), + 'invalid': _('Enter only digits separated by commas.'), } } defaults.update(kwargs) @@ -655,10 +657,10 @@ class CommaSeparatedIntegerField(CharField): class DateField(Field): empty_strings_allowed = False default_error_messages = { - 'invalid': _(u"'%s' value has an invalid date format. It must be " - u"in YYYY-MM-DD format."), - 'invalid_date': _(u"'%s' value has the correct format (YYYY-MM-DD) " - u"but it is an invalid date."), + 'invalid': _("'%s' value has an invalid date format. It must be " + "in YYYY-MM-DD format."), + 'invalid_date': _("'%s' value has the correct format (YYYY-MM-DD) " + "but it is an invalid date."), } description = _("Date (without time)") @@ -743,13 +745,13 @@ class DateField(Field): class DateTimeField(DateField): empty_strings_allowed = False default_error_messages = { - 'invalid': _(u"'%s' value has an invalid format. It must be in " - u"YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."), - 'invalid_date': _(u"'%s' value has the correct format " - u"(YYYY-MM-DD) but it is an invalid date."), - 'invalid_datetime': _(u"'%s' value has the correct format " - u"(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) " - u"but it is an invalid date/time."), + 'invalid': _("'%s' value has an invalid format. It must be in " + "YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."), + 'invalid_date': _("'%s' value has the correct format " + "(YYYY-MM-DD) but it is an invalid date."), + 'invalid_datetime': _("'%s' value has the correct format " + "(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) " + "but it is an invalid date/time."), } description = _("Date (with time)") @@ -770,8 +772,8 @@ class DateTimeField(DateField): # local time. This won't work during DST change, but we can't # do much about it, so we let the exceptions percolate up the # call stack. - warnings.warn(u"DateTimeField received a naive datetime (%s)" - u" while time zone support is active." % value, + warnings.warn("DateTimeField received a naive datetime (%s)" + " while time zone support is active." % value, RuntimeWarning) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) @@ -815,8 +817,8 @@ class DateTimeField(DateField): # For backwards compatibility, interpret naive datetimes in local # time. This won't work during DST change, but we can't do much # about it, so we let the exceptions percolate up the call stack. - warnings.warn(u"DateTimeField received a naive datetime (%s)" - u" while time zone support is active." % value, + warnings.warn("DateTimeField received a naive datetime (%s)" + " while time zone support is active." % value, RuntimeWarning) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) @@ -840,7 +842,7 @@ class DateTimeField(DateField): class DecimalField(Field): empty_strings_allowed = False default_error_messages = { - 'invalid': _(u"'%s' value must be a decimal number."), + 'invalid': _("'%s' value must be a decimal number."), } description = _("Decimal number") @@ -1195,10 +1197,10 @@ class TextField(Field): class TimeField(Field): empty_strings_allowed = False default_error_messages = { - 'invalid': _(u"'%s' value has an invalid format. It must be in " - u"HH:MM[:ss[.uuuuuu]] format."), - 'invalid_time': _(u"'%s' value has the correct format " - u"(HH:MM[:ss[.uuuuuu]]) but it is an invalid time."), + 'invalid': _("'%s' value has an invalid format. It must be in " + "HH:MM[:ss[.uuuuuu]] format."), + 'invalid_time': _("'%s' value has the correct format " + "(HH:MM[:ss[.uuuuuu]]) but it is an invalid time."), } description = _("Time") diff --git a/django/db/models/fields/files.py b/django/db/models/fields/files.py index 34cf84dbc0a..e0c095974dc 100644 --- a/django/db/models/fields/files.py +++ b/django/db/models/fields/files.py @@ -207,7 +207,7 @@ class FileDescriptor(object): class FileField(Field): default_error_messages = { - 'max_length': _(u'Filename is %(extra)d characters too long.') + 'max_length': _('Filename is %(extra)d characters too long.') } # The class to wrap instance attributes in. Accessing the file object off diff --git a/django/forms/extras/widgets.py b/django/forms/extras/widgets.py index 0a2223bc3f5..6c39b25a740 100644 --- a/django/forms/extras/widgets.py +++ b/django/forms/extras/widgets.py @@ -1,6 +1,7 @@ """ Extra HTML Widget classes """ +from __future__ import unicode_literals import datetime import re @@ -90,7 +91,7 @@ class SelectDateWidget(Widget): output.append(month_html) elif field == 'day': output.append(day_html) - return mark_safe(u'\n'.join(output)) + return mark_safe('\n'.join(output)) def id_for_label(self, id_): first_select = None diff --git a/django/forms/fields.py b/django/forms/fields.py index 3811510326b..4668eade974 100644 --- a/django/forms/fields.py +++ b/django/forms/fields.py @@ -2,7 +2,7 @@ Field classes. """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import copy import datetime @@ -20,7 +20,7 @@ from django.forms.widgets import (TextInput, PasswordInput, HiddenInput, NullBooleanSelect, SelectMultiple, DateInput, DateTimeInput, TimeInput, SplitDateTimeWidget, SplitHiddenDateTimeWidget, FILE_INPUT_CONTRADICTION) from django.utils import formats -from django.utils.encoding import smart_unicode, smart_str, force_unicode +from django.utils.encoding import smart_unicode, force_unicode from django.utils.ipv6 import clean_ipv6_address from django.utils.translation import ugettext_lazy as _ @@ -44,8 +44,8 @@ class Field(object): hidden_widget = HiddenInput # Default widget to use when rendering this as "hidden". default_validators = [] # Default set of validators default_error_messages = { - 'required': _(u'This field is required.'), - 'invalid': _(u'Enter a valid value.'), + 'required': _('This field is required.'), + 'invalid': _('Enter a valid value.'), } # Tracks each time a Field instance is created. Used to retain order. @@ -78,7 +78,7 @@ class Field(object): self.required, self.label, self.initial = required, label, initial self.show_hidden_initial = show_hidden_initial if help_text is None: - self.help_text = u'' + self.help_text = '' else: self.help_text = smart_unicode(help_text) widget = widget or self.widget @@ -190,7 +190,7 @@ class CharField(Field): def to_python(self, value): "Returns a Unicode object." if value in validators.EMPTY_VALUES: - return u'' + return '' return smart_unicode(value) def widget_attrs(self, widget): @@ -202,9 +202,9 @@ class CharField(Field): class IntegerField(Field): default_error_messages = { - 'invalid': _(u'Enter a whole number.'), - 'max_value': _(u'Ensure this value is less than or equal to %(limit_value)s.'), - 'min_value': _(u'Ensure this value is greater than or equal to %(limit_value)s.'), + 'invalid': _('Enter a whole number.'), + 'max_value': _('Ensure this value is less than or equal to %(limit_value)s.'), + 'min_value': _('Ensure this value is greater than or equal to %(limit_value)s.'), } def __init__(self, max_value=None, min_value=None, *args, **kwargs): @@ -234,7 +234,7 @@ class IntegerField(Field): class FloatField(IntegerField): default_error_messages = { - 'invalid': _(u'Enter a number.'), + 'invalid': _('Enter a number.'), } def to_python(self, value): @@ -255,9 +255,9 @@ class FloatField(IntegerField): class DecimalField(Field): default_error_messages = { - 'invalid': _(u'Enter a number.'), - 'max_value': _(u'Ensure this value is less than or equal to %(limit_value)s.'), - 'min_value': _(u'Ensure this value is greater than or equal to %(limit_value)s.'), + 'invalid': _('Enter a number.'), + 'max_value': _('Ensure this value is less than or equal to %(limit_value)s.'), + 'min_value': _('Ensure this value is greater than or equal to %(limit_value)s.'), 'max_digits': _('Ensure that there are no more than %s digits in total.'), 'max_decimal_places': _('Ensure that there are no more than %s decimal places.'), 'max_whole_digits': _('Ensure that there are no more than %s digits before the decimal point.') @@ -284,7 +284,7 @@ class DecimalField(Field): return None if self.localize: value = formats.sanitize_separators(value) - value = smart_str(value).strip() + value = smart_unicode(value).strip() try: value = Decimal(value) except DecimalException: @@ -348,7 +348,7 @@ class DateField(BaseTemporalField): widget = DateInput input_formats = formats.get_format_lazy('DATE_INPUT_FORMATS') default_error_messages = { - 'invalid': _(u'Enter a valid date.'), + 'invalid': _('Enter a valid date.'), } def to_python(self, value): @@ -371,7 +371,7 @@ class TimeField(BaseTemporalField): widget = TimeInput input_formats = formats.get_format_lazy('TIME_INPUT_FORMATS') default_error_messages = { - 'invalid': _(u'Enter a valid time.') + 'invalid': _('Enter a valid time.') } def to_python(self, value): @@ -392,7 +392,7 @@ class DateTimeField(BaseTemporalField): widget = DateTimeInput input_formats = formats.get_format_lazy('DATETIME_INPUT_FORMATS') default_error_messages = { - 'invalid': _(u'Enter a valid date/time.'), + 'invalid': _('Enter a valid date/time.'), } def prepare_value(self, value): @@ -457,7 +457,7 @@ class RegexField(CharField): class EmailField(CharField): default_error_messages = { - 'invalid': _(u'Enter a valid e-mail address.'), + 'invalid': _('Enter a valid e-mail address.'), } default_validators = [validators.validate_email] @@ -468,11 +468,11 @@ class EmailField(CharField): class FileField(Field): widget = ClearableFileInput default_error_messages = { - 'invalid': _(u"No file was submitted. Check the encoding type on the form."), - 'missing': _(u"No file was submitted."), - 'empty': _(u"The submitted file is empty."), - 'max_length': _(u'Ensure this filename has at most %(max)d characters (it has %(length)d).'), - 'contradiction': _(u'Please either submit a file or check the clear checkbox, not both.') + 'invalid': _("No file was submitted. Check the encoding type on the form."), + 'missing': _("No file was submitted."), + 'empty': _("The submitted file is empty."), + 'max_length': _('Ensure this filename has at most %(max)d characters (it has %(length)d).'), + 'contradiction': _('Please either submit a file or check the clear checkbox, not both.') } def __init__(self, *args, **kwargs): @@ -527,7 +527,7 @@ class FileField(Field): class ImageField(FileField): default_error_messages = { - 'invalid_image': _(u"Upload a valid image. The file you uploaded was either not an image or a corrupted image."), + 'invalid_image': _("Upload a valid image. The file you uploaded was either not an image or a corrupted image."), } def to_python(self, data): @@ -583,7 +583,7 @@ class ImageField(FileField): class URLField(CharField): default_error_messages = { - 'invalid': _(u'Enter a valid URL.'), + 'invalid': _('Enter a valid URL.'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): @@ -669,7 +669,7 @@ class NullBooleanField(BooleanField): class ChoiceField(Field): widget = Select default_error_messages = { - 'invalid_choice': _(u'Select a valid choice. %(value)s is not one of the available choices.'), + 'invalid_choice': _('Select a valid choice. %(value)s is not one of the available choices.'), } def __init__(self, choices=(), required=True, widget=None, label=None, @@ -697,7 +697,7 @@ class ChoiceField(Field): def to_python(self, value): "Returns a Unicode object." if value in validators.EMPTY_VALUES: - return u'' + return '' return smart_unicode(value) def validate(self, value): @@ -749,8 +749,8 @@ class MultipleChoiceField(ChoiceField): hidden_widget = MultipleHiddenInput widget = SelectMultiple default_error_messages = { - 'invalid_choice': _(u'Select a valid choice. %(value)s is not one of the available choices.'), - 'invalid_list': _(u'Enter a list of values.'), + 'invalid_choice': _('Select a valid choice. %(value)s is not one of the available choices.'), + 'invalid_list': _('Enter a list of values.'), } def to_python(self, value): @@ -838,7 +838,7 @@ class MultiValueField(Field): You'll probably want to use this with MultiWidget. """ default_error_messages = { - 'invalid': _(u'Enter a list of values.'), + 'invalid': _('Enter a list of values.'), } def __init__(self, fields=(), *args, **kwargs): @@ -956,8 +956,8 @@ class SplitDateTimeField(MultiValueField): widget = SplitDateTimeWidget hidden_widget = SplitHiddenDateTimeWidget default_error_messages = { - 'invalid_date': _(u'Enter a valid date.'), - 'invalid_time': _(u'Enter a valid time.'), + 'invalid_date': _('Enter a valid date.'), + 'invalid_time': _('Enter a valid time.'), } def __init__(self, input_date_formats=None, input_time_formats=None, *args, **kwargs): @@ -990,7 +990,7 @@ class SplitDateTimeField(MultiValueField): class IPAddressField(CharField): default_error_messages = { - 'invalid': _(u'Enter a valid IPv4 address.'), + 'invalid': _('Enter a valid IPv4 address.'), } default_validators = [validators.validate_ipv4_address] @@ -1007,7 +1007,7 @@ class GenericIPAddressField(CharField): def to_python(self, value): if value in validators.EMPTY_VALUES: - return u'' + return '' if value and ':' in value: return clean_ipv6_address(value, self.unpack_ipv4, self.error_messages['invalid']) @@ -1016,7 +1016,7 @@ class GenericIPAddressField(CharField): class SlugField(CharField): default_error_messages = { - 'invalid': _(u"Enter a valid 'slug' consisting of letters, numbers," - u" underscores or hyphens."), + 'invalid': _("Enter a valid 'slug' consisting of letters, numbers," + " underscores or hyphens."), } default_validators = [validators.validate_slug] diff --git a/django/forms/forms.py b/django/forms/forms.py index 09663d173c3..22c3057c627 100644 --- a/django/forms/forms.py +++ b/django/forms/forms.py @@ -2,7 +2,7 @@ Form classes """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import copy @@ -23,7 +23,7 @@ NON_FIELD_ERRORS = '__all__' def pretty_name(name): """Converts 'first_name' to 'First name'""" if not name: - return u'' + return '' return name.replace('_', ' ').capitalize() def get_declared_fields(bases, attrs, with_base_fields=True): @@ -136,7 +136,7 @@ class BaseForm(StrAndUnicode): """ Add a 'initial' prefix for checking dynamic initial values """ - return u'initial-%s' % self.add_prefix(field_name) + return 'initial-%s' % self.add_prefix(field_name) def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row): "Helper function for outputting HTML. Used by as_table(), as_ul(), as_p()." @@ -149,7 +149,7 @@ class BaseForm(StrAndUnicode): bf_errors = self.error_class([conditional_escape(error) for error in bf.errors]) # Escape and cache in local variable. if bf.is_hidden: if bf_errors: - top_errors.extend([u'(Hidden field %s) %s' % (name, force_unicode(e)) for e in bf_errors]) + top_errors.extend(['(Hidden field %s) %s' % (name, force_unicode(e)) for e in bf_errors]) hidden_fields.append(unicode(bf)) else: # Create a 'class="..."' atribute if the row should have any @@ -175,7 +175,7 @@ class BaseForm(StrAndUnicode): if field.help_text: help_text = help_text_html % force_unicode(field.help_text) else: - help_text = u'' + help_text = '' output.append(normal_row % { 'errors': force_unicode(bf_errors), @@ -189,7 +189,7 @@ class BaseForm(StrAndUnicode): output.insert(0, error_row % force_unicode(top_errors)) if hidden_fields: # Insert any hidden fields in the last row. - str_hidden = u''.join(hidden_fields) + str_hidden = ''.join(hidden_fields) if output: last_row = output[-1] # Chop off the trailing row_ender (e.g. '') and @@ -208,33 +208,33 @@ class BaseForm(StrAndUnicode): # If there aren't any rows in the output, just append the # hidden fields. output.append(str_hidden) - return mark_safe(u'\n'.join(output)) + return mark_safe('\n'.join(output)) def as_table(self): "Returns this form rendered as HTML s -- excluding the
    ." return self._html_output( - normal_row = u'%(label)s%(errors)s%(field)s%(help_text)s', - error_row = u'%s', - row_ender = u'', - help_text_html = u'
    %s', + normal_row = '%(label)s%(errors)s%(field)s%(help_text)s', + error_row = '%s', + row_ender = '', + help_text_html = '
    %s', errors_on_separate_row = False) def as_ul(self): "Returns this form rendered as HTML
  • s -- excluding the
      ." return self._html_output( - normal_row = u'%(errors)s%(label)s %(field)s%(help_text)s
    • ', - error_row = u'
    • %s
    • ', + normal_row = '%(errors)s%(label)s %(field)s%(help_text)s', + error_row = '
    • %s
    • ', row_ender = '', - help_text_html = u' %s', + help_text_html = ' %s', errors_on_separate_row = False) def as_p(self): "Returns this form rendered as HTML

      s." return self._html_output( - normal_row = u'%(label)s %(field)s%(help_text)s

      ', - error_row = u'%s', + normal_row = '%(label)s %(field)s%(help_text)s

      ', + error_row = '%s', row_ender = '

      ', - help_text_html = u' %s', + help_text_html = ' %s', errors_on_separate_row = True) def non_field_errors(self): @@ -508,7 +508,7 @@ class BoundField(StrAndUnicode): id_ = widget.attrs.get('id') or self.auto_id if id_: attrs = attrs and flatatt(attrs) or '' - contents = u'' % (widget.id_for_label(id_), attrs, unicode(contents)) + contents = '' % (widget.id_for_label(id_), attrs, unicode(contents)) return mark_safe(contents) def css_classes(self, extra_classes=None): diff --git a/django/forms/formsets.py b/django/forms/formsets.py index 739a9d44e37..31ca088bdb3 100644 --- a/django/forms/formsets.py +++ b/django/forms/formsets.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from django.core.exceptions import ValidationError from django.forms import Form @@ -314,11 +314,11 @@ class BaseFormSet(StrAndUnicode): if self.can_order: # Only pre-fill the ordering field for initial forms. if index is not None and index < self.initial_form_count(): - form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_(u'Order'), initial=index+1, required=False) + form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_('Order'), initial=index+1, required=False) else: - form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_(u'Order'), required=False) + form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_('Order'), required=False) if self.can_delete: - form.fields[DELETION_FIELD_NAME] = BooleanField(label=_(u'Delete'), required=False) + form.fields[DELETION_FIELD_NAME] = BooleanField(label=_('Delete'), required=False) def add_prefix(self, index): return '%s-%s' % (self.prefix, index) @@ -344,18 +344,18 @@ class BaseFormSet(StrAndUnicode): # XXX: there is no semantic division between forms here, there # probably should be. It might make sense to render each form as a # table row with each field as a td. - forms = u' '.join([form.as_table() for form in self]) - return mark_safe(u'\n'.join([unicode(self.management_form), forms])) + forms = ' '.join([form.as_table() for form in self]) + return mark_safe('\n'.join([unicode(self.management_form), forms])) def as_p(self): "Returns this formset rendered as HTML

      s." - forms = u' '.join([form.as_p() for form in self]) - return mark_safe(u'\n'.join([unicode(self.management_form), forms])) + forms = ' '.join([form.as_p() for form in self]) + return mark_safe('\n'.join([unicode(self.management_form), forms])) def as_ul(self): "Returns this formset rendered as HTML

    • s." - forms = u' '.join([form.as_ul() for form in self]) - return mark_safe(u'\n'.join([unicode(self.management_form), forms])) + forms = ' '.join([form.as_ul() for form in self]) + return mark_safe('\n'.join([unicode(self.management_form), forms])) def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False, can_delete=False, max_num=None): @@ -363,7 +363,7 @@ def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False, attrs = {'form': form, 'extra': extra, 'can_order': can_order, 'can_delete': can_delete, 'max_num': max_num} - return type(form.__name__ + 'FormSet', (formset,), attrs) + return type(form.__name__ + b'FormSet', (formset,), attrs) def all_valid(formsets): """Returns true if every formset in formsets is valid.""" diff --git a/django/forms/models.py b/django/forms/models.py index 5fcf9590eb6..26f869155b5 100644 --- a/django/forms/models.py +++ b/django/forms/models.py @@ -3,7 +3,7 @@ Helper functions for creating Form classes from Django models and database field objects. """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from django.core.exceptions import ValidationError, NON_FIELD_ERRORS, FieldError from django.core.validators import EMPTY_VALUES @@ -846,7 +846,7 @@ class InlineForeignKeyField(Field): given parent instance in an inline. """ default_error_messages = { - 'invalid_choice': _(u'The inline foreign key did not match the parent instance primary key.'), + 'invalid_choice': _('The inline foreign key did not match the parent instance primary key.'), } def __init__(self, parent_instance, *args, **kwargs): @@ -884,7 +884,7 @@ class ModelChoiceIterator(object): def __iter__(self): if self.field.empty_label is not None: - yield (u"", self.field.empty_label) + yield ("", self.field.empty_label) if self.field.cache_choices: if self.field.choice_cache is None: self.field.choice_cache = [ @@ -907,11 +907,11 @@ class ModelChoiceField(ChoiceField): # This class is a subclass of ChoiceField for purity, but it doesn't # actually use any of ChoiceField's implementation. default_error_messages = { - 'invalid_choice': _(u'Select a valid choice. That choice is not one of' - u' the available choices.'), + 'invalid_choice': _('Select a valid choice. That choice is not one of' + ' the available choices.'), } - def __init__(self, queryset, empty_label=u"---------", cache_choices=False, + def __init__(self, queryset, empty_label="---------", cache_choices=False, required=True, widget=None, label=None, initial=None, help_text=None, to_field_name=None, *args, **kwargs): if required and (initial is not None): @@ -996,10 +996,10 @@ class ModelMultipleChoiceField(ModelChoiceField): widget = SelectMultiple hidden_widget = MultipleHiddenInput default_error_messages = { - 'list': _(u'Enter a list of values.'), - 'invalid_choice': _(u'Select a valid choice. %s is not one of the' - u' available choices.'), - 'invalid_pk_value': _(u'"%s" is not a valid value for a primary key.') + 'list': _('Enter a list of values.'), + 'invalid_choice': _('Select a valid choice. %s is not one of the' + ' available choices.'), + 'invalid_pk_value': _('"%s" is not a valid value for a primary key.') } def __init__(self, queryset, cache_choices=False, required=True, diff --git a/django/forms/util.py b/django/forms/util.py index 66904425346..ca53b1f3d45 100644 --- a/django/forms/util.py +++ b/django/forms/util.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.conf import settings from django.utils.html import conditional_escape from django.utils.encoding import StrAndUnicode, force_unicode @@ -16,7 +18,7 @@ def flatatt(attrs): XML-style pairs. It is assumed that the keys do not need to be XML-escaped. If the passed dictionary is empty, then return an empty string. """ - return u''.join([u' %s="%s"' % (k, conditional_escape(v)) for k, v in attrs.items()]) + return ''.join([' %s="%s"' % (k, conditional_escape(v)) for k, v in attrs.items()]) class ErrorDict(dict, StrAndUnicode): """ @@ -28,13 +30,13 @@ class ErrorDict(dict, StrAndUnicode): return self.as_ul() def as_ul(self): - if not self: return u'' - return mark_safe(u'
        %s
      ' - % ''.join([u'
    • %s%s
    • ' % (k, conditional_escape(force_unicode(v))) + if not self: return '' + return mark_safe('
        %s
      ' + % ''.join(['
    • %s%s
    • ' % (k, conditional_escape(force_unicode(v))) for k, v in self.items()])) def as_text(self): - return u'\n'.join([u'* %s\n%s' % (k, u'\n'.join([u' * %s' % force_unicode(i) for i in v])) for k, v in self.items()]) + return '\n'.join(['* %s\n%s' % (k, '\n'.join([' * %s' % force_unicode(i) for i in v])) for k, v in self.items()]) class ErrorList(list, StrAndUnicode): """ @@ -44,13 +46,13 @@ class ErrorList(list, StrAndUnicode): return self.as_ul() def as_ul(self): - if not self: return u'' - return mark_safe(u'
        %s
      ' - % ''.join([u'
    • %s
    • ' % conditional_escape(force_unicode(e)) for e in self])) + if not self: return '' + return mark_safe('
        %s
      ' + % ''.join(['
    • %s
    • ' % conditional_escape(force_unicode(e)) for e in self])) def as_text(self): - if not self: return u'' - return u'\n'.join([u'* %s' % force_unicode(e) for e in self]) + if not self: return '' + return '\n'.join(['* %s' % force_unicode(e) for e in self]) def __repr__(self): return repr([force_unicode(e) for e in self]) diff --git a/django/forms/widgets.py b/django/forms/widgets.py index 4813af69e96..2fddee918a2 100644 --- a/django/forms/widgets.py +++ b/django/forms/widgets.py @@ -2,7 +2,7 @@ HTML Widget classes """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import copy import datetime @@ -50,10 +50,10 @@ class Media(StrAndUnicode): return self.render() def render(self): - return mark_safe(u'\n'.join(chain(*[getattr(self, 'render_' + name)() for name in MEDIA_TYPES]))) + return mark_safe('\n'.join(chain(*[getattr(self, 'render_' + name)() for name in MEDIA_TYPES]))) def render_js(self): - return [u'' % self.absolute_path(path) for path in self._js] + return ['' % self.absolute_path(path) for path in self._js] def render_css(self): # To keep rendering order consistent, we can't just iterate over items(). @@ -61,12 +61,12 @@ class Media(StrAndUnicode): media = self._css.keys() media.sort() return chain(*[ - [u'' % (self.absolute_path(path), medium) + ['' % (self.absolute_path(path), medium) for path in self._css[medium]] for medium in media]) def absolute_path(self, path, prefix=None): - if path.startswith(u'http://') or path.startswith(u'https://') or path.startswith(u'/'): + if path.startswith(('http://', 'https://', '/')): return path if prefix is None: if settings.STATIC_URL is None: @@ -210,13 +210,13 @@ class Widget(object): """ # For purposes of seeing whether something has changed, None is # the same as an empty string, if the data or inital value we get - # is None, replace it w/ u''. + # is None, replace it w/ ''. if data is None: - data_value = u'' + data_value = '' else: data_value = data if initial is None: - initial_value = u'' + initial_value = '' else: initial_value = initial if force_unicode(initial_value) != force_unicode(data_value): @@ -254,7 +254,7 @@ class Input(Widget): if value != '': # Only add the 'value' attribute if a value is non-empty. final_attrs['value'] = force_unicode(self._format_value(value)) - return mark_safe(u'' % flatatt(final_attrs)) + return mark_safe('' % flatatt(final_attrs)) class TextInput(Input): input_type = 'text' @@ -295,8 +295,8 @@ class MultipleHiddenInput(HiddenInput): # An ID attribute was given. Add a numeric index as a suffix # so that the inputs don't all have the same ID attribute. input_attrs['id'] = '%s_%s' % (id_, i) - inputs.append(u'' % flatatt(input_attrs)) - return mark_safe(u'\n'.join(inputs)) + inputs.append('' % flatatt(input_attrs)) + return mark_safe('\n'.join(inputs)) def value_from_datadict(self, data, files, name): if isinstance(data, (MultiValueDict, MergeDict)): @@ -326,9 +326,9 @@ class ClearableFileInput(FileInput): input_text = ugettext_lazy('Change') clear_checkbox_label = ugettext_lazy('Clear') - template_with_initial = u'%(initial_text)s: %(initial)s %(clear_template)s
      %(input_text)s: %(input)s' + template_with_initial = '%(initial_text)s: %(initial)s %(clear_template)s
      %(input_text)s: %(input)s' - template_with_clear = u'%(clear)s ' + template_with_clear = '%(clear)s ' def clear_checkbox_name(self, name): """ @@ -350,12 +350,12 @@ class ClearableFileInput(FileInput): 'clear_template': '', 'clear_checkbox_label': self.clear_checkbox_label, } - template = u'%(input)s' + template = '%(input)s' substitutions['input'] = super(ClearableFileInput, self).render(name, value, attrs) if value and hasattr(value, "url"): template = self.template_with_initial - substitutions['initial'] = (u'%s' + substitutions['initial'] = ('%s' % (escape(value.url), escape(force_unicode(value)))) if not self.is_required: @@ -392,7 +392,7 @@ class Textarea(Widget): def render(self, name, value, attrs=None): if value is None: value = '' final_attrs = self.build_attrs(attrs, name=name) - return mark_safe(u'%s' % (flatatt(final_attrs), + return mark_safe('%s' % (flatatt(final_attrs), conditional_escape(force_unicode(value)))) class DateInput(Input): @@ -511,7 +511,7 @@ class CheckboxInput(Widget): if not (value is True or value is False or value is None or value == ''): # Only add the 'value' attribute if a value is non-empty. final_attrs['value'] = force_unicode(value) - return mark_safe(u'' % flatatt(final_attrs)) + return mark_safe('' % flatatt(final_attrs)) def value_from_datadict(self, data, files, name): if name not in data: @@ -526,7 +526,7 @@ class CheckboxInput(Widget): return value def _has_changed(self, initial, data): - # Sometimes data or initial could be None or u'' which should be the + # Sometimes data or initial could be None or '' which should be the # same thing as False. return bool(initial) != bool(data) @@ -543,23 +543,23 @@ class Select(Widget): def render(self, name, value, attrs=None, choices=()): if value is None: value = '' final_attrs = self.build_attrs(attrs, name=name) - output = [u'' % flatatt(final_attrs)] + output = ['' % flatatt(final_attrs)] options = self.render_options(choices, [value]) if options: output.append(options) - output.append(u'') - return mark_safe(u'\n'.join(output)) + output.append('') + return mark_safe('\n'.join(output)) def render_option(self, selected_choices, option_value, option_label): option_value = force_unicode(option_value) if option_value in selected_choices: - selected_html = u' selected="selected"' + selected_html = ' selected="selected"' if not self.allow_multiple_selected: # Only allow for a single selection. selected_choices.remove(option_value) else: selected_html = '' - return u'' % ( + return '' % ( escape(option_value), selected_html, conditional_escape(force_unicode(option_label))) @@ -569,37 +569,37 @@ class Select(Widget): output = [] for option_value, option_label in chain(self.choices, choices): if isinstance(option_label, (list, tuple)): - output.append(u'' % escape(force_unicode(option_value))) + output.append('' % escape(force_unicode(option_value))) for option in option_label: output.append(self.render_option(selected_choices, *option)) - output.append(u'') + output.append('') else: output.append(self.render_option(selected_choices, option_value, option_label)) - return u'\n'.join(output) + return '\n'.join(output) class NullBooleanSelect(Select): """ A Select Widget intended to be used with NullBooleanField. """ def __init__(self, attrs=None): - choices = ((u'1', ugettext_lazy('Unknown')), - (u'2', ugettext_lazy('Yes')), - (u'3', ugettext_lazy('No'))) + choices = (('1', ugettext_lazy('Unknown')), + ('2', ugettext_lazy('Yes')), + ('3', ugettext_lazy('No'))) super(NullBooleanSelect, self).__init__(attrs, choices) def render(self, name, value, attrs=None, choices=()): try: - value = {True: u'2', False: u'3', u'2': u'2', u'3': u'3'}[value] + value = {True: '2', False: '3', '2': '2', '3': '3'}[value] except KeyError: - value = u'1' + value = '1' return super(NullBooleanSelect, self).render(name, value, attrs, choices) def value_from_datadict(self, data, files, name): value = data.get(name, None) - return {u'2': True, + return {'2': True, True: True, 'True': True, - u'3': False, + '3': False, 'False': False, False: False}.get(value, None) @@ -618,12 +618,12 @@ class SelectMultiple(Select): def render(self, name, value, attrs=None, choices=()): if value is None: value = [] final_attrs = self.build_attrs(attrs, name=name) - output = [u'' % flatatt(final_attrs)] options = self.render_options(choices, value) if options: output.append(options) output.append('') - return mark_safe(u'\n'.join(output)) + return mark_safe('\n'.join(output)) def value_from_datadict(self, data, files, name): if isinstance(data, (MultiValueDict, MergeDict)): @@ -666,7 +666,7 @@ class RadioInput(SubWidget): else: label_for = '' choice_label = conditional_escape(force_unicode(self.choice_label)) - return mark_safe(u'%s %s' % (label_for, self.tag(), choice_label)) + return mark_safe('%s %s' % (label_for, self.tag(), choice_label)) def is_checked(self): return self.value == self.choice_value @@ -677,7 +677,7 @@ class RadioInput(SubWidget): final_attrs = dict(self.attrs, type='radio', name=self.name, value=self.choice_value) if self.is_checked(): final_attrs['checked'] = 'checked' - return mark_safe(u'' % flatatt(final_attrs)) + return mark_safe('' % flatatt(final_attrs)) class RadioFieldRenderer(StrAndUnicode): """ @@ -701,7 +701,7 @@ class RadioFieldRenderer(StrAndUnicode): def render(self): """Outputs a
        for this set of radio fields.""" - return mark_safe(u'
          \n%s\n
        ' % u'\n'.join([u'
      • %s
      • ' + return mark_safe('
          \n%s\n
        ' % '\n'.join(['
      • %s
      • ' % force_unicode(w) for w in self])) class RadioSelect(Select): @@ -743,7 +743,7 @@ class CheckboxSelectMultiple(SelectMultiple): if value is None: value = [] has_id = attrs and 'id' in attrs final_attrs = self.build_attrs(attrs, name=name) - output = [u'
          '] + output = ['
            '] # Normalize to strings str_values = set([force_unicode(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): @@ -751,7 +751,7 @@ class CheckboxSelectMultiple(SelectMultiple): # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) - label_for = u' for="%s"' % final_attrs['id'] + label_for = ' for="%s"' % final_attrs['id'] else: label_for = '' @@ -759,9 +759,9 @@ class CheckboxSelectMultiple(SelectMultiple): option_value = force_unicode(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_unicode(option_label)) - output.append(u'
          • %s %s
          • ' % (label_for, rendered_cb, option_label)) - output.append(u'
          ') - return mark_safe(u'\n'.join(output)) + output.append('
        • %s %s
        • ' % (label_for, rendered_cb, option_label)) + output.append('
        ') + return mark_safe('\n'.join(output)) def id_for_label(self, id_): # See the comment for RadioSelect.id_for_label() @@ -832,7 +832,7 @@ class MultiWidget(Widget): def _has_changed(self, initial, data): if initial is None: - initial = [u'' for x in range(0, len(data))] + initial = ['' for x in range(0, len(data))] else: if not isinstance(initial, list): initial = self.decompress(initial) @@ -849,7 +849,7 @@ class MultiWidget(Widget): This hook allows you to format the HTML design of the widgets, if needed. """ - return u''.join(rendered_widgets) + return ''.join(rendered_widgets) def decompress(self, value): """ diff --git a/django/http/__init__.py b/django/http/__init__.py index bf848deb388..30d7e5dc2f1 100644 --- a/django/http/__init__.py +++ b/django/http/__init__.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import datetime import os @@ -57,13 +57,14 @@ else: if not _cookie_allows_colon_in_names: def load(self, rawdata): self.bad_cookies = set() - super(SimpleCookie, self).load(rawdata) + super(SimpleCookie, self).load(smart_str(rawdata)) for key in self.bad_cookies: del self[key] # override private __set() method: # (needed for using our Morsel, and for laxness with CookieError def _BaseCookie__set(self, key, real_value, coded_value): + key = smart_str(key) try: M = self.get(key, Morsel()) M.set(key, real_value, coded_value) @@ -131,7 +132,7 @@ def build_request_repr(request, path_override=None, GET_override=None, except: meta = '' path = path_override if path_override is not None else request.path - return smart_str(u'<%s\npath:%s,\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s>' % + return smart_str('<%s\npath:%s,\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s>' % (request.__class__.__name__, path, unicode(get), @@ -488,6 +489,7 @@ class QueryDict(MultiValueDict): """ output = [] if safe: + safe = smart_str(safe, self.encoding) encode = lambda k, v: '%s=%s' % ((quote(k, safe), quote(v, safe))) else: encode = lambda k, v: urlencode({k: v}) diff --git a/django/http/multipartparser.py b/django/http/multipartparser.py index 162c08e38d0..bbe4b052b77 100644 --- a/django/http/multipartparser.py +++ b/django/http/multipartparser.py @@ -4,6 +4,7 @@ Multi-part parsing for file uploads. Exposes one class, ``MultiPartParser``, which feeds chunks of uploaded data to file upload handlers for processing. """ +from __future__ import unicode_literals import cgi from django.conf import settings @@ -59,7 +60,7 @@ class MultiPartParser(object): raise MultiPartParserError('Invalid Content-Type: %s' % content_type) # Parse the header to get the boundary to split the parts. - ctypes, opts = parse_header(content_type) + ctypes, opts = parse_header(content_type.encode('ascii')) boundary = opts.get('boundary') if not boundary or not cgi.valid_boundary(boundary): raise MultiPartParserError('Invalid boundary in multipart: %s' % boundary) @@ -76,6 +77,8 @@ class MultiPartParser(object): # This means we shouldn't continue...raise an error. raise MultiPartParserError("Invalid content length: %r" % content_length) + if isinstance(boundary, unicode): + boundary = boundary.encode('ascii') self._boundary = boundary self._input_data = input_data @@ -589,14 +592,17 @@ class Parser(object): yield parse_boundary_stream(sub_stream, 1024) def parse_header(line): - """ Parse the header into a key-value. """ + """ Parse the header into a key-value. + Input (line): bytes, output: unicode for key/name, bytes for value which + will be decoded later + """ plist = _parse_header_params(b';' + line) - key = plist.pop(0).lower() + key = plist.pop(0).lower().decode('ascii') pdict = {} for p in plist: i = p.find(b'=') if i >= 0: - name = p[:i].strip().lower() + name = p[:i].strip().lower().decode('ascii') value = p[i+1:].strip() if len(value) >= 2 and value[0] == value[-1] == b'"': value = value[1:-1] diff --git a/django/template/base.py b/django/template/base.py index 9b2404cdb3b..5a91bfda99c 100644 --- a/django/template/base.py +++ b/django/template/base.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re from functools import partial @@ -836,7 +836,7 @@ class NodeList(list): else: bit = node bits.append(force_unicode(bit)) - return mark_safe(u''.join(bits)) + return mark_safe(''.join(bits)) def get_nodes_by_type(self, nodetype): "Return a list of all nodes of the given type" @@ -1006,8 +1006,8 @@ def parse_bits(parser, bits, params, varargs, varkw, defaults, if unhandled_params: # Some positional arguments were not supplied raise TemplateSyntaxError( - u"'%s' did not receive value(s) for the argument(s): %s" % - (name, u", ".join([u"'%s'" % p for p in unhandled_params]))) + "'%s' did not receive value(s) for the argument(s): %s" % + (name, ", ".join(["'%s'" % p for p in unhandled_params]))) return args, kwargs def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py index 1a3976f4045..d2c5b03f30f 100644 --- a/django/template/defaultfilters.py +++ b/django/template/defaultfilters.py @@ -1,4 +1,5 @@ """Default variable filters.""" +from __future__ import unicode_literals import re import random as random_module @@ -140,14 +141,14 @@ def floatformat(text, arg=-1): input_val = force_unicode(text) d = Decimal(input_val) except UnicodeEncodeError: - return u'' + return '' except InvalidOperation: if input_val in special_floats: return input_val try: d = Decimal(force_unicode(float(text))) except (ValueError, InvalidOperation, TypeError, UnicodeEncodeError): - return u'' + return '' try: p = int(arg) except ValueError: @@ -159,12 +160,12 @@ def floatformat(text, arg=-1): return input_val if not m and p < 0: - return mark_safe(formats.number_format(u'%d' % (int(d)), 0)) + return mark_safe(formats.number_format('%d' % (int(d)), 0)) if p == 0: exp = Decimal(1) else: - exp = Decimal(u'1.0') / (Decimal(10) ** abs(p)) + exp = Decimal('1.0') / (Decimal(10) ** abs(p)) try: # Set the precision high enough to avoid an exception, see #15789. tupl = d.as_tuple() @@ -177,11 +178,11 @@ def floatformat(text, arg=-1): Context(prec=prec)).as_tuple() digits = [unicode(digit) for digit in reversed(digits)] while len(digits) <= abs(exponent): - digits.append(u'0') - digits.insert(-exponent, u'.') + digits.append('0') + digits.insert(-exponent, '.') if sign: - digits.append(u'-') - number = u''.join(reversed(digits)) + digits.append('-') + number = ''.join(reversed(digits)) return mark_safe(formats.number_format(number, abs(p))) except InvalidOperation: return input_val @@ -196,17 +197,17 @@ def iriencode(value): @stringfilter def linenumbers(value, autoescape=None): """Displays text with line numbers.""" - lines = value.split(u'\n') + lines = value.split('\n') # Find the maximum width of the line count, for use with zero padding # string format command width = unicode(len(unicode(len(lines)))) if not autoescape or isinstance(value, SafeData): for i, line in enumerate(lines): - lines[i] = (u"%0" + width + u"d. %s") % (i + 1, line) + lines[i] = ("%0" + width + "d. %s") % (i + 1, line) else: for i, line in enumerate(lines): - lines[i] = (u"%0" + width + u"d. %s") % (i + 1, escape(line)) - return mark_safe(u'\n'.join(lines)) + lines[i] = ("%0" + width + "d. %s") % (i + 1, escape(line)) + return mark_safe('\n'.join(lines)) @register.filter(is_safe=True) @stringfilter @@ -248,9 +249,9 @@ def stringformat(value, arg): of Python string formatting """ try: - return (u"%" + unicode(arg)) % value + return ("%" + unicode(arg)) % value except (ValueError, TypeError): - return u"" + return "" @register.filter(is_safe=True) @stringfilter @@ -394,7 +395,7 @@ def cut(value, arg): Removes all values of arg from the given string. """ safe = isinstance(value, SafeData) - value = value.replace(arg, u'') + value = value.replace(arg, '') if safe and arg != ';': return mark_safe(value) return value @@ -467,11 +468,11 @@ def safeseq(value): def removetags(value, tags): """Removes a space separated list of [X]HTML tags from the output.""" tags = [re.escape(tag) for tag in tags.split()] - tags_re = u'(%s)' % u'|'.join(tags) - starttag_re = re.compile(ur'<%s(/?>|(\s+[^>]*>))' % tags_re, re.U) - endtag_re = re.compile(u'' % tags_re) - value = starttag_re.sub(u'', value) - value = endtag_re.sub(u'', value) + tags_re = '(%s)' % '|'.join(tags) + starttag_re = re.compile(r'<%s(/?>|(\s+[^>]*>))' % tags_re, re.U) + endtag_re = re.compile('' % tags_re) + value = starttag_re.sub('', value) + value = endtag_re.sub('', value) return value @register.filter(is_safe=True) @@ -493,7 +494,7 @@ def dictsort(value, arg): try: return sorted(value, key=Variable(arg).resolve) except (TypeError, VariableDoesNotExist): - return u'' + return '' @register.filter(is_safe=False) def dictsortreversed(value, arg): @@ -504,7 +505,7 @@ def dictsortreversed(value, arg): try: return sorted(value, key=Variable(arg).resolve, reverse=True) except (TypeError, VariableDoesNotExist): - return u'' + return '' @register.filter(is_safe=False) def first(value): @@ -512,7 +513,7 @@ def first(value): try: return value[0] except IndexError: - return u'' + return '' @register.filter(is_safe=True, needs_autoescape=True) def join(value, arg, autoescape=None): @@ -534,7 +535,7 @@ def last(value): try: return value[-1] except IndexError: - return u'' + return '' @register.filter(is_safe=True) def length(value): @@ -568,7 +569,7 @@ def slice_filter(value, arg): """ try: bits = [] - for x in arg.split(u':'): + for x in arg.split(':'): if len(x) == 0: bits.append(None) else: @@ -635,7 +636,7 @@ def unordered_list(value, autoescape=None): second_item = new_second_item return [first_item, second_item], old_style_list def _helper(list_, tabs=1): - indent = u'\t' * tabs + indent = '\t' * tabs output = [] list_length = len(list_) @@ -708,7 +709,7 @@ def get_digit(value, arg): def date(value, arg=None): """Formats a date according to the given format.""" if not value: - return u'' + return '' if arg is None: arg = settings.DATE_FORMAT try: @@ -722,8 +723,8 @@ def date(value, arg=None): @register.filter(expects_localtime=True, is_safe=False) def time(value, arg=None): """Formats a time according to the given format.""" - if value in (None, u''): - return u'' + if value in (None, ''): + return '' if arg is None: arg = settings.TIME_FORMAT try: @@ -738,23 +739,23 @@ def time(value, arg=None): def timesince_filter(value, arg=None): """Formats a date as the time since that date (i.e. "4 days, 6 hours").""" if not value: - return u'' + return '' try: if arg: return timesince(value, arg) return timesince(value) except (ValueError, TypeError): - return u'' + 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").""" if not value: - return u'' + return '' try: return timeuntil(value, arg) except (ValueError, TypeError): - return u'' + return '' ################### # LOGIC # @@ -795,7 +796,7 @@ def yesno(value, arg=None): """ if arg is None: arg = ugettext('yes,no,maybe') - bits = arg.split(u',') + bits = arg.split(',') if len(bits) < 2: return value # Invalid arg. try: @@ -839,7 +840,7 @@ def filesizeformat(bytes): return ugettext("%s PB") % filesize_number_format(bytes / (1024 * 1024 * 1024 * 1024 * 1024)) @register.filter(is_safe=False) -def pluralize(value, arg=u's'): +def pluralize(value, arg='s'): """ Returns a plural suffix if the value is not 1. By default, 's' is used as the suffix: @@ -862,11 +863,11 @@ def pluralize(value, arg=u's'): * If value is 1, cand{{ value|pluralize:"y,ies" }} displays "1 candy". * If value is 2, cand{{ value|pluralize:"y,ies" }} displays "2 candies". """ - if not u',' in arg: - arg = u',' + arg - bits = arg.split(u',') + if not ',' in arg: + arg = ',' + arg + bits = arg.split(',') if len(bits) > 2: - return u'' + return '' singular_suffix, plural_suffix = bits[:2] try: @@ -893,4 +894,4 @@ def pprint(value): try: return pformat(value) except Exception as e: - return u"Error in formatting: %s" % force_unicode(e, errors="replace") + return "Error in formatting: %s" % force_unicode(e, errors="replace") diff --git a/django/template/defaulttags.py b/django/template/defaulttags.py index 3073b41049e..0de5d9e3db6 100644 --- a/django/template/defaulttags.py +++ b/django/template/defaulttags.py @@ -1,4 +1,5 @@ """Default tags used by the template system, available to all templates.""" +from __future__ import unicode_literals import sys import re @@ -13,7 +14,7 @@ from django.template.base import (Node, NodeList, Template, Context, Library, VARIABLE_ATTRIBUTE_SEPARATOR, get_library, token_kwargs, kwarg_re) from django.template.smartif import IfParser, Literal from django.template.defaultfilters import date -from django.utils.encoding import smart_str, smart_unicode +from django.utils.encoding import smart_unicode from django.utils.safestring import mark_safe from django.utils import timezone @@ -43,9 +44,9 @@ class CsrfTokenNode(Node): csrf_token = context.get('csrf_token', None) if csrf_token: if csrf_token == 'NOTPROVIDED': - return mark_safe(u"") + return mark_safe("") else: - return mark_safe(u"
        " % csrf_token) + return mark_safe("
        " % csrf_token) else: # It's very probable that the token is missing because of # misconfiguration, so we raise a warning @@ -53,7 +54,7 @@ class CsrfTokenNode(Node): if settings.DEBUG: import warnings 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 u'' + return '' class CycleNode(Node): def __init__(self, cyclevars, variable_name=None, silent=False): @@ -102,7 +103,7 @@ class FirstOfNode(Node): value = var.resolve(context, True) if value: return smart_unicode(value) - return u'' + return '' class ForNode(Node): child_nodelists = ('nodelist_loop', 'nodelist_empty') @@ -390,7 +391,7 @@ class URLNode(Node): def render(self, context): from django.core.urlresolvers import reverse, NoReverseMatch args = [arg.resolve(context) for arg in self.args] - kwargs = dict([(smart_str(k, 'ascii'), v.resolve(context)) + kwargs = dict([(smart_unicode(k, 'ascii'), v.resolve(context)) for k, v in self.kwargs.items()]) view_name = self.view_name.resolve(context) @@ -486,7 +487,7 @@ def autoescape(parser, token): if len(args) != 2: raise TemplateSyntaxError("'autoescape' tag requires exactly one argument.") arg = args[1] - if arg not in (u'on', u'off'): + if arg not in ('on', 'off'): raise TemplateSyntaxError("'autoescape' argument should be 'on' or 'off'") nodelist = parser.parse(('endautoescape',)) parser.delete_first_token() diff --git a/django/templatetags/cache.py b/django/templatetags/cache.py index 8183452422f..056eadc7de0 100644 --- a/django/templatetags/cache.py +++ b/django/templatetags/cache.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import hashlib from django.template import Library, Node, TemplateSyntaxError, Variable, VariableDoesNotExist from django.template import resolve_variable @@ -23,7 +25,7 @@ class CacheNode(Node): except (ValueError, TypeError): raise TemplateSyntaxError('"cache" tag got a non-integer timeout value: %r' % expire_time) # Build a unicode key for this fragment and all vary-on's. - args = hashlib.md5(u':'.join([urlquote(resolve_variable(var, context)) for var in self.vary_on])) + args = hashlib.md5(':'.join([urlquote(resolve_variable(var, context)) for var in self.vary_on])) cache_key = 'template.cache.%s.%s' % (self.fragment_name, args.hexdigest()) value = cache.get(cache_key) if value is None: @@ -57,5 +59,5 @@ def do_cache(parser, token): parser.delete_first_token() tokens = token.contents.split() if len(tokens) < 3: - raise TemplateSyntaxError(u"'%r' tag requires at least 2 arguments." % tokens[0]) + raise TemplateSyntaxError("'%r' tag requires at least 2 arguments." % tokens[0]) return CacheNode(nodelist, tokens[1], tokens[2], tokens[3:]) diff --git a/django/templatetags/i18n.py b/django/templatetags/i18n.py index e090781080d..231b723d3a5 100644 --- a/django/templatetags/i18n.py +++ b/django/templatetags/i18n.py @@ -1,3 +1,4 @@ +from __future__ import unicode_literals import re from django.template import (Node, Variable, TemplateSyntaxError, @@ -76,7 +77,7 @@ class TranslateNode(Node): self.message_context = message_context self.filter_expression = filter_expression if isinstance(self.filter_expression.var, basestring): - self.filter_expression.var = Variable(u"'%s'" % + self.filter_expression.var = Variable("'%s'" % self.filter_expression.var) def render(self, context): @@ -110,7 +111,7 @@ class BlockTranslateNode(Node): if token.token_type == TOKEN_TEXT: result.append(token.contents) elif token.token_type == TOKEN_VAR: - result.append(u'%%(%s)s' % token.contents) + result.append('%%(%s)s' % token.contents) vars.append(token.contents) return ''.join(result), vars @@ -127,12 +128,12 @@ class BlockTranslateNode(Node): context.update(tmp_context) singular, vars = self.render_token_list(self.singular) # Escape all isolated '%' - singular = re.sub(u'%(?!\()', u'%%', singular) + singular = re.sub('%(?!\()', '%%', singular) if self.plural and self.countervar and self.counter: count = self.counter.resolve(context) context[self.countervar] = count plural, plural_vars = self.render_token_list(self.plural) - plural = re.sub(u'%(?!\()', u'%%', plural) + plural = re.sub('%(?!\()', '%%', plural) if message_context: result = translation.npgettext(message_context, singular, plural, count) diff --git a/django/test/client.py b/django/test/client.py index 3cc6a6e5376..79844426f1f 100644 --- a/django/test/client.py +++ b/django/test/client.py @@ -146,7 +146,7 @@ def encode_file(boundary, key, file): if content_type is None: content_type = 'application/octet-stream' return [ - '--' + boundary, + '--' + to_str(boundary), 'Content-Disposition: form-data; name="%s"; filename="%s"' \ % (to_str(key), to_str(os.path.basename(file.name))), 'Content-Type: %s' % content_type, diff --git a/django/test/html.py b/django/test/html.py index f1e4897efd2..79b198f1beb 100644 --- a/django/test/html.py +++ b/django/test/html.py @@ -1,6 +1,9 @@ """ Comparing two html documents. """ + +from __future__ import unicode_literals + import re from HTMLParser import HTMLParseError from django.utils.encoding import force_unicode @@ -113,18 +116,18 @@ class Element(object): return self.children[key] def __unicode__(self): - output = u'<%s' % self.name + output = '<%s' % self.name for key, value in self.attributes: if value: - output += u' %s="%s"' % (key, value) + output += ' %s="%s"' % (key, value) else: - output += u' %s' % key + output += ' %s' % key if self.children: - output += u'>\n' - output += u''.join(unicode(c) for c in self.children) - output += u'\n' % self.name + output += '>\n' + output += ''.join(unicode(c) for c in self.children) + output += '\n' % self.name else: - output += u' />' + output += ' />' return output def __repr__(self): @@ -136,7 +139,7 @@ class RootElement(Element): super(RootElement, self).__init__(None, ()) def __unicode__(self): - return u''.join(unicode(c) for c in self.children) + return ''.join(unicode(c) for c in self.children) class Parser(HTMLParser): diff --git a/django/test/testcases.py b/django/test/testcases.py index e2d7b3f82e2..95e751d3846 100644 --- a/django/test/testcases.py +++ b/django/test/testcases.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import difflib import json import os @@ -85,7 +87,7 @@ def assert_and_parse_html(self, html, user_msg, msg): try: dom = parse_html(html) except HTMLParseError as e: - standardMsg = u'%s\n%s' % (msg, e.msg) + standardMsg = '%s\n%s' % (msg, e.msg) self.fail(self._formatMessage(user_msg, standardMsg)) return dom @@ -205,10 +207,6 @@ class OutputChecker(doctest.OutputChecker): "foo" >>> o._strip_quotes('"foo"') "foo" - >>> o._strip_quotes("u'foo'") - "foo" - >>> o._strip_quotes('u"foo"') - "foo" """ def is_quoted_string(s): s = s.strip() @@ -292,7 +290,7 @@ class _AssertTemplateUsedContext(object): return self.template_name in self.rendered_template_names def message(self): - return u'%s was not rendered.' % self.template_name + return '%s was not rendered.' % self.template_name def __enter__(self): template_rendered.connect(self.on_template_render) @@ -306,9 +304,9 @@ class _AssertTemplateUsedContext(object): if not self.test(): message = self.message() if len(self.rendered_templates) == 0: - message += u' No template was rendered.' + message += ' No template was rendered.' else: - message += u' Following templates were rendered: %s' % ( + message += ' Following templates were rendered: %s' % ( ', '.join(self.rendered_template_names)) self.test_case.fail(message) @@ -318,7 +316,7 @@ class _AssertTemplateNotUsedContext(_AssertTemplateUsedContext): return self.template_name not in self.rendered_template_names def message(self): - return u'%s was rendered.' % self.template_name + return '%s was rendered.' % self.template_name class SimpleTestCase(ut2.TestCase): @@ -359,7 +357,7 @@ class SimpleTestCase(ut2.TestCase): re.escape(expected_message), callable_obj, *args, **kwargs) def assertFieldOutput(self, fieldclass, valid, invalid, field_args=None, - field_kwargs=None, empty_value=u''): + field_kwargs=None, empty_value=''): """ Asserts that a form field behaves correctly with various inputs. @@ -415,9 +413,9 @@ class SimpleTestCase(ut2.TestCase): significant. The passed-in arguments must be valid HTML. """ dom1 = assert_and_parse_html(self, html1, msg, - u'First argument is not valid HTML:') + 'First argument is not valid HTML:') dom2 = assert_and_parse_html(self, html2, msg, - u'Second argument is not valid HTML:') + 'Second argument is not valid HTML:') if dom1 != dom2: standardMsg = '%s != %s' % ( @@ -431,9 +429,9 @@ class SimpleTestCase(ut2.TestCase): def assertHTMLNotEqual(self, html1, html2, msg=None): """Asserts that two HTML snippets are not semantically equivalent.""" dom1 = assert_and_parse_html(self, html1, msg, - u'First argument is not valid HTML:') + 'First argument is not valid HTML:') dom2 = assert_and_parse_html(self, html2, msg, - u'Second argument is not valid HTML:') + 'Second argument is not valid HTML:') if dom1 == dom2: standardMsg = '%s == %s' % ( @@ -620,14 +618,14 @@ class TransactionTestCase(SimpleTestCase): self.assertEqual(response.status_code, status_code, msg_prefix + "Couldn't retrieve content: Response code was %d" " (expected %d)" % (response.status_code, status_code)) - text = smart_str(text, response._charset) + enc_text = smart_str(text, response._charset) content = response.content if html: content = assert_and_parse_html(self, content, None, - u"Response's content is not valid HTML:") - text = assert_and_parse_html(self, text, None, - u"Second argument is not valid HTML:") - real_count = content.count(text) + "Response's content is not valid HTML:") + enc_text = assert_and_parse_html(self, enc_text, None, + "Second argument is not valid HTML:") + real_count = content.count(enc_text) if count is not None: self.assertEqual(real_count, count, msg_prefix + "Found %d instances of '%s' in response" @@ -656,14 +654,14 @@ class TransactionTestCase(SimpleTestCase): self.assertEqual(response.status_code, status_code, msg_prefix + "Couldn't retrieve content: Response code was %d" " (expected %d)" % (response.status_code, status_code)) - text = smart_str(text, response._charset) + enc_text = smart_str(text, response._charset) content = response.content if html: content = assert_and_parse_html(self, content, None, - u'Response\'s content is not valid HTML:') - text = assert_and_parse_html(self, text, None, - u'Second argument is not valid HTML:') - self.assertEqual(content.count(text), 0, + 'Response\'s content is not valid HTML:') + enc_text = assert_and_parse_html(self, enc_text, None, + 'Second argument is not valid HTML:') + self.assertEqual(content.count(enc_text), 0, msg_prefix + "Response should not contain '%s'" % text) def assertFormError(self, response, form, field, errors, msg_prefix=''): @@ -723,7 +721,7 @@ class TransactionTestCase(SimpleTestCase): the response. Also usable as context manager. """ if response is None and template_name is None: - raise TypeError(u'response and/or template_name argument must be provided') + raise TypeError('response and/or template_name argument must be provided') if msg_prefix: msg_prefix += ": " @@ -742,7 +740,7 @@ class TransactionTestCase(SimpleTestCase): self.assertTrue(template_name in template_names, msg_prefix + "Template '%s' was not a template used to render" " the response. Actual template(s) used: %s" % - (template_name, u', '.join(template_names))) + (template_name, ', '.join(template_names))) def assertTemplateNotUsed(self, response=None, template_name=None, msg_prefix=''): """ @@ -750,7 +748,7 @@ class TransactionTestCase(SimpleTestCase): rendering the response. Also usable as context manager. """ if response is None and template_name is None: - raise TypeError(u'response and/or template_name argument must be provided') + raise TypeError('response and/or template_name argument must be provided') if msg_prefix: msg_prefix += ": " diff --git a/django/test/utils.py b/django/test/utils.py index 805117df808..ca4a5e74745 100644 --- a/django/test/utils.py +++ b/django/test/utils.py @@ -219,3 +219,5 @@ class override_settings(object): setting_changed.send(sender=settings._wrapped.__class__, setting=key, value=new_value) +def str_prefix(s): + return s % {'_': 'u'} diff --git a/django/utils/crypto.py b/django/utils/crypto.py index 0fce06012ba..cc59e2e39f9 100644 --- a/django/utils/crypto.py +++ b/django/utils/crypto.py @@ -1,6 +1,7 @@ """ Django's standard crypto functions and utilities. """ +from __future__ import unicode_literals import hmac import struct @@ -42,7 +43,7 @@ def salted_hmac(key_salt, value, secret=None): # We need to generate a derived key from our base key. We can do this by # passing the key_salt and our base key through a pseudo-random function and # SHA1 works nicely. - key = hashlib.sha1(key_salt + secret).digest() + key = hashlib.sha1((key_salt + secret).encode('utf-8')).digest() # If len(key_salt + secret) > sha_constructor().block_size, the above # line is redundant and could be replaced by key = key_salt + secret, since @@ -105,7 +106,7 @@ def _long_to_bin(x, hex_format_string): Convert a long integer into a binary string. hex_format_string is like "%020x" for padding 10 characters. """ - return binascii.unhexlify(hex_format_string % x) + return binascii.unhexlify((hex_format_string % x).encode('ascii')) def _fast_hmac(key, msg, digest): @@ -113,6 +114,7 @@ def _fast_hmac(key, msg, digest): A trimmed down version of Python's HMAC implementation """ dig1, dig2 = digest(), digest() + key = smart_str(key) if len(key) > dig1.block_size: key = digest(key).digest() key += chr(0) * (dig1.block_size - len(key)) diff --git a/django/utils/dateformat.py b/django/utils/dateformat.py index e16a2df1f28..d410bce63e1 100644 --- a/django/utils/dateformat.py +++ b/django/utils/dateformat.py @@ -10,6 +10,7 @@ Usage: 7th October 2003 11:39 >>> """ +from __future__ import unicode_literals import re import time @@ -33,7 +34,7 @@ class Formatter(object): pieces.append(force_unicode(getattr(self, piece)())) elif piece: pieces.append(re_escaped.sub(r'\1', piece)) - return u''.join(pieces) + return ''.join(pieces) class TimeFormat(Formatter): def __init__(self, t): @@ -64,7 +65,7 @@ class TimeFormat(Formatter): """ if self.data.minute == 0: return self.g() - return u'%s:%s' % (self.g(), self.i()) + return '%s:%s' % (self.g(), self.i()) def g(self): "Hour, 12-hour format without leading zeros; i.e. '1' to '12'" @@ -80,15 +81,15 @@ class TimeFormat(Formatter): def h(self): "Hour, 12-hour format; i.e. '01' to '12'" - return u'%02d' % self.g() + return '%02d' % self.g() def H(self): "Hour, 24-hour format; i.e. '00' to '23'" - return u'%02d' % self.G() + return '%02d' % self.G() def i(self): "Minutes; i.e. '00' to '59'" - return u'%02d' % self.data.minute + return '%02d' % self.data.minute def P(self): """ @@ -101,11 +102,11 @@ class TimeFormat(Formatter): return _('midnight') if self.data.minute == 0 and self.data.hour == 12: return _('noon') - return u'%s %s' % (self.f(), self.a()) + return '%s %s' % (self.f(), self.a()) def s(self): "Seconds; i.e. '00' to '59'" - return u'%02d' % self.data.second + return '%02d' % self.data.second def u(self): "Microseconds" @@ -138,7 +139,7 @@ class DateFormat(TimeFormat): def d(self): "Day of the month, 2 digits with leading zeros; i.e. '01' to '31'" - return u'%02d' % self.data.day + return '%02d' % self.data.day def D(self): "Day of the week, textual, 3 letters; e.g. 'Fri'" @@ -166,9 +167,9 @@ class DateFormat(TimeFormat): def I(self): "'1' if Daylight Savings Time, '0' otherwise." if self.timezone and self.timezone.dst(self.data): - return u'1' + return '1' else: - return u'0' + return '0' def j(self): "Day of the month without leading zeros; i.e. '1' to '31'" @@ -184,7 +185,7 @@ class DateFormat(TimeFormat): def m(self): "Month; i.e. '01' to '12'" - return u'%02d' % self.data.month + return '%02d' % self.data.month def M(self): "Month, textual, 3 letters; e.g. 'Jan'" @@ -207,7 +208,7 @@ class DateFormat(TimeFormat): seconds = self.Z() sign = '-' if seconds < 0 else '+' seconds = abs(seconds) - return u"%s%02d%02d" % (sign, seconds // 3600, (seconds // 60) % 60) + return "%s%02d%02d" % (sign, seconds // 3600, (seconds // 60) % 60) def r(self): "RFC 2822 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'" @@ -216,19 +217,19 @@ class DateFormat(TimeFormat): def S(self): "English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'" if self.data.day in (11, 12, 13): # Special case - return u'th' + return 'th' last = self.data.day % 10 if last == 1: - return u'st' + return 'st' if last == 2: - return u'nd' + return 'nd' if last == 3: - return u'rd' - return u'th' + return 'rd' + return 'th' def t(self): "Number of days in the given month; i.e. '28' to '31'" - return u'%02d' % calendar.monthrange(self.data.year, self.data.month)[1] + return '%02d' % calendar.monthrange(self.data.year, self.data.month)[1] def T(self): "Time zone of this machine; e.g. 'EST' or 'MDT'" diff --git a/django/utils/encoding.py b/django/utils/encoding.py index 6b246ac59bb..80e456ba2a4 100644 --- a/django/utils/encoding.py +++ b/django/utils/encoding.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import urllib import locale import datetime @@ -80,7 +82,7 @@ def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'): # without raising a further exception. We do an # approximation to what the Exception's standard str() # output should be. - s = u' '.join([force_unicode(arg, encoding, strings_only, + s = ' '.join([force_unicode(arg, encoding, strings_only, errors) for arg in s]) elif not isinstance(s, unicode): # Note: We use .decode() here, instead of unicode(s, encoding, @@ -96,7 +98,7 @@ def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'): # working unicode method. Try to handle this without raising a # further exception by individually forcing the exception args # to unicode. - s = u' '.join([force_unicode(arg, encoding, strings_only, + s = ' '.join([force_unicode(arg, encoding, strings_only, errors) for arg in s]) return s diff --git a/django/utils/feedgenerator.py b/django/utils/feedgenerator.py index 7cd15674d6b..52f40fb5f18 100644 --- a/django/utils/feedgenerator.py +++ b/django/utils/feedgenerator.py @@ -5,14 +5,14 @@ Sample usage: >>> from django.utils import feedgenerator >>> feed = feedgenerator.Rss201rev2Feed( -... title=u"Poynter E-Media Tidbits", -... link=u"http://www.poynter.org/column.asp?id=31", -... description=u"A group Weblog by the sharpest minds in online media/journalism/publishing.", -... language=u"en", +... title="Poynter E-Media Tidbits", +... link="http://www.poynter.org/column.asp?id=31", +... description="A group Weblog by the sharpest minds in online media/journalism/publishing.", +... language="en", ... ) >>> feed.add_item( ... title="Hello", -... link=u"http://www.holovaty.com/test/", +... link="http://www.holovaty.com/test/", ... description="Testing." ... ) >>> with open('test.rss', 'w') as fp: @@ -21,6 +21,7 @@ Sample usage: For definitions of the different versions of RSS, see: http://diveintomark.org/archives/2004/02/04/incompatible-rss """ +from __future__ import unicode_literals import datetime import urlparse @@ -70,7 +71,7 @@ def get_tag_uri(url, date): d = '' if date is not None: d = ',%s' % datetime_safe.new_datetime(date).strftime('%Y-%m-%d') - return u'tag:%s%s:%s/%s' % (bits.hostname, d, bits.path, bits.fragment) + 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()" @@ -203,177 +204,177 @@ class RssFeed(SyndicationFeed): def write(self, outfile, encoding): handler = SimplerXMLGenerator(outfile, encoding) handler.startDocument() - handler.startElement(u"rss", self.rss_attributes()) - handler.startElement(u"channel", self.root_attributes()) + handler.startElement("rss", self.rss_attributes()) + handler.startElement("channel", self.root_attributes()) self.add_root_elements(handler) self.write_items(handler) self.endChannelElement(handler) - handler.endElement(u"rss") + handler.endElement("rss") def rss_attributes(self): - return {u"version": self._version, - u"xmlns:atom": u"http://www.w3.org/2005/Atom"} + return {"version": self._version, + "xmlns:atom": "http://www.w3.org/2005/Atom"} def write_items(self, handler): for item in self.items: - handler.startElement(u'item', self.item_attributes(item)) + handler.startElement('item', self.item_attributes(item)) self.add_item_elements(handler, item) - handler.endElement(u"item") + handler.endElement("item") def add_root_elements(self, handler): - handler.addQuickElement(u"title", self.feed['title']) - handler.addQuickElement(u"link", self.feed['link']) - handler.addQuickElement(u"description", self.feed['description']) + handler.addQuickElement("title", self.feed['title']) + handler.addQuickElement("link", self.feed['link']) + handler.addQuickElement("description", self.feed['description']) if self.feed['feed_url'] is not None: - handler.addQuickElement(u"atom:link", None, - {u"rel": u"self", u"href": self.feed['feed_url']}) + handler.addQuickElement("atom:link", None, + {"rel": "self", "href": self.feed['feed_url']}) if self.feed['language'] is not None: - handler.addQuickElement(u"language", self.feed['language']) + handler.addQuickElement("language", self.feed['language']) for cat in self.feed['categories']: - handler.addQuickElement(u"category", cat) + handler.addQuickElement("category", cat) if self.feed['feed_copyright'] is not None: - handler.addQuickElement(u"copyright", self.feed['feed_copyright']) - handler.addQuickElement(u"lastBuildDate", rfc2822_date(self.latest_post_date()).decode('utf-8')) + handler.addQuickElement("copyright", self.feed['feed_copyright']) + handler.addQuickElement("lastBuildDate", rfc2822_date(self.latest_post_date()).decode('utf-8')) if self.feed['ttl'] is not None: - handler.addQuickElement(u"ttl", self.feed['ttl']) + handler.addQuickElement("ttl", self.feed['ttl']) def endChannelElement(self, handler): - handler.endElement(u"channel") + handler.endElement("channel") class RssUserland091Feed(RssFeed): - _version = u"0.91" + _version = "0.91" def add_item_elements(self, handler, item): - handler.addQuickElement(u"title", item['title']) - handler.addQuickElement(u"link", item['link']) + handler.addQuickElement("title", item['title']) + handler.addQuickElement("link", item['link']) if item['description'] is not None: - handler.addQuickElement(u"description", item['description']) + handler.addQuickElement("description", item['description']) class Rss201rev2Feed(RssFeed): # Spec: http://blogs.law.harvard.edu/tech/rss - _version = u"2.0" + _version = "2.0" def add_item_elements(self, handler, item): - handler.addQuickElement(u"title", item['title']) - handler.addQuickElement(u"link", item['link']) + handler.addQuickElement("title", item['title']) + handler.addQuickElement("link", item['link']) if item['description'] is not None: - handler.addQuickElement(u"description", item['description']) + handler.addQuickElement("description", item['description']) # Author information. if item["author_name"] and item["author_email"]: - handler.addQuickElement(u"author", "%s (%s)" % \ + handler.addQuickElement("author", "%s (%s)" % \ (item['author_email'], item['author_name'])) elif item["author_email"]: - handler.addQuickElement(u"author", item["author_email"]) + handler.addQuickElement("author", item["author_email"]) elif item["author_name"]: - handler.addQuickElement(u"dc:creator", item["author_name"], {u"xmlns:dc": u"http://purl.org/dc/elements/1.1/"}) + handler.addQuickElement("dc:creator", item["author_name"], {"xmlns:dc": "http://purl.org/dc/elements/1.1/"}) if item['pubdate'] is not None: - handler.addQuickElement(u"pubDate", rfc2822_date(item['pubdate']).decode('utf-8')) + handler.addQuickElement("pubDate", rfc2822_date(item['pubdate']).decode('utf-8')) if item['comments'] is not None: - handler.addQuickElement(u"comments", item['comments']) + handler.addQuickElement("comments", item['comments']) if item['unique_id'] is not None: - handler.addQuickElement(u"guid", item['unique_id']) + handler.addQuickElement("guid", item['unique_id']) if item['ttl'] is not None: - handler.addQuickElement(u"ttl", item['ttl']) + handler.addQuickElement("ttl", item['ttl']) # Enclosure. if item['enclosure'] is not None: - handler.addQuickElement(u"enclosure", '', - {u"url": item['enclosure'].url, u"length": item['enclosure'].length, - u"type": item['enclosure'].mime_type}) + handler.addQuickElement("enclosure", '', + {"url": item['enclosure'].url, "length": item['enclosure'].length, + "type": item['enclosure'].mime_type}) # Categories. for cat in item['categories']: - handler.addQuickElement(u"category", cat) + 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' - ns = u"http://www.w3.org/2005/Atom" + ns = "http://www.w3.org/2005/Atom" def write(self, outfile, encoding): handler = SimplerXMLGenerator(outfile, encoding) handler.startDocument() - handler.startElement(u'feed', self.root_attributes()) + handler.startElement('feed', self.root_attributes()) self.add_root_elements(handler) self.write_items(handler) - handler.endElement(u"feed") + handler.endElement("feed") def root_attributes(self): if self.feed['language'] is not None: - return {u"xmlns": self.ns, u"xml:lang": self.feed['language']} + return {"xmlns": self.ns, "xml:lang": self.feed['language']} else: - return {u"xmlns": self.ns} + return {"xmlns": self.ns} def add_root_elements(self, handler): - handler.addQuickElement(u"title", self.feed['title']) - handler.addQuickElement(u"link", "", {u"rel": u"alternate", u"href": self.feed['link']}) + handler.addQuickElement("title", self.feed['title']) + handler.addQuickElement("link", "", {"rel": "alternate", "href": self.feed['link']}) if self.feed['feed_url'] is not None: - handler.addQuickElement(u"link", "", {u"rel": u"self", u"href": self.feed['feed_url']}) - handler.addQuickElement(u"id", self.feed['id']) - handler.addQuickElement(u"updated", rfc3339_date(self.latest_post_date()).decode('utf-8')) + handler.addQuickElement("link", "", {"rel": "self", "href": self.feed['feed_url']}) + handler.addQuickElement("id", self.feed['id']) + handler.addQuickElement("updated", rfc3339_date(self.latest_post_date()).decode('utf-8')) if self.feed['author_name'] is not None: - handler.startElement(u"author", {}) - handler.addQuickElement(u"name", self.feed['author_name']) + handler.startElement("author", {}) + handler.addQuickElement("name", self.feed['author_name']) if self.feed['author_email'] is not None: - handler.addQuickElement(u"email", self.feed['author_email']) + handler.addQuickElement("email", self.feed['author_email']) if self.feed['author_link'] is not None: - handler.addQuickElement(u"uri", self.feed['author_link']) - handler.endElement(u"author") + handler.addQuickElement("uri", self.feed['author_link']) + handler.endElement("author") if self.feed['subtitle'] is not None: - handler.addQuickElement(u"subtitle", self.feed['subtitle']) + handler.addQuickElement("subtitle", self.feed['subtitle']) for cat in self.feed['categories']: - handler.addQuickElement(u"category", "", {u"term": cat}) + handler.addQuickElement("category", "", {"term": cat}) if self.feed['feed_copyright'] is not None: - handler.addQuickElement(u"rights", self.feed['feed_copyright']) + handler.addQuickElement("rights", self.feed['feed_copyright']) def write_items(self, handler): for item in self.items: - handler.startElement(u"entry", self.item_attributes(item)) + handler.startElement("entry", self.item_attributes(item)) self.add_item_elements(handler, item) - handler.endElement(u"entry") + handler.endElement("entry") def add_item_elements(self, handler, item): - handler.addQuickElement(u"title", item['title']) - handler.addQuickElement(u"link", u"", {u"href": item['link'], u"rel": u"alternate"}) + handler.addQuickElement("title", item['title']) + handler.addQuickElement("link", "", {"href": item['link'], "rel": "alternate"}) if item['pubdate'] is not None: - handler.addQuickElement(u"updated", rfc3339_date(item['pubdate']).decode('utf-8')) + handler.addQuickElement("updated", rfc3339_date(item['pubdate']).decode('utf-8')) # Author information. if item['author_name'] is not None: - handler.startElement(u"author", {}) - handler.addQuickElement(u"name", item['author_name']) + handler.startElement("author", {}) + handler.addQuickElement("name", item['author_name']) if item['author_email'] is not None: - handler.addQuickElement(u"email", item['author_email']) + handler.addQuickElement("email", item['author_email']) if item['author_link'] is not None: - handler.addQuickElement(u"uri", item['author_link']) - handler.endElement(u"author") + handler.addQuickElement("uri", item['author_link']) + handler.endElement("author") # Unique ID. if item['unique_id'] is not None: unique_id = item['unique_id'] else: unique_id = get_tag_uri(item['link'], item['pubdate']) - handler.addQuickElement(u"id", unique_id) + handler.addQuickElement("id", unique_id) # Summary. if item['description'] is not None: - handler.addQuickElement(u"summary", item['description'], {u"type": u"html"}) + handler.addQuickElement("summary", item['description'], {"type": "html"}) # Enclosure. if item['enclosure'] is not None: - handler.addQuickElement(u"link", '', - {u"rel": u"enclosure", - u"href": item['enclosure'].url, - u"length": item['enclosure'].length, - u"type": item['enclosure'].mime_type}) + handler.addQuickElement("link", '', + {"rel": "enclosure", + "href": item['enclosure'].url, + "length": item['enclosure'].length, + "type": item['enclosure'].mime_type}) # Categories. for cat in item['categories']: - handler.addQuickElement(u"category", u"", {u"term": cat}) + handler.addQuickElement("category", "", {"term": cat}) # Rights. if item['item_copyright'] is not None: - handler.addQuickElement(u"rights", item['item_copyright']) + handler.addQuickElement("rights", item['item_copyright']) # This isolates the decision of what the system default is, so calling code can # do "feedgenerator.DefaultFeed" instead of "feedgenerator.Rss201rev2Feed". diff --git a/django/utils/html.py b/django/utils/html.py index 1b1a16a9119..014d837bbb3 100644 --- a/django/utils/html.py +++ b/django/utils/html.py @@ -1,5 +1,7 @@ """HTML utilities suitable for global use.""" +from __future__ import unicode_literals + import re import string import urllib @@ -15,7 +17,7 @@ TRAILING_PUNCTUATION = ['.', ',', ':', ';'] WRAPPING_PUNCTUATION = [('(', ')'), ('<', '>'), ('<', '>')] # List of possible strings used for bullets in bulleted lists. -DOTS = [u'·', u'*', u'\u2022', u'•', u'•', u'•'] +DOTS = ['·', '*', '\u2022', '•', '•', '•'] unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)') unquoted_percents_re = re.compile(r'%(?![0-9A-Fa-f]{2})') @@ -37,17 +39,17 @@ def escape(html): escape = allow_lazy(escape, unicode) _base_js_escapes = ( - ('\\', r'\u005C'), - ('\'', r'\u0027'), - ('"', r'\u0022'), - ('>', r'\u003E'), - ('<', r'\u003C'), - ('&', r'\u0026'), - ('=', r'\u003D'), - ('-', r'\u002D'), - (';', r'\u003B'), - (u'\u2028', r'\u2028'), - (u'\u2029', r'\u2029') + ('\\', '\\u005C'), + ('\'', '\\u0027'), + ('"', '\\u0022'), + ('>', '\\u003E'), + ('<', '\\u003C'), + ('&', '\\u0026'), + ('=', '\\u003D'), + ('-', '\\u002D'), + (';', '\\u003B'), + ('\u2028', '\\u2028'), + ('\u2029', '\\u2029') ) # Escape every ASCII character with a value less than 32. @@ -75,10 +77,10 @@ def linebreaks(value, autoescape=False): value = normalize_newlines(value) paras = re.split('\n{2,}', value) if autoescape: - paras = [u'

        %s

        ' % escape(p).replace('\n', '
        ') for p in paras] + paras = ['

        %s

        ' % escape(p).replace('\n', '
        ') for p in paras] else: - paras = [u'

        %s

        ' % p.replace('\n', '
        ') for p in paras] - return u'\n\n'.join(paras) + paras = ['

        %s

        ' % p.replace('\n', '
        ') for p in paras] + return '\n\n'.join(paras) linebreaks = allow_lazy(linebreaks, unicode) def strip_tags(value): @@ -192,7 +194,7 @@ def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): words[i] = mark_safe(word) elif autoescape: words[i] = escape(word) - return u''.join(words) + return ''.join(words) urlize = allow_lazy(urlize, unicode) def clean_html(text): @@ -218,13 +220,13 @@ def clean_html(text): text = html_gunk_re.sub('', text) # Convert hard-coded bullets into HTML unordered lists. def replace_p_tags(match): - s = match.group().replace(u'

        ', u'') + s = match.group().replace('

        ', '') for d in DOTS: - s = s.replace(u'

        %s' % d, u'

      • ') - return u'
          \n%s\n
        ' % s + s = s.replace('

        %s' % d, '

      • ') + return '
          \n%s\n
        ' % s text = hard_coded_bullets_re.sub(replace_p_tags, text) # Remove stuff like "

          

        ", but only if it's at the bottom # of the text. - text = trailing_empty_content_re.sub(u'', text) + text = trailing_empty_content_re.sub('', text) return text clean_html = allow_lazy(clean_html, unicode) diff --git a/django/utils/regex_helper.py b/django/utils/regex_helper.py index f17b263c379..4b8ecea7217 100644 --- a/django/utils/regex_helper.py +++ b/django/utils/regex_helper.py @@ -5,6 +5,7 @@ Used internally by Django and not intended for external use. This is not, and is not intended to be, a complete reg-exp decompiler. It should be good enough for a large class of URLS, however. """ +from __future__ import unicode_literals # Mapping of an escape character to a representative of that class. So, e.g., # "\w" is replaced by "x" in a reverse URL. A value of None means to ignore @@ -13,12 +14,12 @@ ESCAPE_MAPPINGS = { "A": None, "b": None, "B": None, - "d": u"0", - "D": u"x", - "s": u" ", - "S": u"x", - "w": u"x", - "W": u"!", + "d": "0", + "D": "x", + "s": " ", + "S": "x", + "w": "x", + "W": "!", "Z": None, } @@ -77,7 +78,7 @@ def normalize(pattern): try: ch, escaped = next(pattern_iter) except StopIteration: - return zip([u''], [[]]) + return zip([''], [[]]) try: while True: @@ -85,7 +86,7 @@ def normalize(pattern): result.append(ch) elif ch == '.': # Replace "any character" with an arbitrary representative. - result.append(u".") + result.append(".") elif ch == '|': # FIXME: One day we'll should do this, but not in 1.0. raise NotImplementedError @@ -117,7 +118,7 @@ def normalize(pattern): # A positional group name = "_%d" % num_args num_args += 1 - result.append(Group(((u"%%(%s)s" % name), name))) + result.append(Group((("%%(%s)s" % name), name))) walk_to_end(ch, pattern_iter) else: ch, escaped = next(pattern_iter) @@ -152,10 +153,10 @@ def normalize(pattern): # Named backreferences have already consumed the # parenthesis. if terminal_char != ')': - result.append(Group(((u"%%(%s)s" % param), param))) + result.append(Group((("%%(%s)s" % param), param))) walk_to_end(ch, pattern_iter) else: - result.append(Group(((u"%%(%s)s" % param), None))) + result.append(Group((("%%(%s)s" % param), None))) elif ch in "*?+{": # Quanitifers affect the previous item in the result list. count, ch = get_quantifier(ch, pattern_iter) @@ -190,7 +191,7 @@ def normalize(pattern): pass except NotImplementedError: # A case of using the disjunctive form. No results for you! - return zip([u''], [[]]) + return zip([''], [[]]) return zip(*flatten_result(result)) @@ -290,20 +291,20 @@ def flatten_result(source): Each of the two lists will be of the same length. """ if source is None: - return [u''], [[]] + return [''], [[]] if isinstance(source, Group): if source[1] is None: params = [] else: params = [source[1]] return [source[0]], [params] - result = [u''] + result = [''] result_args = [[]] pos = last = 0 for pos, elt in enumerate(source): if isinstance(elt, basestring): continue - piece = u''.join(source[last:pos]) + piece = ''.join(source[last:pos]) if isinstance(elt, Group): piece += elt[0] param = elt[1] @@ -331,7 +332,7 @@ def flatten_result(source): result = new_result result_args = new_args if pos >= last: - piece = u''.join(source[last:]) + piece = ''.join(source[last:]) for i in range(len(result)): result[i] += piece return result, result_args diff --git a/django/utils/text.py b/django/utils/text.py index 8ae0bf76630..2546f770b54 100644 --- a/django/utils/text.py +++ b/django/utils/text.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import re import unicodedata import warnings @@ -43,7 +45,7 @@ def wrap(text, width): if len(lines) > 1: pos = len(lines[-1]) yield word - return u''.join(_generator()) + return ''.join(_generator()) wrap = allow_lazy(wrap, unicode) @@ -58,7 +60,7 @@ class Truncator(SimpleLazyObject): if truncate is None: truncate = pgettext( 'String to return when truncating text', - u'%(truncated_text)s...') + '%(truncated_text)s...') truncate = force_unicode(truncate) if '%(truncated_text)s' in truncate: return truncate % {'truncated_text': text} @@ -130,8 +132,8 @@ class Truncator(SimpleLazyObject): words = self._wrapped.split() if len(words) > length: words = words[:length] - return self.add_truncation_text(u' '.join(words), truncate) - return u' '.join(words) + return self.add_truncation_text(' '.join(words), truncate) + return ' '.join(words) def _html_words(self, length, truncate): """ @@ -142,7 +144,7 @@ class Truncator(SimpleLazyObject): Newlines in the HTML are preserved. """ if length <= 0: - return u'' + return '' html4_singlets = ( 'br', 'col', 'link', 'base', 'img', 'param', 'area', 'hr', 'input' @@ -221,28 +223,28 @@ def get_valid_filename(s): spaces are converted to underscores; and anything that is not a unicode alphanumeric, dash, underscore, or dot, is removed. >>> get_valid_filename("john's portrait in 2004.jpg") - u'johns_portrait_in_2004.jpg' + 'johns_portrait_in_2004.jpg' """ s = force_unicode(s).strip().replace(' ', '_') return re.sub(r'(?u)[^-\w.]', '', s) get_valid_filename = allow_lazy(get_valid_filename, unicode) -def get_text_list(list_, last_word=ugettext_lazy(u'or')): +def get_text_list(list_, last_word=ugettext_lazy('or')): """ >>> get_text_list(['a', 'b', 'c', 'd']) - u'a, b, c or d' + 'a, b, c or d' >>> get_text_list(['a', 'b', 'c'], 'and') - u'a, b and c' + 'a, b and c' >>> get_text_list(['a', 'b'], 'and') - u'a and b' + 'a and b' >>> get_text_list(['a']) - u'a' + 'a' >>> get_text_list([]) - u'' + '' """ - if len(list_) == 0: return u'' + if len(list_) == 0: return '' if len(list_) == 1: return force_unicode(list_[0]) - return u'%s %s %s' % ( + return '%s %s %s' % ( # Translators: This string is used as a separator between list elements _(', ').join([force_unicode(i) for i in list_][:-1]), force_unicode(last_word), force_unicode(list_[-1])) @@ -267,7 +269,7 @@ def phone2numeric(phone): 'n': '6', 'o': '6', 'p': '7', 'q': '7', 'r': '7', 's': '7', 't': '8', 'u': '8', 'v': '8', 'w': '9', 'x': '9', 'y': '9', 'z': '9', } - return u''.join(char2number.get(c, c) for c in phone.lower()) + 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 @@ -279,12 +281,12 @@ def compress_string(s): zfile.close() return zbuf.getvalue() -ustring_re = re.compile(u"([\u0080-\uffff])") +ustring_re = re.compile("([\u0080-\uffff])") def javascript_quote(s, quote_double_quotes=False): def fix(match): - return r"\u%04x" % ord(match.group(1)) + return b"\u%04x" % ord(match.group(1)) if type(s) == str: s = s.decode('utf-8') @@ -321,11 +323,11 @@ def smart_split(text): be further processed with unescape_string_literal()). >>> list(smart_split(r'This is "a person\'s" test.')) - [u'This', u'is', u'"a person\\\'s"', u'test.'] + ['This', 'is', '"a person\\\'s"', 'test.'] >>> list(smart_split(r"Another 'person\'s' test.")) - [u'Another', u"'person\\'s'", u'test.'] + ['Another', "'person\\'s'", 'test.'] >>> list(smart_split(r'A "\"funky\" style" test.')) - [u'A', u'"\\"funky\\" style"', u'test.'] + ['A', '"\\"funky\\" style"', 'test.'] """ text = force_unicode(text) for bit in smart_split_re.finditer(text): @@ -334,10 +336,10 @@ smart_split = allow_lazy(smart_split, unicode) def _replace_entity(match): text = match.group(1) - if text[0] == u'#': + if text[0] == '#': text = text[1:] try: - if text[0] in u'xX': + if text[0] in 'xX': c = int(text[1:], 16) else: c = int(text) diff --git a/django/utils/timesince.py b/django/utils/timesince.py index 276108b55a0..1721f097bdb 100644 --- a/django/utils/timesince.py +++ b/django/utils/timesince.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import datetime from django.utils.timezone import is_aware, utc @@ -38,7 +40,7 @@ def timesince(d, now=None, reversed=False): since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: # d is in the future compared to now, stop processing. - return u'0 ' + ugettext('minutes') + return '0 ' + ugettext('minutes') for i, (seconds, name) in enumerate(chunks): count = since // seconds if count != 0: diff --git a/django/utils/translation/__init__.py b/django/utils/translation/__init__.py index ac062823a4a..0f1f28e5c44 100644 --- a/django/utils/translation/__init__.py +++ b/django/utils/translation/__init__.py @@ -1,6 +1,8 @@ """ Internationalization support. """ +from __future__ import unicode_literals + from django.utils.encoding import force_unicode from django.utils.functional import lazy @@ -136,7 +138,7 @@ def _string_concat(*strings): Lazy variant of string concatenation, needed for translations that are constructed from multiple parts. """ - return u''.join([force_unicode(s) for s in strings]) + return ''.join([force_unicode(s) for s in strings]) string_concat = lazy(_string_concat, unicode) def get_language_info(lang_code): diff --git a/django/utils/translation/trans_real.py b/django/utils/translation/trans_real.py index 135a8cf6d5b..0cd13fd6f59 100644 --- a/django/utils/translation/trans_real.py +++ b/django/utils/translation/trans_real.py @@ -1,11 +1,12 @@ """Translation helper functions.""" +from __future__ import unicode_literals import locale import os import re import sys import gettext as gettext_module -from io import BytesIO +from io import StringIO from threading import local from django.utils.importlib import import_module @@ -25,7 +26,7 @@ _default = None _accepted = {} # magic gettext number to separate context from message -CONTEXT_SEPARATOR = u"\x04" +CONTEXT_SEPARATOR = "\x04" # Format of Accept-Language header values. From RFC 2616, section 14.4 and 3.9. accept_language_re = re.compile(r''' @@ -263,7 +264,7 @@ def ugettext(message): def pgettext(context, message): result = do_translate( - u"%s%s%s" % (context, CONTEXT_SEPARATOR, message), 'ugettext') + "%s%s%s" % (context, CONTEXT_SEPARATOR, message), 'ugettext') if CONTEXT_SEPARATOR in result: # Translation not found result = message @@ -304,8 +305,8 @@ def ungettext(singular, plural, number): return do_ntranslate(singular, plural, number, 'ungettext') def npgettext(context, singular, plural, number): - result = do_ntranslate(u"%s%s%s" % (context, CONTEXT_SEPARATOR, singular), - u"%s%s%s" % (context, CONTEXT_SEPARATOR, plural), + result = do_ntranslate("%s%s%s" % (context, CONTEXT_SEPARATOR, singular), + "%s%s%s" % (context, CONTEXT_SEPARATOR, plural), number, 'ungettext') if CONTEXT_SEPARATOR in result: # Translation not found @@ -436,9 +437,11 @@ def templatize(src, origin=None): does so by translating the Django translation tags into standard gettext function invocations. """ + from django.conf import settings from django.template import (Lexer, TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK, TOKEN_COMMENT, TRANSLATOR_COMMENT_MARK) - out = BytesIO() + src = src.decode(settings.FILE_CHARSET) + out = StringIO() message_context = None intrans = False inplural = False @@ -449,16 +452,16 @@ def templatize(src, origin=None): for t in Lexer(src, origin).tokenize(): if incomment: if t.token_type == TOKEN_BLOCK and t.contents == 'endcomment': - content = b''.join(comment) + content = ''.join(comment) translators_comment_start = None for lineno, line in enumerate(content.splitlines(True)): if line.lstrip().startswith(TRANSLATOR_COMMENT_MARK): translators_comment_start = lineno for lineno, line in enumerate(content.splitlines(True)): if translators_comment_start is not None and lineno >= translators_comment_start: - out.write(b' # %s' % line) + out.write(' # %s' % line) else: - out.write(b' #\n') + out.write(' #\n') incomment = False comment = [] else: @@ -470,18 +473,18 @@ def templatize(src, origin=None): if endbmatch: if inplural: if message_context: - out.write(b' npgettext(%r, %r, %r,count) ' % (message_context, ''.join(singular), ''.join(plural))) + out.write(' npgettext(%r, %r, %r,count) ' % (message_context, ''.join(singular), ''.join(plural))) else: - out.write(b' ngettext(%r, %r, count) ' % (''.join(singular), ''.join(plural))) + out.write(' ngettext(%r, %r, count) ' % (''.join(singular), ''.join(plural))) for part in singular: out.write(blankout(part, 'S')) for part in plural: out.write(blankout(part, 'P')) else: if message_context: - out.write(b' pgettext(%r, %r) ' % (message_context, ''.join(singular))) + out.write(' pgettext(%r, %r) ' % (message_context, ''.join(singular))) else: - out.write(b' gettext(%r) ' % ''.join(singular)) + out.write(' gettext(%r) ' % ''.join(singular)) for part in singular: out.write(blankout(part, 'S')) message_context = None @@ -527,10 +530,10 @@ def templatize(src, origin=None): message_context = message_context.strip('"') elif message_context[0] == "'": message_context = message_context.strip("'") - out.write(b' pgettext(%r, %r) ' % (message_context, g)) + out.write(' pgettext(%r, %r) ' % (message_context, g)) message_context = None else: - out.write(b' gettext(%r) ' % g) + out.write(' gettext(%r) ' % g) elif bmatch: for fmatch in constant_re.findall(t.contents): out.write(' _(%s) ' % fmatch) @@ -548,7 +551,7 @@ def templatize(src, origin=None): plural = [] elif cmatches: for cmatch in cmatches: - out.write(b' _(%s) ' % cmatch) + out.write(' _(%s) ' % cmatch) elif t.contents == 'comment': incomment = True else: @@ -557,17 +560,17 @@ def templatize(src, origin=None): parts = t.contents.split('|') cmatch = constant_re.match(parts[0]) if cmatch: - out.write(b' _(%s) ' % cmatch.group(1)) + out.write(' _(%s) ' % cmatch.group(1)) for p in parts[1:]: if p.find(':_(') >= 0: - out.write(b' %s ' % p.split(':',1)[1]) + out.write(' %s ' % p.split(':',1)[1]) else: out.write(blankout(p, 'F')) elif t.token_type == TOKEN_COMMENT: - out.write(b' # %s' % t.contents) + out.write(' # %s' % t.contents) else: out.write(blankout(t.contents, 'X')) - return out.getvalue() + return out.getvalue().encode('utf-8') def parse_accept_lang_header(lang_string): """ diff --git a/django/utils/tzinfo.py b/django/utils/tzinfo.py index a07b635a995..05f4aa6d2fe 100644 --- a/django/utils/tzinfo.py +++ b/django/utils/tzinfo.py @@ -1,5 +1,7 @@ "Implementation of tzinfo classes for use with datetime.datetime." +from __future__ import unicode_literals + import time from datetime import timedelta, tzinfo @@ -20,7 +22,7 @@ class FixedOffset(tzinfo): self.__offset = timedelta(minutes=offset) sign = '-' if offset < 0 else '+' - self.__name = u"%s%02d%02d" % (sign, abs(offset) / 60., abs(offset) % 60) + self.__name = "%s%02d%02d" % (sign, abs(offset) / 60., abs(offset) % 60) def __repr__(self): return self.__name diff --git a/django/utils/version.py b/django/utils/version.py index 3f108b8af29..3d66b9ef529 100644 --- a/django/utils/version.py +++ b/django/utils/version.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import datetime import os import subprocess diff --git a/django/views/debug.py b/django/views/debug.py index d95cd620175..25eee4a91a6 100644 --- a/django/views/debug.py +++ b/django/views/debug.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import datetime import os import re @@ -16,7 +18,7 @@ from django.utils.encoding import smart_unicode, smart_str HIDDEN_SETTINGS = re.compile('API|TOKEN|KEY|SECRET|PASS|PROFANITIES_LIST|SIGNATURE') -CLEANSED_SUBSTITUTE = u'********************' +CLEANSED_SUBSTITUTE = '********************' def linebreak_iter(template_source): yield 0 @@ -355,7 +357,7 @@ class ExceptionReporter(object): for line in source[:2]: # File coding may be specified. Match pattern from PEP-263 # (http://www.python.org/dev/peps/pep-0263/) - match = re.search(r'coding[:=]\s*([-\w.]+)', line) + match = re.search(br'coding[:=]\s*([-\w.]+)', line) if match: encoding = match.group(1) break diff --git a/django/views/generic/base.py b/django/views/generic/base.py index 7d3649cbfff..c45bc32bf54 100644 --- a/django/views/generic/base.py +++ b/django/views/generic/base.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from functools import update_wrapper from django import http from django.core.exceptions import ImproperlyConfigured @@ -44,11 +46,11 @@ class View(object): # sanitize keyword arguments for key in initkwargs: if key in cls.http_method_names: - raise TypeError(u"You tried to pass in the %s method name as a " - u"keyword argument to %s(). Don't do that." + raise TypeError("You tried to pass in the %s method name as a " + "keyword argument to %s(). Don't do that." % (key, cls.__name__)) if not hasattr(cls, key): - raise TypeError(u"%s() received an invalid keyword %r" % ( + raise TypeError("%s() received an invalid keyword %r" % ( cls.__name__, key)) def view(request, *args, **kwargs): diff --git a/django/views/generic/dates.py b/django/views/generic/dates.py index 3e6ab0fa0ca..26b172231c0 100644 --- a/django/views/generic/dates.py +++ b/django/views/generic/dates.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import datetime from django.conf import settings from django.db import models @@ -34,7 +36,7 @@ class YearMixin(object): try: year = self.request.GET['year'] except KeyError: - raise Http404(_(u"No year specified")) + raise Http404(_("No year specified")) return year def get_next_year(self, date): @@ -87,7 +89,7 @@ class MonthMixin(object): try: month = self.request.GET['month'] except KeyError: - raise Http404(_(u"No month specified")) + raise Http404(_("No month specified")) return month def get_next_month(self, date): @@ -143,7 +145,7 @@ class DayMixin(object): try: day = self.request.GET['day'] except KeyError: - raise Http404(_(u"No day specified")) + raise Http404(_("No day specified")) return day def get_next_day(self, date): @@ -196,7 +198,7 @@ class WeekMixin(object): try: week = self.request.GET['week'] except KeyError: - raise Http404(_(u"No week specified")) + raise Http404(_("No week specified")) return week def get_next_week(self, date): @@ -252,7 +254,7 @@ class DateMixin(object): Get the name of the date field to be used to filter by. """ if self.date_field is None: - raise ImproperlyConfigured(u"%s.date_field is required." % self.__class__.__name__) + raise ImproperlyConfigured("%s.date_field is required." % self.__class__.__name__) return self.date_field def get_allow_future(self): @@ -350,7 +352,7 @@ class BaseDateListView(MultipleObjectMixin, DateMixin, View): # than to load the unpaginated queryset in memory. is_empty = len(qs) == 0 if paginate_by is None else not qs.exists() if is_empty: - raise Http404(_(u"No %(verbose_name_plural)s available") % { + raise Http404(_("No %(verbose_name_plural)s available") % { 'verbose_name_plural': force_unicode(qs.model._meta.verbose_name_plural) }) @@ -367,7 +369,7 @@ class BaseDateListView(MultipleObjectMixin, DateMixin, View): date_list = queryset.dates(date_field, date_type)[::-1] if date_list is not None and not date_list and not allow_empty: name = force_unicode(queryset.model._meta.verbose_name_plural) - raise Http404(_(u"No %(verbose_name_plural)s available") % + raise Http404(_("No %(verbose_name_plural)s available") % {'verbose_name_plural': name}) return date_list @@ -617,7 +619,7 @@ class BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailV qs = queryset or self.get_queryset() if not self.get_allow_future() and date > datetime.date.today(): - raise Http404(_(u"Future %(verbose_name_plural)s not available because %(class_name)s.allow_future is False.") % { + raise Http404(_("Future %(verbose_name_plural)s not available because %(class_name)s.allow_future is False.") % { 'verbose_name_plural': qs.model._meta.verbose_name_plural, 'class_name': self.__class__.__name__, }) @@ -649,7 +651,7 @@ def _date_from_string(year, year_format, month='', month_format='', day='', day_ try: return datetime.datetime.strptime(datestr, format).date() except ValueError: - raise Http404(_(u"Invalid date string '%(datestr)s' given format '%(format)s'") % { + raise Http404(_("Invalid date string '%(datestr)s' given format '%(format)s'") % { 'datestr': datestr, 'format': format, }) diff --git a/django/views/generic/detail.py b/django/views/generic/detail.py index 4b5281745e0..8cc413aa650 100644 --- a/django/views/generic/detail.py +++ b/django/views/generic/detail.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist from django.http import Http404 from django.utils.translation import ugettext as _ @@ -40,14 +42,14 @@ class SingleObjectMixin(ContextMixin): # If none of those are defined, it's an error. else: - raise AttributeError(u"Generic detail view %s must be called with " - u"either an object pk or a slug." + raise AttributeError("Generic detail view %s must be called with " + "either an object pk or a slug." % self.__class__.__name__) try: obj = queryset.get() except ObjectDoesNotExist: - raise Http404(_(u"No %(verbose_name)s found matching the query") % + raise Http404(_("No %(verbose_name)s found matching the query") % {'verbose_name': queryset.model._meta.verbose_name}) return obj @@ -60,9 +62,9 @@ class SingleObjectMixin(ContextMixin): if self.model: return self.model._default_manager.all() else: - raise ImproperlyConfigured(u"%(cls)s is missing a queryset. Define " - u"%(cls)s.model, %(cls)s.queryset, or override " - u"%(cls)s.get_object()." % { + raise ImproperlyConfigured("%(cls)s is missing a queryset. Define " + "%(cls)s.model, %(cls)s.queryset, or override " + "%(cls)s.get_object()." % { 'cls': self.__class__.__name__ }) return self.queryset._clone() diff --git a/django/views/generic/list.py b/django/views/generic/list.py index ae45fd2218c..2e852699d54 100644 --- a/django/views/generic/list.py +++ b/django/views/generic/list.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.core.paginator import Paginator, InvalidPage from django.core.exceptions import ImproperlyConfigured from django.http import Http404 @@ -25,7 +27,7 @@ class MultipleObjectMixin(ContextMixin): elif self.model is not None: queryset = self.model._default_manager.all() else: - raise ImproperlyConfigured(u"'%s' must define 'queryset' or 'model'" + raise ImproperlyConfigured("'%s' must define 'queryset' or 'model'" % self.__class__.__name__) return queryset @@ -41,12 +43,12 @@ class MultipleObjectMixin(ContextMixin): if page == 'last': page_number = paginator.num_pages else: - raise Http404(_(u"Page is not 'last', nor can it be converted to an int.")) + raise Http404(_("Page is not 'last', nor can it be converted to an int.")) try: page = paginator.page(page_number) return (paginator, page, page.object_list, page.has_other_pages()) except InvalidPage: - raise Http404(_(u'Invalid page (%(page_number)s)') % { + raise Http404(_('Invalid page (%(page_number)s)') % { 'page_number': page_number }) @@ -123,7 +125,7 @@ class BaseListView(MultipleObjectMixin, View): else: is_empty = len(self.object_list) == 0 if is_empty: - raise Http404(_(u"Empty list and '%(class_name)s.allow_empty' is False.") + raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.") % {'class_name': self.__class__.__name__}) context = self.get_context_data(object_list=self.object_list) return self.render_to_response(context) diff --git a/django/views/static.py b/django/views/static.py index 2a756134a6c..1d7891e3f48 100644 --- a/django/views/static.py +++ b/django/views/static.py @@ -2,6 +2,7 @@ Views and functions for serving static files. These are only to be used during development, and SHOULD NOT be used in a production setting. """ +from __future__ import unicode_literals import mimetypes import os @@ -48,9 +49,9 @@ def serve(request, path, document_root=None, show_indexes=False): if os.path.isdir(fullpath): if show_indexes: return directory_index(newpath, fullpath) - raise Http404(_(u"Directory indexes are not allowed here.")) + raise Http404(_("Directory indexes are not allowed here.")) if not os.path.exists(fullpath): - raise Http404(_(u'"%(path)s" does not exist') % {'path': fullpath}) + raise Http404(_('"%(path)s" does not exist') % {'path': fullpath}) # Respect the If-Modified-Since header. statobj = os.stat(fullpath) mimetype, encoding = mimetypes.guess_type(fullpath) @@ -91,7 +92,7 @@ DEFAULT_DIRECTORY_INDEX_TEMPLATE = """ """ -template_translatable = ugettext_noop(u"Index of %(directory)s") +template_translatable = ugettext_noop("Index of %(directory)s") def directory_index(path, fullpath): try: diff --git a/docs/conf.py b/docs/conf.py index 2aa3a5c641e..659115dfbd8 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -11,6 +11,8 @@ # All configuration values have a default; values that are commented out # serve to show the default. +from __future__ import unicode_literals + import sys import os @@ -197,8 +199,8 @@ modindex_common_prefix = ["django."] # (source start file, target name, title, author, document class [howto/manual]). #latex_documents = [] latex_documents = [ - ('contents', 'django.tex', u'Django Documentation', - u'Django Software Foundation', 'manual'), + ('contents', 'django.tex', 'Django Documentation', + 'Django Software Foundation', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of @@ -237,10 +239,10 @@ man_pages = [ # -- Options for Epub output --------------------------------------------------- # Bibliographic Dublin Core info. -epub_title = u'Django' -epub_author = u'Django Software Foundation' -epub_publisher = u'Django Software Foundation' -epub_copyright = u'2010, Django Software Foundation' +epub_title = 'Django' +epub_author = 'Django Software Foundation' +epub_publisher = 'Django Software Foundation' +epub_copyright = '2010, Django Software Foundation' # The language of the text. It defaults to the language option # or en if the language is not set. diff --git a/docs/ref/files/file.txt b/docs/ref/files/file.txt index 10108d1f4fc..99547f1c9e7 100644 --- a/docs/ref/files/file.txt +++ b/docs/ref/files/file.txt @@ -94,10 +94,11 @@ The ``ContentFile`` Class but unlike :class:`~django.core.files.File` it operates on string content, rather than an actual file. For example:: + from __future__ import unicode_literals from django.core.files.base import ContentFile f1 = ContentFile(b"my string content") - f2 = ContentFile(u"my unicode content encoded as UTF-8".encode('UTF-8')) + f2 = ContentFile("my unicode content encoded as UTF-8".encode('UTF-8')) .. currentmodule:: django.core.files.images diff --git a/docs/ref/forms/fields.txt b/docs/ref/forms/fields.txt index d9bfbc5e452..486d49d7965 100644 --- a/docs/ref/forms/fields.txt +++ b/docs/ref/forms/fields.txt @@ -25,8 +25,6 @@ exception or returns the clean value:: >>> f = forms.EmailField() >>> f.clean('foo@example.com') u'foo@example.com' - >>> f.clean(u'foo@example.com') - u'foo@example.com' >>> f.clean('invalid email address') Traceback (most recent call last): ... diff --git a/docs/ref/forms/validation.txt b/docs/ref/forms/validation.txt index f1642148b5f..f6cdfc81414 100644 --- a/docs/ref/forms/validation.txt +++ b/docs/ref/forms/validation.txt @@ -184,7 +184,7 @@ a look at Django's ``EmailField``:: class EmailField(CharField): default_error_messages = { - 'invalid': _(u'Enter a valid e-mail address.'), + 'invalid': _('Enter a valid e-mail address.'), } default_validators = [validators.validate_email] @@ -197,7 +197,7 @@ on field definition so:: is equivalent to:: email = forms.CharField(validators=[validators.validate_email], - error_messages={'invalid': _(u'Enter a valid e-mail address.')}) + error_messages={'invalid': _('Enter a valid e-mail address.')}) Form field default cleaning diff --git a/docs/ref/unicode.txt b/docs/ref/unicode.txt index 46ce4138a4f..85e48ae15d1 100644 --- a/docs/ref/unicode.txt +++ b/docs/ref/unicode.txt @@ -45,6 +45,28 @@ rendering or anywhere else -- you have two choices for encoding those strings. You can use Unicode strings, or you can use normal strings (sometimes called "bytestrings") that are encoded using UTF-8. +.. versionchanged:: 1.5 + +In Python 3, the logic is reversed, that is normal strings are Unicode, and +when you want to specifically create a bytestring, you have to prefix the +string with a 'b'. As we are doing in Django code from version 1.5, +we recommend that you import ``unicode_literals`` from the __future__ library +in your code. Then, when you specifically want to create a bytestring literal, +prefix the string with 'b'. + +Python 2 legacy:: + + my_string = "This is a bytestring" + my_unicode = u"This is an Unicode string" + +Python 2 with unicode literals or Python 3:: + + from __future__ import unicode_literals + + my_string = b"This is a bytestring" + my_unicode = "This is an Unicode string" + + .. admonition:: Warning A bytestring does not carry any information with it about its encoding. @@ -182,7 +204,7 @@ An example might clarify things here:: >>> urlquote(u'Paris & Orléans') u'Paris%20%26%20Orl%C3%A9ans' - >>> iri_to_uri(u'/favorites/François/%s' % urlquote(u'Paris & Orléans')) + >>> iri_to_uri(u'/favorites/François/%s' % urlquote('Paris & Orléans')) '/favorites/Fran%C3%A7ois/Paris%20%26%20Orl%C3%A9ans' If you look carefully, you can see that the portion that was generated by @@ -268,7 +290,9 @@ You can pass either Unicode strings or UTF-8 bytestrings as arguments to ``filter()`` methods and the like in the database API. The following two querysets are identical:: - qs = People.objects.filter(name__contains=u'Å') + from __future__ import unicode_literals + + qs = People.objects.filter(name__contains='Å') qs = People.objects.filter(name__contains=b'\xc3\x85') # UTF-8 encoding of Å Templates @@ -276,9 +300,10 @@ Templates You can use either Unicode or bytestrings when creating templates manually:: - from django.template import Template - t1 = Template(b'This is a bytestring template.') - t2 = Template(u'This is a Unicode template.') + from __future__ import unicode_literals + from django.template import Template + t1 = Template(b'This is a bytestring template.') + t2 = Template('This is a Unicode template.') But the common case is to read templates from the filesystem, and this creates a slight complication: not all filesystems store their data encoded as UTF-8. @@ -316,14 +341,15 @@ characters. The following code example demonstrates that everything except email addresses can be non-ASCII:: + from __future__ import unicode_literals from django.core.mail import EmailMessage - subject = u'My visit to Sør-Trøndelag' - sender = u'Arnbjörg Ráðormsdóttir ' + subject = 'My visit to Sør-Trøndelag' + sender = 'Arnbjörg Ráðormsdóttir ' recipients = ['Fred %s" % (self.tag, self.staff) + return "%s -> %s" % (self.tag, self.staff) diff --git a/tests/modeltests/distinct_on_fields/tests.py b/tests/modeltests/distinct_on_fields/tests.py index 4d827d15b63..f62a32e58d5 100644 --- a/tests/modeltests/distinct_on_fields/tests.py +++ b/tests/modeltests/distinct_on_fields/tests.py @@ -2,6 +2,7 @@ from __future__ import absolute_import from django.db.models import Max from django.test import TestCase, skipUnlessDBFeature +from django.test.utils import str_prefix from .models import Tag, Celebrity, Fan, Staff, StaffTag @@ -78,7 +79,8 @@ class DistinctOnTests(TestCase): ( (Staff.objects.distinct('id').order_by('id', 'coworkers__name'). values_list('id', 'coworkers__name')), - ["(1, u'p2')", "(2, u'p1')", "(3, u'p1')", "(4, None)"] + [str_prefix("(1, %(_)s'p2')"), str_prefix("(2, %(_)s'p1')"), + str_prefix("(3, %(_)s'p1')"), "(4, None)"] ), ) for qset, expected in qsets: diff --git a/tests/modeltests/expressions/models.py b/tests/modeltests/expressions/models.py index dd504999fff..018a0cf795a 100644 --- a/tests/modeltests/expressions/models.py +++ b/tests/modeltests/expressions/models.py @@ -1,6 +1,7 @@ """ Tests for F() query expression syntax. """ +from __future__ import unicode_literals from django.db import models @@ -10,7 +11,7 @@ class Employee(models.Model): lastname = models.CharField(max_length=50) def __unicode__(self): - return u'%s %s' % (self.firstname, self.lastname) + return '%s %s' % (self.firstname, self.lastname) class Company(models.Model): name = models.CharField(max_length=100) diff --git a/tests/modeltests/expressions/tests.py b/tests/modeltests/expressions/tests.py index 8f4f5461a51..c4e2707109f 100644 --- a/tests/modeltests/expressions/tests.py +++ b/tests/modeltests/expressions/tests.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from django.core.exceptions import FieldError from django.db.models import F @@ -77,17 +77,17 @@ class ExpressionsTests(TestCase): company_query, [ { 'num_chairs': 2302, - 'name': u'Example Inc.', + 'name': 'Example Inc.', 'num_employees': 2300 }, { 'num_chairs': 5, - 'name': u'Foobar Ltd.', + 'name': 'Foobar Ltd.', 'num_employees': 3 }, { 'num_chairs': 34, - 'name': u'Test GmbH', + 'name': 'Test GmbH', 'num_employees': 32 } ], @@ -102,17 +102,17 @@ class ExpressionsTests(TestCase): company_query, [ { 'num_chairs': 6900, - 'name': u'Example Inc.', + 'name': 'Example Inc.', 'num_employees': 2300 }, { 'num_chairs': 9, - 'name': u'Foobar Ltd.', + 'name': 'Foobar Ltd.', 'num_employees': 3 }, { 'num_chairs': 96, - 'name': u'Test GmbH', + 'name': 'Test GmbH', 'num_employees': 32 } ], @@ -127,17 +127,17 @@ class ExpressionsTests(TestCase): company_query, [ { 'num_chairs': 5294600, - 'name': u'Example Inc.', + 'name': 'Example Inc.', 'num_employees': 2300 }, { 'num_chairs': 15, - 'name': u'Foobar Ltd.', + 'name': 'Foobar Ltd.', 'num_employees': 3 }, { 'num_chairs': 1088, - 'name': u'Test GmbH', + 'name': 'Test GmbH', 'num_employees': 32 } ], diff --git a/tests/modeltests/field_subclassing/fields.py b/tests/modeltests/field_subclassing/fields.py index 4d809ba6f88..b9987c0fab2 100644 --- a/tests/modeltests/field_subclassing/fields.py +++ b/tests/modeltests/field_subclassing/fields.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import json from django.db import models @@ -13,7 +15,7 @@ class Small(object): self.first, self.second = first, second def __unicode__(self): - return u'%s%s' % (force_unicode(self.first), force_unicode(self.second)) + return '%s%s' % (force_unicode(self.first), force_unicode(self.second)) def __str__(self): return unicode(self).encode('utf-8') diff --git a/tests/modeltests/files/tests.py b/tests/modeltests/files/tests.py index 837723a0493..3e256f787f4 100644 --- a/tests/modeltests/files/tests.py +++ b/tests/modeltests/files/tests.py @@ -19,7 +19,7 @@ class FileStorageTests(TestCase): shutil.rmtree(temp_storage_location) def test_files(self): - temp_storage.save('tests/default.txt', ContentFile('default content')) + temp_storage.save('tests/default.txt', ContentFile(b'default content')) # Attempting to access a FileField from the class raises a descriptive # error self.assertRaises(AttributeError, lambda: Storage.normal) @@ -30,15 +30,15 @@ class FileStorageTests(TestCase): self.assertRaises(ValueError, lambda: obj1.normal.size) # Saving a file enables full functionality. - obj1.normal.save("django_test.txt", ContentFile("content")) + obj1.normal.save("django_test.txt", ContentFile(b"content")) self.assertEqual(obj1.normal.name, "tests/django_test.txt") self.assertEqual(obj1.normal.size, 7) - self.assertEqual(obj1.normal.read(), "content") + self.assertEqual(obj1.normal.read(), b"content") obj1.normal.close() # File objects can be assigned to FileField attributes, but shouldn't # get committed until the model it's attached to is saved. - obj1.normal = SimpleUploadedFile("assignment.txt", "content") + obj1.normal = SimpleUploadedFile("assignment.txt", b"content") dirs, files = temp_storage.listdir("tests") self.assertEqual(dirs, []) self.assertEqual(sorted(files), ["default.txt", "django_test.txt"]) @@ -51,14 +51,14 @@ class FileStorageTests(TestCase): # Files can be read in a little at a time, if necessary. obj1.normal.open() - self.assertEqual(obj1.normal.read(3), "con") - self.assertEqual(obj1.normal.read(), "tent") - self.assertEqual(list(obj1.normal.chunks(chunk_size=2)), ["co", "nt", "en", "t"]) + self.assertEqual(obj1.normal.read(3), b"con") + self.assertEqual(obj1.normal.read(), b"tent") + self.assertEqual(list(obj1.normal.chunks(chunk_size=2)), [b"co", b"nt", b"en", b"t"]) obj1.normal.close() # Save another file with the same name. obj2 = Storage() - obj2.normal.save("django_test.txt", ContentFile("more content")) + obj2.normal.save("django_test.txt", ContentFile(b"more content")) self.assertEqual(obj2.normal.name, "tests/django_test_1.txt") self.assertEqual(obj2.normal.size, 12) @@ -69,13 +69,13 @@ class FileStorageTests(TestCase): # Deleting an object does not delete the file it uses. obj2.delete() - obj2.normal.save("django_test.txt", ContentFile("more content")) + obj2.normal.save("django_test.txt", ContentFile(b"more content")) self.assertEqual(obj2.normal.name, "tests/django_test_2.txt") # Multiple files with the same name get _N appended to them. objs = [Storage() for i in range(3)] for o in objs: - o.normal.save("multiple_files.txt", ContentFile("Same Content")) + o.normal.save("multiple_files.txt", ContentFile(b"Same Content")) self.assertEqual( [o.normal.name for o in objs], ["tests/multiple_files.txt", "tests/multiple_files_1.txt", "tests/multiple_files_2.txt"] @@ -86,20 +86,20 @@ class FileStorageTests(TestCase): # Default values allow an object to access a single file. obj3 = Storage.objects.create() self.assertEqual(obj3.default.name, "tests/default.txt") - self.assertEqual(obj3.default.read(), "default content") + self.assertEqual(obj3.default.read(), b"default content") obj3.default.close() # But it shouldn't be deleted, even if there are no more objects using # it. obj3.delete() obj3 = Storage() - self.assertEqual(obj3.default.read(), "default content") + self.assertEqual(obj3.default.read(), b"default content") obj3.default.close() # Verify the fix for #5655, making sure the directory is only # determined once. obj4 = Storage() - obj4.random.save("random_file", ContentFile("random content")) + obj4.random.save("random_file", ContentFile(b"random content")) self.assertTrue(obj4.random.name.endswith("/random_file")) # Clean up the temporary files and dir. diff --git a/tests/modeltests/fixtures_model_package/tests.py b/tests/modeltests/fixtures_model_package/tests.py index a415fdf6a7a..17538ed7e81 100644 --- a/tests/modeltests/fixtures_model_package/tests.py +++ b/tests/modeltests/fixtures_model_package/tests.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.core import management from django.db import transaction from django.test import TestCase, TransactionTestCase @@ -13,9 +15,9 @@ class SampleTestCase(TestCase): self.assertEqual(Article.objects.count(), 3) self.assertQuerysetEqual( Article.objects.all(),[ - u"Django conquers world!", - u"Copyright is fine the way it is", - u"Poker has no place on ESPN", + "Django conquers world!", + "Copyright is fine the way it is", + "Poker has no place on ESPN", ], lambda a: a.headline ) @@ -61,7 +63,7 @@ class FixtureTestCase(TestCase): # syncdb introduces 1 initial data object from initial_data.json self.assertQuerysetEqual( Book.objects.all(), [ - u'Achieving self-awareness of Python programs' + 'Achieving self-awareness of Python programs' ], lambda a: a.name ) @@ -72,8 +74,8 @@ class FixtureTestCase(TestCase): management.call_command("loaddata", "fixture1.json", verbosity=0, commit=False) self.assertQuerysetEqual( Article.objects.all(), [ - u"Time to reform copyright", - u"Poker has no place on ESPN", + "Time to reform copyright", + "Poker has no place on ESPN", ], lambda a: a.headline, ) @@ -83,9 +85,9 @@ class FixtureTestCase(TestCase): management.call_command("loaddata", "fixture2.json", verbosity=0, commit=False) self.assertQuerysetEqual( Article.objects.all(), [ - u"Django conquers world!", - u"Copyright is fine the way it is", - u"Poker has no place on ESPN", + "Django conquers world!", + "Copyright is fine the way it is", + "Poker has no place on ESPN", ], lambda a: a.headline, ) @@ -94,9 +96,9 @@ class FixtureTestCase(TestCase): management.call_command("loaddata", "unknown.json", verbosity=0, commit=False) self.assertQuerysetEqual( Article.objects.all(), [ - u"Django conquers world!", - u"Copyright is fine the way it is", - u"Poker has no place on ESPN", + "Django conquers world!", + "Copyright is fine the way it is", + "Poker has no place on ESPN", ], lambda a: a.headline, ) diff --git a/tests/modeltests/generic_relations/models.py b/tests/modeltests/generic_relations/models.py index f3e216edf59..f2dcf7db242 100644 --- a/tests/modeltests/generic_relations/models.py +++ b/tests/modeltests/generic_relations/models.py @@ -9,6 +9,8 @@ The canonical example is tags (although this example implementation is *far* from complete). """ +from __future__ import unicode_literals + from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.db import models @@ -47,7 +49,7 @@ class Comparison(models.Model): other_obj = generic.GenericForeignKey(ct_field="content_type2", fk_field="object_id2") def __unicode__(self): - return u"%s is %s than %s" % (self.first_obj, self.comparative, self.other_obj) + return "%s is %s than %s" % (self.first_obj, self.comparative, self.other_obj) class Animal(models.Model): common_name = models.CharField(max_length=150) diff --git a/tests/modeltests/generic_relations/tests.py b/tests/modeltests/generic_relations/tests.py index 0ac552cf770..d3de71d9170 100644 --- a/tests/modeltests/generic_relations/tests.py +++ b/tests/modeltests/generic_relations/tests.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from django import forms from django.contrib.contenttypes.generic import generic_inlineformset_factory @@ -90,23 +90,23 @@ class GenericRelationsTests(TestCase): ) self.assertQuerysetEqual(TaggedItem.objects.all(), [ - (u'clearish', Mineral, quartz.pk), - (u'fatty', Animal, platypus.pk), - (u'fatty', Vegetable, bacon.pk), - (u'hairy', Animal, lion.pk), - (u'salty', Vegetable, bacon.pk), - (u'shiny', Animal, platypus.pk), - (u'yellow', Animal, lion.pk) + ('clearish', Mineral, quartz.pk), + ('fatty', Animal, platypus.pk), + ('fatty', Vegetable, bacon.pk), + ('hairy', Animal, lion.pk), + ('salty', Vegetable, bacon.pk), + ('shiny', Animal, platypus.pk), + ('yellow', Animal, lion.pk) ], comp_func ) lion.delete() self.assertQuerysetEqual(TaggedItem.objects.all(), [ - (u'clearish', Mineral, quartz.pk), - (u'fatty', Animal, platypus.pk), - (u'fatty', Vegetable, bacon.pk), - (u'salty', Vegetable, bacon.pk), - (u'shiny', Animal, platypus.pk) + ('clearish', Mineral, quartz.pk), + ('fatty', Animal, platypus.pk), + ('fatty', Vegetable, bacon.pk), + ('salty', Vegetable, bacon.pk), + ('shiny', Animal, platypus.pk) ], comp_func ) @@ -116,11 +116,11 @@ class GenericRelationsTests(TestCase): quartz_pk = quartz.pk quartz.delete() self.assertQuerysetEqual(TaggedItem.objects.all(), [ - (u'clearish', Mineral, quartz_pk), - (u'fatty', Animal, platypus.pk), - (u'fatty', Vegetable, bacon.pk), - (u'salty', Vegetable, bacon.pk), - (u'shiny', Animal, platypus.pk) + ('clearish', Mineral, quartz_pk), + ('fatty', Animal, platypus.pk), + ('fatty', Vegetable, bacon.pk), + ('salty', Vegetable, bacon.pk), + ('shiny', Animal, platypus.pk) ], comp_func ) @@ -130,10 +130,10 @@ class GenericRelationsTests(TestCase): tag.delete() self.assertQuerysetEqual(bacon.tags.all(), [""]) self.assertQuerysetEqual(TaggedItem.objects.all(), [ - (u'clearish', Mineral, quartz_pk), - (u'fatty', Animal, platypus.pk), - (u'salty', Vegetable, bacon.pk), - (u'shiny', Animal, platypus.pk) + ('clearish', Mineral, quartz_pk), + ('fatty', Animal, platypus.pk), + ('salty', Vegetable, bacon.pk), + ('shiny', Animal, platypus.pk) ], comp_func ) @@ -200,11 +200,11 @@ class GenericRelationsTests(TestCase): def test_generic_inline_formsets(self): GenericFormSet = generic_inlineformset_factory(TaggedItem, extra=1) formset = GenericFormSet() - self.assertHTMLEqual(u''.join(form.as_p() for form in formset.forms), u"""

        + self.assertHTMLEqual(''.join(form.as_p() for form in formset.forms), """

        """) formset = GenericFormSet(instance=Animal()) - self.assertHTMLEqual(u''.join(form.as_p() for form in formset.forms), u"""

        + self.assertHTMLEqual(''.join(form.as_p() for form in formset.forms), """

        """) platypus = Animal.objects.create( @@ -216,13 +216,13 @@ class GenericRelationsTests(TestCase): tagged_item_id = TaggedItem.objects.get( tag='shiny', object_id=platypus.id ).id - self.assertHTMLEqual(u''.join(form.as_p() for form in formset.forms), u"""

        + self.assertHTMLEqual(''.join(form.as_p() for form in formset.forms), """

        """ % tagged_item_id) lion = Animal.objects.create(common_name="Lion", latin_name="Panthera leo") formset = GenericFormSet(instance=lion, prefix='x') - self.assertHTMLEqual(u''.join(form.as_p() for form in formset.forms), u"""

        + self.assertHTMLEqual(''.join(form.as_p() for form in formset.forms), """

        """) def test_gfk_manager(self): diff --git a/tests/modeltests/get_or_create/models.py b/tests/modeltests/get_or_create/models.py index 1de5a6ecec9..78b92f09df8 100644 --- a/tests/modeltests/get_or_create/models.py +++ b/tests/modeltests/get_or_create/models.py @@ -6,6 +6,8 @@ given parameters. If an object isn't found, it creates one with the given parameters. """ +from __future__ import unicode_literals + from django.db import models @@ -15,7 +17,7 @@ class Person(models.Model): birthday = models.DateField() def __unicode__(self): - return u'%s %s' % (self.first_name, self.last_name) + return '%s %s' % (self.first_name, self.last_name) class ManualPrimaryKeyTest(models.Model): id = models.IntegerField(primary_key=True) diff --git a/tests/modeltests/invalid_models/invalid_models/models.py b/tests/modeltests/invalid_models/invalid_models/models.py index ed69fb60ee1..b2ba253c5d8 100644 --- a/tests/modeltests/invalid_models/invalid_models/models.py +++ b/tests/modeltests/invalid_models/invalid_models/models.py @@ -5,6 +5,8 @@ This example exists purely to point out errors in models. """ +from __future__ import unicode_literals + from django.db import connection, models @@ -223,12 +225,12 @@ class InvalidSetDefault(models.Model): class UnicodeForeignKeys(models.Model): """Foreign keys which can translate to ascii should be OK, but fail if they're not.""" - good = models.ForeignKey(u'FKTarget') - also_good = models.ManyToManyField(u'FKTarget', related_name='unicode2') + good = models.ForeignKey('FKTarget') + also_good = models.ManyToManyField('FKTarget', related_name='unicode2') # In Python 3 this should become legal, but currently causes unicode errors # when adding the errors in core/management/validation.py - #bad = models.ForeignKey(u'★') + #bad = models.ForeignKey('★') class PrimaryKeyNull(models.Model): my_pk_field = models.IntegerField(primary_key=True, null=True) diff --git a/tests/modeltests/lookup/models.py b/tests/modeltests/lookup/models.py index bcdd3d7c68d..3e5d61538a0 100644 --- a/tests/modeltests/lookup/models.py +++ b/tests/modeltests/lookup/models.py @@ -4,6 +4,8 @@ This demonstrates features of the database API. """ +from __future__ import unicode_literals + from django.db import models @@ -41,11 +43,11 @@ class Game(models.Model): away = models.CharField(max_length=100) def __unicode__(self): - return u"%s at %s" % (self.away, self.home) + return "%s at %s" % (self.away, self.home) class Player(models.Model): name = models.CharField(max_length=100) games = models.ManyToManyField(Game, related_name='players') def __unicode__(self): - return self.name \ No newline at end of file + return self.name diff --git a/tests/modeltests/lookup/tests.py b/tests/modeltests/lookup/tests.py index 502e0d5f2b8..98358e3d10e 100644 --- a/tests/modeltests/lookup/tests.py +++ b/tests/modeltests/lookup/tests.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from datetime import datetime from operator import attrgetter @@ -128,13 +128,13 @@ class LookupTests(TestCase): identity = lambda x:x self.assertQuerysetEqual(Article.objects.values('headline'), [ - {'headline': u'Article 5'}, - {'headline': u'Article 6'}, - {'headline': u'Article 4'}, - {'headline': u'Article 2'}, - {'headline': u'Article 3'}, - {'headline': u'Article 7'}, - {'headline': u'Article 1'}, + {'headline': 'Article 5'}, + {'headline': 'Article 6'}, + {'headline': 'Article 4'}, + {'headline': 'Article 2'}, + {'headline': 'Article 3'}, + {'headline': 'Article 7'}, + {'headline': 'Article 1'}, ], transform=identity) self.assertQuerysetEqual( @@ -156,13 +156,13 @@ class LookupTests(TestCase): # because iterator() uses database-level iteration. self.assertQuerysetEqual(Article.objects.values('id', 'headline').iterator(), [ - {'headline': u'Article 5', 'id': self.a5.id}, - {'headline': u'Article 6', 'id': self.a6.id}, - {'headline': u'Article 4', 'id': self.a4.id}, - {'headline': u'Article 2', 'id': self.a2.id}, - {'headline': u'Article 3', 'id': self.a3.id}, - {'headline': u'Article 7', 'id': self.a7.id}, - {'headline': u'Article 1', 'id': self.a1.id}, + {'headline': 'Article 5', 'id': self.a5.id}, + {'headline': 'Article 6', 'id': self.a6.id}, + {'headline': 'Article 4', 'id': self.a4.id}, + {'headline': 'Article 2', 'id': self.a2.id}, + {'headline': 'Article 3', 'id': self.a3.id}, + {'headline': 'Article 7', 'id': self.a7.id}, + {'headline': 'Article 1', 'id': self.a1.id}, ], transform=identity) # The values() method works with "extra" fields specified in extra(select). @@ -259,13 +259,13 @@ class LookupTests(TestCase): identity = lambda x:x self.assertQuerysetEqual(Article.objects.values_list('headline'), [ - (u'Article 5',), - (u'Article 6',), - (u'Article 4',), - (u'Article 2',), - (u'Article 3',), - (u'Article 7',), - (u'Article 1',), + ('Article 5',), + ('Article 6',), + ('Article 4',), + ('Article 2',), + ('Article 3',), + ('Article 7',), + ('Article 1',), ], transform=identity) self.assertQuerysetEqual(Article.objects.values_list('id').order_by('id'), [(self.a1.id,), (self.a2.id,), (self.a3.id,), (self.a4.id,), (self.a5.id,), (self.a6.id,), (self.a7.id,)], diff --git a/tests/modeltests/m2m_and_m2o/models.py b/tests/modeltests/m2m_and_m2o/models.py index 9368398f718..6c1f2778114 100644 --- a/tests/modeltests/m2m_and_m2o/models.py +++ b/tests/modeltests/m2m_and_m2o/models.py @@ -3,6 +3,7 @@ Make sure to set ``related_name`` if you use relationships to the same table. """ +from __future__ import unicode_literals from django.db import models @@ -22,5 +23,5 @@ class Issue(models.Model): ordering = ('num',) class UnicodeReferenceModel(models.Model): - others = models.ManyToManyField(u"UnicodeReferenceModel") + others = models.ManyToManyField("UnicodeReferenceModel") diff --git a/tests/modeltests/m2m_intermediary/models.py b/tests/modeltests/m2m_intermediary/models.py index ea9b83ea145..85786e8458e 100644 --- a/tests/modeltests/m2m_intermediary/models.py +++ b/tests/modeltests/m2m_intermediary/models.py @@ -9,6 +9,7 @@ each ``Article``-``Reporter`` combination (a ``Writer``) has a ``position`` field, which specifies the ``Reporter``'s position for the given article (e.g. "Staff writer"). """ +from __future__ import unicode_literals from django.db import models @@ -18,7 +19,7 @@ class Reporter(models.Model): last_name = models.CharField(max_length=30) def __unicode__(self): - return u"%s %s" % (self.first_name, self.last_name) + return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) @@ -33,5 +34,5 @@ class Writer(models.Model): position = models.CharField(max_length=100) def __unicode__(self): - return u'%s (%s)' % (self.reporter, self.position) + return '%s (%s)' % (self.reporter, self.position) diff --git a/tests/modeltests/m2m_through/tests.py b/tests/modeltests/m2m_through/tests.py index 94be628a421..259dc68a0b2 100644 --- a/tests/modeltests/m2m_through/tests.py +++ b/tests/modeltests/m2m_through/tests.py @@ -333,7 +333,7 @@ class M2mThroughTests(TestCase): # Jim showed up twice, because he joined two groups ('Rock', and 'Roll'): self.assertEqual( [(m.person.name, m.group.name) for m in Membership.objects.filter(date_joined__gt=datetime(2004, 1, 1))], - [(u'Jane', u'Rock'), (u'Jim', u'Rock'), (u'Jim', u'Roll')] + [('Jane', 'Rock'), ('Jim', 'Rock'), ('Jim', 'Roll')] ) # QuerySet's distinct() method can correct this problem. self.assertQuerysetEqual( diff --git a/tests/modeltests/many_to_one/models.py b/tests/modeltests/many_to_one/models.py index 1e4afcf22f3..0d2688e8a45 100644 --- a/tests/modeltests/many_to_one/models.py +++ b/tests/modeltests/many_to_one/models.py @@ -3,6 +3,7 @@ To define a many-to-one relationship, use ``ForeignKey()``. """ +from __future__ import unicode_literals from django.db import models @@ -13,7 +14,7 @@ class Reporter(models.Model): email = models.EmailField() def __unicode__(self): - return u"%s %s" % (self.first_name, self.last_name) + return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) diff --git a/tests/modeltests/many_to_one/tests.py b/tests/modeltests/many_to_one/tests.py index aed952fe2fc..257025583bf 100644 --- a/tests/modeltests/many_to_one/tests.py +++ b/tests/modeltests/many_to_one/tests.py @@ -177,7 +177,7 @@ class ManyToOneTests(TestCase): # ... and should work fine with the unicode that comes out of forms.Form.cleaned_data self.assertQuerysetEqual( Article.objects.filter(reporter__first_name__exact='John' - ).extra(where=["many_to_one_reporter.last_name='%s'" % u'Smith']), + ).extra(where=["many_to_one_reporter.last_name='%s'" % 'Smith']), [ "", "", @@ -300,7 +300,7 @@ class ManyToOneTests(TestCase): # It's possible to use values() calls across many-to-one relations. # (Note, too, that we clear the ordering here so as not to drag the # 'headline' field into the columns being used to determine uniqueness) - d = {'reporter__first_name': u'John', 'reporter__last_name': u'Smith'} + d = {'reporter__first_name': 'John', 'reporter__last_name': 'Smith'} self.assertEqual([d], list(Article.objects.filter(reporter=self.r).distinct().order_by() .values('reporter__first_name', 'reporter__last_name'))) @@ -418,7 +418,7 @@ class ManyToOneTests(TestCase): reporter = Reporter.objects.create(first_name='John', last_name='Smith', email='john.smith@example.com') - lazy = ugettext_lazy(u'test') + lazy = ugettext_lazy('test') reporter.article_set.create(headline=lazy, pub_date=datetime(2011, 6, 10)) notlazy = unicode(lazy) diff --git a/tests/modeltests/model_forms/models.py b/tests/modeltests/model_forms/models.py index 35fc9a7bc1a..a4ce86f1848 100644 --- a/tests/modeltests/model_forms/models.py +++ b/tests/modeltests/model_forms/models.py @@ -6,6 +6,7 @@ tests to use ``ModelForm``. As such, the text may not make sense in all cases, and the examples are probably a poor fit for the ``ModelForm`` syntax. In other words, most of these tests should be rewritten. """ +from __future__ import unicode_literals import os import tempfile @@ -161,7 +162,7 @@ class Price(models.Model): quantity = models.PositiveIntegerField() def __unicode__(self): - return u"%s for %s" % (self.quantity, self.price) + return "%s for %s" % (self.quantity, self.price) class Meta: unique_together = (('price', 'quantity'),) diff --git a/tests/modeltests/model_forms/tests.py b/tests/modeltests/model_forms/tests.py index af8bcbca4e5..281316a28e3 100644 --- a/tests/modeltests/model_forms/tests.py +++ b/tests/modeltests/model_forms/tests.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import datetime import os @@ -408,7 +408,7 @@ class UniqueTest(TestCase): obj = form.save() form = ProductForm({'slug': 'teddy-bear-blue'}) self.assertEqual(len(form.errors), 1) - self.assertEqual(form.errors['slug'], [u'Product with this Slug already exists.']) + self.assertEqual(form.errors['slug'], ['Product with this Slug already exists.']) form = ProductForm({'slug': 'teddy-bear-blue'}, instance=obj) self.assertTrue(form.is_valid()) @@ -420,7 +420,7 @@ class UniqueTest(TestCase): form = PriceForm({'price': '6.00', 'quantity': '1'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) - self.assertEqual(form.errors['__all__'], [u'Price with this Price and Quantity already exists.']) + self.assertEqual(form.errors['__all__'], ['Price with this Price and Quantity already exists.']) def test_unique_null(self): title = 'I May Be Wrong But I Doubt It' @@ -430,7 +430,7 @@ class UniqueTest(TestCase): form = BookForm({'title': title, 'author': self.writer.pk}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) - self.assertEqual(form.errors['__all__'], [u'Book with this Title and Author already exists.']) + self.assertEqual(form.errors['__all__'], ['Book with this Title and Author already exists.']) form = BookForm({'title': title}) self.assertTrue(form.is_valid()) form.save() @@ -440,10 +440,10 @@ class UniqueTest(TestCase): def test_inherited_unique(self): title = 'Boss' Book.objects.create(title=title, author=self.writer, special_id=1) - form = DerivedBookForm({'title': 'Other', 'author': self.writer.pk, 'special_id': u'1', 'isbn': '12345'}) + form = DerivedBookForm({'title': 'Other', 'author': self.writer.pk, 'special_id': '1', 'isbn': '12345'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) - self.assertEqual(form.errors['special_id'], [u'Book with this Special id already exists.']) + self.assertEqual(form.errors['special_id'], ['Book with this Special id already exists.']) def test_inherited_unique_together(self): title = 'Boss' @@ -453,7 +453,7 @@ class UniqueTest(TestCase): form = DerivedBookForm({'title': title, 'author': self.writer.pk, 'isbn': '12345'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) - self.assertEqual(form.errors['__all__'], [u'Book with this Title and Author already exists.']) + self.assertEqual(form.errors['__all__'], ['Book with this Title and Author already exists.']) def test_abstract_inherited_unique(self): title = 'Boss' @@ -462,7 +462,7 @@ class UniqueTest(TestCase): form = DerivedBookForm({'title': 'Other', 'author': self.writer.pk, 'isbn': isbn}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) - self.assertEqual(form.errors['isbn'], [u'Derived book with this Isbn already exists.']) + self.assertEqual(form.errors['isbn'], ['Derived book with this Isbn already exists.']) def test_abstract_inherited_unique_together(self): title = 'Boss' @@ -472,30 +472,30 @@ class UniqueTest(TestCase): 'title': 'Other', 'author': self.writer.pk, 'isbn': '9876', - 'suffix1': u'0', - 'suffix2': u'0' + 'suffix1': '0', + 'suffix2': '0' }) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['__all__'], - [u'Derived book with this Suffix1 and Suffix2 already exists.']) + ['Derived book with this Suffix1 and Suffix2 already exists.']) def test_explicitpk_unspecified(self): """Test for primary_key being in the form and failing validation.""" - form = ExplicitPKForm({'key': u'', 'desc': u'' }) + form = ExplicitPKForm({'key': '', 'desc': '' }) self.assertFalse(form.is_valid()) def test_explicitpk_unique(self): """Ensure keys and blank character strings are tested for uniqueness.""" - form = ExplicitPKForm({'key': u'key1', 'desc': u''}) + form = ExplicitPKForm({'key': 'key1', 'desc': ''}) self.assertTrue(form.is_valid()) form.save() - form = ExplicitPKForm({'key': u'key1', 'desc': u''}) + form = ExplicitPKForm({'key': 'key1', 'desc': ''}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 3) - self.assertEqual(form.errors['__all__'], [u'Explicit pk with this Key and Desc already exists.']) - self.assertEqual(form.errors['desc'], [u'Explicit pk with this Desc already exists.']) - self.assertEqual(form.errors['key'], [u'Explicit pk with this Key already exists.']) + self.assertEqual(form.errors['__all__'], ['Explicit pk with this Key and Desc already exists.']) + self.assertEqual(form.errors['desc'], ['Explicit pk with this Desc already exists.']) + self.assertEqual(form.errors['key'], ['Explicit pk with this Key already exists.']) def test_unique_for_date(self): p = Post.objects.create(title="Django 1.0 is released", @@ -503,7 +503,7 @@ class UniqueTest(TestCase): form = PostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) - self.assertEqual(form.errors['title'], [u'Title must be unique for Posted date.']) + self.assertEqual(form.errors['title'], ['Title must be unique for Posted date.']) form = PostForm({'title': "Work on Django 1.1 begins", 'posted': '2008-09-03'}) self.assertTrue(form.is_valid()) form = PostForm({'title': "Django 1.0 is released", 'posted': '2008-09-04'}) @@ -511,17 +511,17 @@ class UniqueTest(TestCase): form = PostForm({'slug': "Django 1.0", 'posted': '2008-01-01'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) - self.assertEqual(form.errors['slug'], [u'Slug must be unique for Posted year.']) + self.assertEqual(form.errors['slug'], ['Slug must be unique for Posted year.']) form = PostForm({'subtitle': "Finally", 'posted': '2008-09-30'}) self.assertFalse(form.is_valid()) - self.assertEqual(form.errors['subtitle'], [u'Subtitle must be unique for Posted month.']) + self.assertEqual(form.errors['subtitle'], ['Subtitle must be unique for Posted month.']) form = PostForm({'subtitle': "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0", 'posted': '2008-09-03'}, instance=p) self.assertTrue(form.is_valid()) form = PostForm({'title': "Django 1.0 is released"}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) - self.assertEqual(form.errors['posted'], [u'This field is required.']) + self.assertEqual(form.errors['posted'], ['This field is required.']) def test_inherited_unique_for_date(self): p = Post.objects.create(title="Django 1.0 is released", @@ -529,7 +529,7 @@ class UniqueTest(TestCase): form = DerivedPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) - self.assertEqual(form.errors['title'], [u'Title must be unique for Posted date.']) + self.assertEqual(form.errors['title'], ['Title must be unique for Posted date.']) form = DerivedPostForm({'title': "Work on Django 1.1 begins", 'posted': '2008-09-03'}) self.assertTrue(form.is_valid()) form = DerivedPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-04'}) @@ -537,10 +537,10 @@ class UniqueTest(TestCase): form = DerivedPostForm({'slug': "Django 1.0", 'posted': '2008-01-01'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) - self.assertEqual(form.errors['slug'], [u'Slug must be unique for Posted year.']) + self.assertEqual(form.errors['slug'], ['Slug must be unique for Posted year.']) form = DerivedPostForm({'subtitle': "Finally", 'posted': '2008-09-30'}) self.assertFalse(form.is_valid()) - self.assertEqual(form.errors['subtitle'], [u'Subtitle must be unique for Posted month.']) + self.assertEqual(form.errors['subtitle'], ['Subtitle must be unique for Posted month.']) form = DerivedPostForm({'subtitle': "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0", 'posted': '2008-09-03'}, instance=p) self.assertTrue(form.is_valid()) @@ -624,9 +624,9 @@ class OldFormForXTests(TestCase): # save() on the resulting model instance. f = BaseCategoryForm({'name': 'Third test', 'slug': 'third-test', 'url': 'third'}) self.assertEqual(f.is_valid(), True) - self.assertEqual(f.cleaned_data['url'], u'third') - self.assertEqual(f.cleaned_data['name'], u'Third test') - self.assertEqual(f.cleaned_data['slug'], u'third-test') + self.assertEqual(f.cleaned_data['url'], 'third') + self.assertEqual(f.cleaned_data['name'], 'Third test') + self.assertEqual(f.cleaned_data['slug'], 'third-test') c3 = f.save(commit=False) self.assertEqual(c3.name, "Third test") self.assertEqual(Category.objects.count(), 2) @@ -635,8 +635,8 @@ class OldFormForXTests(TestCase): # If you call save() with invalid data, you'll get a ValueError. f = BaseCategoryForm({'name': '', 'slug': 'not a slug!', 'url': 'foo'}) - self.assertEqual(f.errors['name'], [u'This field is required.']) - self.assertEqual(f.errors['slug'], [u"Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."]) + self.assertEqual(f.errors['name'], ['This field is required.']) + self.assertEqual(f.errors['slug'], ["Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."]) with self.assertRaises(AttributeError): f.cleaned_data with self.assertRaises(ValueError): @@ -722,9 +722,9 @@ class OldFormForXTests(TestCase):
      • ''' % (w_woodward.pk, w_royko.pk, c1.pk, c2.pk, c3.pk)) f = TestArticleForm({ - 'headline': u'Test headline', + 'headline': 'Test headline', 'slug': 'test-headline', - 'pub_date': u'1984-02-06', + 'pub_date': '1984-02-06', 'writer': unicode(w_royko.pk), 'article': 'Hello.' }, instance=art) @@ -733,13 +733,13 @@ class OldFormForXTests(TestCase): test_art = f.save() self.assertEqual(test_art.id == art_id_1, True) test_art = Article.objects.get(id=art_id_1) - self.assertEqual(test_art.headline, u'Test headline') + self.assertEqual(test_art.headline, 'Test headline') # You can create a form over a subset of the available fields # by specifying a 'fields' argument to form_for_instance. f = PartialArticleFormWithSlug({ - 'headline': u'New headline', + 'headline': 'New headline', 'slug': 'new-headline', - 'pub_date': u'1988-01-04' + 'pub_date': '1988-01-04' }, auto_id=False, instance=art) self.assertHTMLEqual(f.as_ul(), '''
      • Headline:
      • Slug:
      • @@ -748,7 +748,7 @@ class OldFormForXTests(TestCase): new_art = f.save() self.assertEqual(new_art.id == art_id_1, True) new_art = Article.objects.get(id=art_id_1) - self.assertEqual(new_art.headline, u'New headline') + self.assertEqual(new_art.headline, 'New headline') # Add some categories and test the many-to-many form output. self.assertEqual(map(lambda o: o.name, new_art.categories.all()), []) @@ -805,11 +805,11 @@ class OldFormForXTests(TestCase): ''' % (w_woodward.pk, w_royko.pk, c1.pk, c2.pk, c3.pk)) f = TestArticleForm({ - 'headline': u'New headline', - 'slug': u'new-headline', - 'pub_date': u'1988-01-04', + 'headline': 'New headline', + 'slug': 'new-headline', + 'pub_date': '1988-01-04', 'writer': unicode(w_royko.pk), - 'article': u'Hello.', + 'article': 'Hello.', 'categories': [unicode(c1.id), unicode(c2.id)] }, instance=new_art) new_art = f.save() @@ -819,16 +819,16 @@ class OldFormForXTests(TestCase): ["Entertainment", "It's a test"]) # Now, submit form data with no categories. This deletes the existing categories. - f = TestArticleForm({'headline': u'New headline', 'slug': u'new-headline', 'pub_date': u'1988-01-04', - 'writer': unicode(w_royko.pk), 'article': u'Hello.'}, instance=new_art) + f = TestArticleForm({'headline': 'New headline', 'slug': 'new-headline', 'pub_date': '1988-01-04', + 'writer': unicode(w_royko.pk), 'article': 'Hello.'}, instance=new_art) new_art = f.save() self.assertEqual(new_art.id == art_id_1, True) new_art = Article.objects.get(id=art_id_1) self.assertEqual(map(lambda o: o.name, new_art.categories.all()), []) # Create a new article, with categories, via the form. - f = ArticleForm({'headline': u'The walrus was Paul', 'slug': u'walrus-was-paul', 'pub_date': u'1967-11-01', - 'writer': unicode(w_royko.pk), 'article': u'Test.', 'categories': [unicode(c1.id), unicode(c2.id)]}) + f = ArticleForm({'headline': 'The walrus was Paul', 'slug': 'walrus-was-paul', 'pub_date': '1967-11-01', + 'writer': unicode(w_royko.pk), 'article': 'Test.', 'categories': [unicode(c1.id), unicode(c2.id)]}) new_art = f.save() art_id_2 = new_art.id self.assertEqual(art_id_2 not in (None, art_id_1), True) @@ -836,8 +836,8 @@ class OldFormForXTests(TestCase): self.assertEqual(map(lambda o: o.name, new_art.categories.order_by('name')), ["Entertainment", "It's a test"]) # Create a new article, with no categories, via the form. - f = ArticleForm({'headline': u'The walrus was Paul', 'slug': u'walrus-was-paul', 'pub_date': u'1967-11-01', - 'writer': unicode(w_royko.pk), 'article': u'Test.'}) + f = ArticleForm({'headline': 'The walrus was Paul', 'slug': 'walrus-was-paul', 'pub_date': '1967-11-01', + 'writer': unicode(w_royko.pk), 'article': 'Test.'}) new_art = f.save() art_id_3 = new_art.id self.assertEqual(art_id_3 not in (None, art_id_1, art_id_2), True) @@ -846,8 +846,8 @@ class OldFormForXTests(TestCase): # Create a new article, with categories, via the form, but use commit=False. # The m2m data won't be saved until save_m2m() is invoked on the form. - f = ArticleForm({'headline': u'The walrus was Paul', 'slug': 'walrus-was-paul', 'pub_date': u'1967-11-01', - 'writer': unicode(w_royko.pk), 'article': u'Test.', 'categories': [unicode(c1.id), unicode(c2.id)]}) + f = ArticleForm({'headline': 'The walrus was Paul', 'slug': 'walrus-was-paul', 'pub_date': '1967-11-01', + 'writer': unicode(w_royko.pk), 'article': 'Test.', 'categories': [unicode(c1.id), unicode(c2.id)]}) new_art = f.save(commit=False) # Manually save the instance @@ -929,11 +929,11 @@ class OldFormForXTests(TestCase): f = forms.ModelChoiceField(Category.objects.all()) self.assertEqual(list(f.choices), [ - (u'', u'---------'), - (c1.pk, u'Entertainment'), - (c2.pk, u"It's a test"), - (c3.pk, u'Third'), - (c4.pk, u'Fourth')]) + ('', '---------'), + (c1.pk, 'Entertainment'), + (c2.pk, "It's a test"), + (c3.pk, 'Third'), + (c4.pk, 'Fourth')]) with self.assertRaises(ValidationError): f.clean('') with self.assertRaises(ValidationError): @@ -967,10 +967,10 @@ class OldFormForXTests(TestCase): # queryset can be changed after the field is created. f.queryset = Category.objects.exclude(name='Fourth') self.assertEqual(list(f.choices), [ - (u'', u'---------'), - (c1.pk, u'Entertainment'), - (c2.pk, u"It's a test"), - (c3.pk, u'Third')]) + ('', '---------'), + (c1.pk, 'Entertainment'), + (c2.pk, "It's a test"), + (c3.pk, 'Third')]) self.assertEqual(f.clean(c3.id).name, 'Third') with self.assertRaises(ValidationError): f.clean(c4.id) @@ -978,18 +978,18 @@ class OldFormForXTests(TestCase): # check that we can safely iterate choices repeatedly gen_one = list(f.choices) gen_two = f.choices - self.assertEqual(gen_one[2], (c2.pk, u"It's a test")) + self.assertEqual(gen_one[2], (c2.pk, "It's a test")) self.assertEqual(list(gen_two), [ - (u'', u'---------'), - (c1.pk, u'Entertainment'), - (c2.pk, u"It's a test"), - (c3.pk, u'Third')]) + ('', '---------'), + (c1.pk, 'Entertainment'), + (c2.pk, "It's a test"), + (c3.pk, 'Third')]) # check that we can override the label_from_instance method to print custom labels (#4620) f.queryset = Category.objects.all() f.label_from_instance = lambda obj: "category " + str(obj) self.assertEqual(list(f.choices), [ - (u'', u'---------'), + ('', '---------'), (c1.pk, 'category Entertainment'), (c2.pk, "category It's a test"), (c3.pk, 'category Third'), @@ -999,10 +999,10 @@ class OldFormForXTests(TestCase): f = forms.ModelMultipleChoiceField(Category.objects.all()) self.assertEqual(list(f.choices), [ - (c1.pk, u'Entertainment'), - (c2.pk, u"It's a test"), - (c3.pk, u'Third'), - (c4.pk, u'Fourth')]) + (c1.pk, 'Entertainment'), + (c2.pk, "It's a test"), + (c3.pk, 'Third'), + (c4.pk, 'Fourth')]) with self.assertRaises(ValidationError): f.clean(None) with self.assertRaises(ValidationError): @@ -1047,9 +1047,9 @@ class OldFormForXTests(TestCase): # queryset can be changed after the field is created. f.queryset = Category.objects.exclude(name='Fourth') self.assertEqual(list(f.choices), [ - (c1.pk, u'Entertainment'), - (c2.pk, u"It's a test"), - (c3.pk, u'Third')]) + (c1.pk, 'Entertainment'), + (c2.pk, "It's a test"), + (c3.pk, 'Third')]) self.assertEqual(map(lambda o: o.name, f.clean([c3.id])), ["Third"]) with self.assertRaises(ValidationError): f.clean([c4.id]) @@ -1070,7 +1070,7 @@ class OldFormForXTests(TestCase): self.assertEqual(ImprovedArticleWithParentLinkForm.base_fields.keys(), []) - bw = BetterWriter(name=u'Joe Better', score=10) + bw = BetterWriter(name='Joe Better', score=10) bw.save() self.assertEqual(sorted(model_to_dict(bw).keys()), ['id', 'name', 'score', 'writer_ptr']) @@ -1092,7 +1092,7 @@ class OldFormForXTests(TestCase): data = { 'writer': unicode(w_woodward.pk), - 'age': u'65', + 'age': '65', } form = WriterProfileForm(data) instance = form.save() @@ -1111,21 +1111,21 @@ class OldFormForXTests(TestCase): def test_phone_number_field(self): f = PhoneNumberForm({'phone': '(312) 555-1212', 'description': 'Assistance'}) self.assertEqual(f.is_valid(), True) - self.assertEqual(f.cleaned_data['phone'], u'312-555-1212') - self.assertEqual(f.cleaned_data['description'], u'Assistance') + self.assertEqual(f.cleaned_data['phone'], '312-555-1212') + self.assertEqual(f.cleaned_data['description'], 'Assistance') def test_file_field(self): # Test conditions when files is either not given or empty. - f = TextFileForm(data={'description': u'Assistance'}) + f = TextFileForm(data={'description': 'Assistance'}) self.assertEqual(f.is_valid(), False) - f = TextFileForm(data={'description': u'Assistance'}, files={}) + f = TextFileForm(data={'description': 'Assistance'}, files={}) self.assertEqual(f.is_valid(), False) # Upload a file and ensure it all works as expected. f = TextFileForm( - data={'description': u'Assistance'}, + data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test1.txt', b'hello world')}) self.assertEqual(f.is_valid(), True) self.assertEqual(type(f.cleaned_data['file']), SimpleUploadedFile) @@ -1134,7 +1134,7 @@ class OldFormForXTests(TestCase): instance.file.delete() f = TextFileForm( - data={'description': u'Assistance'}, + data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test1.txt', b'hello world')}) self.assertEqual(f.is_valid(), True) self.assertEqual(type(f.cleaned_data['file']), SimpleUploadedFile) @@ -1143,7 +1143,7 @@ class OldFormForXTests(TestCase): # Check if the max_length attribute has been inherited from the model. f = TextFileForm( - data={'description': u'Assistance'}, + data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test-maxlength.txt', b'hello world')}) self.assertEqual(f.is_valid(), False) @@ -1151,7 +1151,7 @@ class OldFormForXTests(TestCase): # save the file again, but leave it exactly as it is. f = TextFileForm( - data={'description': u'Assistance'}, + data={'description': 'Assistance'}, instance=instance) self.assertEqual(f.is_valid(), True) self.assertEqual(f.cleaned_data['file'].name, 'tests/test1.txt') @@ -1164,7 +1164,7 @@ class OldFormForXTests(TestCase): # Override the file by uploading a new one. f = TextFileForm( - data={'description': u'Assistance'}, + data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test2.txt', b'hello world')}, instance=instance) self.assertEqual(f.is_valid(), True) instance = f.save() @@ -1173,7 +1173,7 @@ class OldFormForXTests(TestCase): # Delete the current file since this is not done by Django. instance.file.delete() f = TextFileForm( - data={'description': u'Assistance'}, + data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test2.txt', b'hello world')}) self.assertEqual(f.is_valid(), True) instance = f.save() @@ -1185,14 +1185,14 @@ class OldFormForXTests(TestCase): instance.delete() # Test the non-required FileField - f = TextFileForm(data={'description': u'Assistance'}) + f = TextFileForm(data={'description': 'Assistance'}) f.fields['file'].required = False self.assertEqual(f.is_valid(), True) instance = f.save() self.assertEqual(instance.file.name, '') f = TextFileForm( - data={'description': u'Assistance'}, + data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test3.txt', b'hello world')}, instance=instance) self.assertEqual(f.is_valid(), True) instance = f.save() @@ -1201,12 +1201,12 @@ class OldFormForXTests(TestCase): # Instance can be edited w/out re-uploading the file and existing file should be preserved. f = TextFileForm( - data={'description': u'New Description'}, + data={'description': 'New Description'}, instance=instance) f.fields['file'].required = False self.assertEqual(f.is_valid(), True) instance = f.save() - self.assertEqual(instance.description, u'New Description') + self.assertEqual(instance.description, 'New Description') self.assertEqual(instance.file.name, 'tests/test3.txt') # Delete the current file since this is not done by Django. @@ -1214,7 +1214,7 @@ class OldFormForXTests(TestCase): instance.delete() f = TextFileForm( - data={'description': u'Assistance'}, + data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test3.txt', b'hello world')}) self.assertEqual(f.is_valid(), True) instance = f.save() @@ -1229,12 +1229,12 @@ class OldFormForXTests(TestCase): self.assertEqual(bif.is_valid(), True) bif = BigIntForm({'biggie': '-9223372036854775809'}) self.assertEqual(bif.is_valid(), False) - self.assertEqual(bif.errors, {'biggie': [u'Ensure this value is greater than or equal to -9223372036854775808.']}) + self.assertEqual(bif.errors, {'biggie': ['Ensure this value is greater than or equal to -9223372036854775808.']}) bif = BigIntForm({'biggie': '9223372036854775807'}) self.assertEqual(bif.is_valid(), True) bif = BigIntForm({'biggie': '9223372036854775808'}) self.assertEqual(bif.is_valid(), False) - self.assertEqual(bif.errors, {'biggie': [u'Ensure this value is less than or equal to 9223372036854775807.']}) + self.assertEqual(bif.errors, {'biggie': ['Ensure this value is less than or equal to 9223372036854775807.']}) @skipUnless(test_images, "PIL not installed") def test_image_field(self): @@ -1248,7 +1248,7 @@ class OldFormForXTests(TestCase): image_data2 = fp.read() f = ImageFileForm( - data={'description': u'An image'}, + data={'description': 'An image'}, files={'image': SimpleUploadedFile('test.png', image_data)}) self.assertEqual(f.is_valid(), True) self.assertEqual(type(f.cleaned_data['image']), SimpleUploadedFile) @@ -1261,7 +1261,7 @@ class OldFormForXTests(TestCase): # because the dimension fields are not null=True. instance.image.delete(save=False) f = ImageFileForm( - data={'description': u'An image'}, + data={'description': 'An image'}, files={'image': SimpleUploadedFile('test.png', image_data)}) self.assertEqual(f.is_valid(), True) self.assertEqual(type(f.cleaned_data['image']), SimpleUploadedFile) @@ -1273,7 +1273,7 @@ class OldFormForXTests(TestCase): # Edit an instance that already has the (required) image defined in the model. This will not # save the image again, but leave it exactly as it is. - f = ImageFileForm(data={'description': u'Look, it changed'}, instance=instance) + f = ImageFileForm(data={'description': 'Look, it changed'}, instance=instance) self.assertEqual(f.is_valid(), True) self.assertEqual(f.cleaned_data['image'].name, 'tests/test.png') instance = f.save() @@ -1287,7 +1287,7 @@ class OldFormForXTests(TestCase): # Override the file by uploading a new one. f = ImageFileForm( - data={'description': u'Changed it'}, + data={'description': 'Changed it'}, files={'image': SimpleUploadedFile('test2.png', image_data2)}, instance=instance) self.assertEqual(f.is_valid(), True) instance = f.save() @@ -1301,7 +1301,7 @@ class OldFormForXTests(TestCase): instance.delete() f = ImageFileForm( - data={'description': u'Changed it'}, + data={'description': 'Changed it'}, files={'image': SimpleUploadedFile('test2.png', image_data2)}) self.assertEqual(f.is_valid(), True) instance = f.save() @@ -1315,14 +1315,14 @@ class OldFormForXTests(TestCase): instance.delete() # Test the non-required ImageField - # Note: In Oracle, we expect a null ImageField to return u'' instead of + # Note: In Oracle, we expect a null ImageField to return '' instead of # None. if connection.features.interprets_empty_strings_as_nulls: - expected_null_imagefield_repr = u'' + expected_null_imagefield_repr = '' else: expected_null_imagefield_repr = None - f = OptionalImageFileForm(data={'description': u'Test'}) + f = OptionalImageFileForm(data={'description': 'Test'}) self.assertEqual(f.is_valid(), True) instance = f.save() self.assertEqual(instance.image.name, expected_null_imagefield_repr) @@ -1330,7 +1330,7 @@ class OldFormForXTests(TestCase): self.assertEqual(instance.height, None) f = OptionalImageFileForm( - data={'description': u'And a final one'}, + data={'description': 'And a final one'}, files={'image': SimpleUploadedFile('test3.png', image_data)}, instance=instance) self.assertEqual(f.is_valid(), True) instance = f.save() @@ -1340,11 +1340,11 @@ class OldFormForXTests(TestCase): # Editing the instance without re-uploading the image should not affect the image or its width/height properties f = OptionalImageFileForm( - data={'description': u'New Description'}, + data={'description': 'New Description'}, instance=instance) self.assertEqual(f.is_valid(), True) instance = f.save() - self.assertEqual(instance.description, u'New Description') + self.assertEqual(instance.description, 'New Description') self.assertEqual(instance.image.name, 'tests/test3.png') self.assertEqual(instance.width, 16) self.assertEqual(instance.height, 16) @@ -1354,7 +1354,7 @@ class OldFormForXTests(TestCase): instance.delete() f = OptionalImageFileForm( - data={'description': u'And a final one'}, + data={'description': 'And a final one'}, files={'image': SimpleUploadedFile('test4.png', image_data2)} ) self.assertEqual(f.is_valid(), True) @@ -1365,7 +1365,7 @@ class OldFormForXTests(TestCase): instance.delete() # Test callable upload_to behavior that's dependent on the value of another field in the model f = ImageFileForm( - data={'description': u'And a final one', 'path': 'foo'}, + data={'description': 'And a final one', 'path': 'foo'}, files={'image': SimpleUploadedFile('test4.png', image_data)}) self.assertEqual(f.is_valid(), True) instance = f.save() @@ -1381,22 +1381,22 @@ class OldFormForXTests(TestCase): f = CommaSeparatedIntegerForm({'field': '1,2,3'}) self.assertEqual(f.is_valid(), True) - self.assertEqual(f.cleaned_data, {'field': u'1,2,3'}) + self.assertEqual(f.cleaned_data, {'field': '1,2,3'}) f = CommaSeparatedIntegerForm({'field': '1a,2'}) - self.assertEqual(f.errors, {'field': [u'Enter only digits separated by commas.']}) + self.assertEqual(f.errors, {'field': ['Enter only digits separated by commas.']}) f = CommaSeparatedIntegerForm({'field': ',,,,'}) self.assertEqual(f.is_valid(), True) - self.assertEqual(f.cleaned_data, {'field': u',,,,'}) + self.assertEqual(f.cleaned_data, {'field': ',,,,'}) f = CommaSeparatedIntegerForm({'field': '1.2'}) - self.assertEqual(f.errors, {'field': [u'Enter only digits separated by commas.']}) + self.assertEqual(f.errors, {'field': ['Enter only digits separated by commas.']}) f = CommaSeparatedIntegerForm({'field': '1,a,2'}) - self.assertEqual(f.errors, {'field': [u'Enter only digits separated by commas.']}) + self.assertEqual(f.errors, {'field': ['Enter only digits separated by commas.']}) f = CommaSeparatedIntegerForm({'field': '1,,2'}) self.assertEqual(f.is_valid(), True) - self.assertEqual(f.cleaned_data, {'field': u'1,,2'}) + self.assertEqual(f.cleaned_data, {'field': '1,,2'}) f = CommaSeparatedIntegerForm({'field': '1'}) self.assertEqual(f.is_valid(), True) - self.assertEqual(f.cleaned_data, {'field': u'1'}) + self.assertEqual(f.cleaned_data, {'field': '1'}) # This Price instance generated by this form is not valid because the quantity # field is required, but the form is valid because the field is excluded from @@ -1439,10 +1439,10 @@ class OldFormForXTests(TestCase): field = forms.ModelChoiceField(Inventory.objects.all(), to_field_name='barcode') self.assertEqual(tuple(field.choices), ( - (u'', u'---------'), - (86, u'Apple'), - (87, u'Core'), - (22, u'Pear'))) + ('', '---------'), + (86, 'Apple'), + (87, 'Core'), + (22, 'Pear'))) form = InventoryForm(instance=core) self.assertHTMLEqual(unicode(form['parent']), '''

        ' % (owner1.auto_id, owner2.auto_id)) - owner1 = Owner.objects.get(name=u'Joe Perry') + owner1 = Owner.objects.get(name='Joe Perry') FormSet = inlineformset_factory(Owner, OwnerProfile, max_num=1, can_delete=False) self.assertEqual(FormSet.max_num, 1) @@ -815,7 +815,7 @@ class ModelFormsetTest(TestCase): 'ownerprofile-INITIAL_FORMS': '0', 'ownerprofile-MAX_NUM_FORMS': '1', 'ownerprofile-0-owner': '', - 'ownerprofile-0-age': u'54', + 'ownerprofile-0-age': '54', } formset = FormSet(data, instance=owner1) self.assertTrue(formset.is_valid()) @@ -836,7 +836,7 @@ class ModelFormsetTest(TestCase): 'ownerprofile-INITIAL_FORMS': '1', 'ownerprofile-MAX_NUM_FORMS': '1', 'ownerprofile-0-owner': unicode(owner1.auto_id), - 'ownerprofile-0-age': u'55', + 'ownerprofile-0-age': '55', } formset = FormSet(data, instance=owner1) self.assertTrue(formset.is_valid()) @@ -849,7 +849,7 @@ class ModelFormsetTest(TestCase): def test_unique_true_enforces_max_num_one(self): # ForeignKey with unique=True should enforce max_num=1 - place = Place.objects.create(pk=1, name=u'Giordanos', city=u'Chicago') + place = Place.objects.create(pk=1, name='Giordanos', city='Chicago') FormSet = inlineformset_factory(Place, Location, can_delete=False) self.assertEqual(FormSet.max_num, 1) @@ -887,7 +887,7 @@ class ModelFormsetTest(TestCase): } formset = FormSet(data) self.assertFalse(formset.is_valid()) - self.assertEqual(formset.errors, [{'slug': [u'Product with this Slug already exists.']}]) + self.assertEqual(formset.errors, [{'slug': ['Product with this Slug already exists.']}]) def test_unique_together_validation(self): FormSet = modelformset_factory(Price, extra=1) @@ -895,7 +895,7 @@ class ModelFormsetTest(TestCase): 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', - 'form-0-price': u'12.00', + 'form-0-price': '12.00', 'form-0-quantity': '1', } formset = FormSet(data) @@ -910,17 +910,17 @@ class ModelFormsetTest(TestCase): 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', - 'form-0-price': u'12.00', + 'form-0-price': '12.00', 'form-0-quantity': '1', } formset = FormSet(data) self.assertFalse(formset.is_valid()) - self.assertEqual(formset.errors, [{'__all__': [u'Price with this Price and Quantity already exists.']}]) + self.assertEqual(formset.errors, [{'__all__': ['Price with this Price and Quantity already exists.']}]) def test_unique_together_with_inlineformset_factory(self): # Also see bug #8882. - repository = Repository.objects.create(name=u'Test Repo') + repository = Repository.objects.create(name='Test Repo') FormSet = inlineformset_factory(Repository, Revision, extra=1) data = { 'revision_set-TOTAL_FORMS': '1', @@ -949,7 +949,7 @@ class ModelFormsetTest(TestCase): } formset = FormSet(data, instance=repository) self.assertFalse(formset.is_valid()) - self.assertEqual(formset.errors, [{'__all__': [u'Revision with this Repository and Revision already exists.']}]) + self.assertEqual(formset.errors, [{'__all__': ['Revision with this Repository and Revision already exists.']}]) # unique_together with inlineformset_factory with overridden form fields # Also see #9494 @@ -1040,7 +1040,7 @@ class ModelFormsetTest(TestCase): def test_inlineformset_factory_with_null_fk(self): # inlineformset_factory tests with fk having null=True. see #9462. # create some data that will exbit the issue - team = Team.objects.create(name=u"Red Vipers") + team = Team.objects.create(name="Red Vipers") Player(name="Timmy").save() Player(name="Bobby", team=team).save() @@ -1073,7 +1073,7 @@ class ModelFormsetTest(TestCase): formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset._non_form_errors, - [u'Please correct the duplicate data for slug.']) + ['Please correct the duplicate data for slug.']) FormSet = modelformset_factory(Price, extra=2) data = { @@ -1088,7 +1088,7 @@ class ModelFormsetTest(TestCase): formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset._non_form_errors, - [u'Please correct the duplicate data for price and quantity, which must be unique.']) + ['Please correct the duplicate data for price and quantity, which must be unique.']) # Only the price field is specified, this should skip any unique checks since # the unique_together is not fulfilled. This will fail with a KeyError if broken. @@ -1126,9 +1126,9 @@ class ModelFormsetTest(TestCase): formset = FormSet(data=data, instance=author) self.assertFalse(formset.is_valid()) self.assertEqual(formset._non_form_errors, - [u'Please correct the duplicate data for title.']) + ['Please correct the duplicate data for title.']) self.assertEqual(formset.errors, - [{}, {'__all__': [u'Please correct the duplicate values below.']}]) + [{}, {'__all__': ['Please correct the duplicate values below.']}]) FormSet = modelformset_factory(Post, extra=2) data = { @@ -1148,9 +1148,9 @@ class ModelFormsetTest(TestCase): formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset._non_form_errors, - [u'Please correct the duplicate data for title which must be unique for the date in posted.']) + ['Please correct the duplicate data for title which must be unique for the date in posted.']) self.assertEqual(formset.errors, - [{}, {'__all__': [u'Please correct the duplicate values below.']}]) + [{}, {'__all__': ['Please correct the duplicate values below.']}]) data = { 'form-TOTAL_FORMS': '2', @@ -1169,7 +1169,7 @@ class ModelFormsetTest(TestCase): formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset._non_form_errors, - [u'Please correct the duplicate data for slug which must be unique for the year in posted.']) + ['Please correct the duplicate data for slug which must be unique for the year in posted.']) data = { 'form-TOTAL_FORMS': '2', @@ -1188,4 +1188,4 @@ class ModelFormsetTest(TestCase): formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset._non_form_errors, - [u'Please correct the duplicate data for subtitle which must be unique for the month in posted.']) + ['Please correct the duplicate data for subtitle which must be unique for the month in posted.']) diff --git a/tests/modeltests/model_inheritance/models.py b/tests/modeltests/model_inheritance/models.py index a0fed8a5ccd..37ca603021b 100644 --- a/tests/modeltests/model_inheritance/models.py +++ b/tests/modeltests/model_inheritance/models.py @@ -11,6 +11,7 @@ Model inheritance exists in two varieties: Both styles are demonstrated here. """ +from __future__ import unicode_literals from django.db import models @@ -27,7 +28,7 @@ class CommonInfo(models.Model): ordering = ['name'] def __unicode__(self): - return u'%s %s' % (self.__class__.__name__, self.name) + return '%s %s' % (self.__class__.__name__, self.name) class Worker(CommonInfo): job = models.CharField(max_length=50) @@ -72,14 +73,14 @@ class Chef(models.Model): name = models.CharField(max_length=50) def __unicode__(self): - return u"%s the chef" % self.name + return "%s the chef" % self.name class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) def __unicode__(self): - return u"%s the place" % self.name + return "%s the place" % self.name class Rating(models.Model): rating = models.IntegerField(null=True, blank=True) @@ -97,19 +98,19 @@ class Restaurant(Place, Rating): db_table = 'my_restaurant' def __unicode__(self): - return u"%s the restaurant" % self.name + return "%s the restaurant" % self.name class ItalianRestaurant(Restaurant): serves_gnocchi = models.BooleanField() def __unicode__(self): - return u"%s the italian restaurant" % self.name + return "%s the italian restaurant" % self.name class Supplier(Place): customers = models.ManyToManyField(Restaurant, related_name='provider') def __unicode__(self): - return u"%s the supplier" % self.name + return "%s the supplier" % self.name class ParkingLot(Place): # An explicit link to the parent (we can control the attribute name). @@ -117,7 +118,7 @@ class ParkingLot(Place): main_site = models.ForeignKey(Place, related_name='lot') def __unicode__(self): - return u"%s the parking lot" % self.name + return "%s the parking lot" % self.name # # Abstract base classes with related models where the sub-class has the diff --git a/tests/modeltests/one_to_one/models.py b/tests/modeltests/one_to_one/models.py index 429c1d019f6..8c6d56a795a 100644 --- a/tests/modeltests/one_to_one/models.py +++ b/tests/modeltests/one_to_one/models.py @@ -5,6 +5,7 @@ To define a one-to-one relationship, use ``OneToOneField()``. In this example, a ``Place`` optionally can be a ``Restaurant``. """ +from __future__ import unicode_literals from django.db import models @@ -14,7 +15,7 @@ class Place(models.Model): address = models.CharField(max_length=80) def __unicode__(self): - return u"%s the place" % self.name + return "%s the place" % self.name class Restaurant(models.Model): place = models.OneToOneField(Place, primary_key=True) @@ -22,14 +23,14 @@ class Restaurant(models.Model): serves_pizza = models.BooleanField() def __unicode__(self): - return u"%s the restaurant" % self.place.name + return "%s the restaurant" % self.place.name class Waiter(models.Model): restaurant = models.ForeignKey(Restaurant) name = models.CharField(max_length=50) def __unicode__(self): - return u"%s the waiter at %s" % (self.name, self.restaurant) + return "%s the waiter at %s" % (self.name, self.restaurant) class ManualPrimaryKey(models.Model): primary_key = models.CharField(max_length=10, primary_key=True) @@ -45,4 +46,4 @@ class MultiModel(models.Model): name = models.CharField(max_length=50) def __unicode__(self): - return u"Multimodel %s" % self.name + return "Multimodel %s" % self.name diff --git a/tests/modeltests/pagination/tests.py b/tests/modeltests/pagination/tests.py index b7e217ebebc..9ced9edff2d 100644 --- a/tests/modeltests/pagination/tests.py +++ b/tests/modeltests/pagination/tests.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from datetime import datetime @@ -32,7 +32,7 @@ class PaginationTests(TestCase): def test_first_page(self): paginator = Paginator(Article.objects.all(), 5) p = paginator.page(1) - self.assertEqual(u"", unicode(p)) + self.assertEqual("", unicode(p)) self.assertQuerysetEqual(p.object_list, [ "", "", @@ -52,7 +52,7 @@ class PaginationTests(TestCase): def test_last_page(self): paginator = Paginator(Article.objects.all(), 5) p = paginator.page(2) - self.assertEqual(u"", unicode(p)) + self.assertEqual("", unicode(p)) self.assertQuerysetEqual(p.object_list, [ "", "", @@ -109,7 +109,7 @@ class PaginationTests(TestCase): self.assertEqual(2, paginator.num_pages) self.assertEqual([1, 2], paginator.page_range) p = paginator.page(1) - self.assertEqual(u"", unicode(p)) + self.assertEqual("", unicode(p)) self.assertEqual([1, 2, 3, 4, 5], p.object_list) self.assertTrue(p.has_next()) self.assertFalse(p.has_previous()) diff --git a/tests/modeltests/prefetch_related/tests.py b/tests/modeltests/prefetch_related/tests.py index b21244b6d92..43f195d3575 100644 --- a/tests/modeltests/prefetch_related/tests.py +++ b/tests/modeltests/prefetch_related/tests.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from django.contrib.contenttypes.models import ContentType from django.db import connection @@ -66,7 +66,7 @@ class PrefetchRelatedTests(TestCase): lists = [list(b.first_time_authors.all()) for b in Book.objects.prefetch_related('first_time_authors')] - self.assertQuerysetEqual(self.book2.authors.all(), [u""]) + self.assertQuerysetEqual(self.book2.authors.all(), [""]) def test_onetoone_reverse_no_match(self): # Regression for #17439 @@ -125,10 +125,10 @@ class PrefetchRelatedTests(TestCase): for a in qs] self.assertEqual(lists, [ - [[u"Amy"], [u"Belinda"]], # Charlotte - Poems, Jane Eyre - [[u"Amy"]], # Anne - Poems - [[u"Amy"], []], # Emily - Poems, Wuthering Heights - [[u"Amy", u"Belinda"]], # Jane - Sense and Sense + [["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre + [["Amy"]], # Anne - Poems + [["Amy"], []], # Emily - Poems, Wuthering Heights + [["Amy", "Belinda"]], # Jane - Sense and Sense ]) def test_overriding_prefetch(self): @@ -139,10 +139,10 @@ class PrefetchRelatedTests(TestCase): for a in qs] self.assertEqual(lists, [ - [[u"Amy"], [u"Belinda"]], # Charlotte - Poems, Jane Eyre - [[u"Amy"]], # Anne - Poems - [[u"Amy"], []], # Emily - Poems, Wuthering Heights - [[u"Amy", u"Belinda"]], # Jane - Sense and Sense + [["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre + [["Amy"]], # Anne - Poems + [["Amy"], []], # Emily - Poems, Wuthering Heights + [["Amy", "Belinda"]], # Jane - Sense and Sense ]) with self.assertNumQueries(3): qs = Author.objects.prefetch_related('books__read_by', 'books') @@ -151,10 +151,10 @@ class PrefetchRelatedTests(TestCase): for a in qs] self.assertEqual(lists, [ - [[u"Amy"], [u"Belinda"]], # Charlotte - Poems, Jane Eyre - [[u"Amy"]], # Anne - Poems - [[u"Amy"], []], # Emily - Poems, Wuthering Heights - [[u"Amy", u"Belinda"]], # Jane - Sense and Sense + [["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre + [["Amy"]], # Anne - Poems + [["Amy"], []], # Emily - Poems, Wuthering Heights + [["Amy", "Belinda"]], # Jane - Sense and Sense ]) def test_get(self): @@ -166,7 +166,7 @@ class PrefetchRelatedTests(TestCase): author = Author.objects.prefetch_related('books__read_by').get(name="Charlotte") lists = [[unicode(r) for r in b.read_by.all()] for b in author.books.all()] - self.assertEqual(lists, [[u"Amy"], [u"Belinda"]]) # Poems, Jane Eyre + self.assertEqual(lists, [["Amy"], ["Belinda"]]) # Poems, Jane Eyre def test_foreign_key_then_m2m(self): """ @@ -177,10 +177,10 @@ class PrefetchRelatedTests(TestCase): qs = Author.objects.select_related('first_book').prefetch_related('first_book__read_by') lists = [[unicode(r) for r in a.first_book.read_by.all()] for a in qs] - self.assertEqual(lists, [[u"Amy"], - [u"Amy"], - [u"Amy"], - [u"Amy", "Belinda"]]) + self.assertEqual(lists, [["Amy"], + ["Amy"], + ["Amy"], + ["Amy", "Belinda"]]) def test_attribute_error(self): qs = Reader.objects.all().prefetch_related('books_read__xyz') diff --git a/tests/modeltests/proxy_models/tests.py b/tests/modeltests/proxy_models/tests.py index 738e0dbce29..7ec86e9b228 100644 --- a/tests/modeltests/proxy_models/tests.py +++ b/tests/modeltests/proxy_models/tests.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from django.contrib.contenttypes.models import ContentType from django.core import management @@ -195,7 +195,7 @@ class ProxyModelTests(TestCase): signals.pre_save.connect(h3, sender=Person) signals.post_save.connect(h4, sender=Person) - dino = MyPerson.objects.create(name=u"dino") + dino = MyPerson.objects.create(name="dino") self.assertEqual(output, [ 'MyPerson pre save', 'MyPerson post save' @@ -209,7 +209,7 @@ class ProxyModelTests(TestCase): signals.pre_save.connect(h5, sender=MyPersonProxy) signals.post_save.connect(h6, sender=MyPersonProxy) - dino = MyPersonProxy.objects.create(name=u"pebbles") + dino = MyPersonProxy.objects.create(name="pebbles") self.assertEqual(output, [ 'MyPersonProxy pre save', diff --git a/tests/modeltests/save_delete_hooks/models.py b/tests/modeltests/save_delete_hooks/models.py index 515c7f6c917..bae60e4b866 100644 --- a/tests/modeltests/save_delete_hooks/models.py +++ b/tests/modeltests/save_delete_hooks/models.py @@ -4,6 +4,7 @@ To execute arbitrary code around ``save()`` and ``delete()``, just subclass the methods. """ +from __future__ import unicode_literals from django.db import models @@ -17,7 +18,7 @@ class Person(models.Model): self.data = [] def __unicode__(self): - return u"%s %s" % (self.first_name, self.last_name) + return "%s %s" % (self.first_name, self.last_name) def save(self, *args, **kwargs): self.data.append("Before save") diff --git a/tests/modeltests/select_related/tests.py b/tests/modeltests/select_related/tests.py index ebe2f8c2be7..557a5c318af 100644 --- a/tests/modeltests/select_related/tests.py +++ b/tests/modeltests/select_related/tests.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from django.test import TestCase @@ -147,13 +147,13 @@ class SelectRelatedTests(TestCase): world = Species.objects.filter(genus__name='Amanita')\ .select_related('genus__family') orders = [o.genus.family.order.name for o in world] - self.assertEqual(orders, [u'Agaricales']) + self.assertEqual(orders, ['Agaricales']) def test_field_traversal(self): with self.assertNumQueries(1): s = Species.objects.all().select_related('genus__family__order' ).order_by('id')[0:1].get().genus.family.order.name - self.assertEqual(s, u'Diptera') + self.assertEqual(s, 'Diptera') def test_depth_fields_fails(self): self.assertRaises(TypeError, diff --git a/tests/modeltests/serializers/models.py b/tests/modeltests/serializers/models.py index 9948afd4e02..3549be1b4ff 100644 --- a/tests/modeltests/serializers/models.py +++ b/tests/modeltests/serializers/models.py @@ -5,6 +5,7 @@ ``django.core.serializers`` provides interfaces to converting Django ``QuerySet`` objects to and from "flat" data (i.e. strings). """ +from __future__ import unicode_literals from decimal import Decimal @@ -49,7 +50,7 @@ class AuthorProfile(models.Model): date_of_birth = models.DateField() def __unicode__(self): - return u"Profile of %s" % self.author + return "Profile of %s" % self.author class Actor(models.Model): @@ -116,4 +117,4 @@ class Player(models.Model): team = TeamField() def __unicode__(self): - return u'%s (%d) playing for %s' % (self.name, self.rank, self.team.to_string()) + return '%s (%d) playing for %s' % (self.name, self.rank, self.team.to_string()) diff --git a/tests/modeltests/serializers/tests.py b/tests/modeltests/serializers/tests.py index e792c944a10..13cf1e7e17a 100644 --- a/tests/modeltests/serializers/tests.py +++ b/tests/modeltests/serializers/tests.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals # -*- coding: utf-8 -*- import json @@ -162,8 +162,8 @@ class SerializersTestBase(object): def test_serialize_unicode(self): """Tests that unicode makes the roundtrip intact""" - actor_name = u"Za\u017c\u00f3\u0142\u0107" - movie_title = u'G\u0119\u015bl\u0105 ja\u017a\u0144' + actor_name = "Za\u017c\u00f3\u0142\u0107" + movie_title = 'G\u0119\u015bl\u0105 ja\u017a\u0144' ac = Actor(name=actor_name) mv = Movie(title=movie_title, actor=ac) ac.save() diff --git a/tests/modeltests/signals/models.py b/tests/modeltests/signals/models.py index 53b8f266064..18ca4676550 100644 --- a/tests/modeltests/signals/models.py +++ b/tests/modeltests/signals/models.py @@ -1,6 +1,7 @@ """ Testing signals before/after saving and deleting. """ +from __future__ import unicode_literals from django.db import models @@ -10,11 +11,11 @@ class Person(models.Model): last_name = models.CharField(max_length=20) def __unicode__(self): - return u"%s %s" % (self.first_name, self.last_name) + return "%s %s" % (self.first_name, self.last_name) class Car(models.Model): make = models.CharField(max_length=20) model = models.CharField(max_length=20) def __unicode__(self): - return u"%s %s" % (self.make, self.model) + return "%s %s" % (self.make, self.model) diff --git a/tests/modeltests/str/tests.py b/tests/modeltests/str/tests.py index 1b0eb0972fa..bed9ea719bf 100644 --- a/tests/modeltests/str/tests.py +++ b/tests/modeltests/str/tests.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import datetime @@ -19,7 +19,7 @@ class SimpleTests(TestCase): def test_international(self): a = InternationalArticle.objects.create( - headline=u'Girl wins €12.500 in lottery', + headline='Girl wins €12.500 in lottery', pub_date=datetime.datetime(2005, 7, 28) ) # The default str() output will be the UTF-8 encoded output of __unicode__(). diff --git a/tests/modeltests/test_client/models.py b/tests/modeltests/test_client/models.py index a533d6a280e..399d2906a83 100644 --- a/tests/modeltests/test_client/models.py +++ b/tests/modeltests/test_client/models.py @@ -20,7 +20,7 @@ testing against the contexts and templates produced by a view, rather than the HTML rendered to the end-user. """ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from django.conf import settings from django.core import mail @@ -37,12 +37,12 @@ class ClientTest(TestCase): "GET a view" # The data is ignored, but let's check it doesn't crash the system # anyway. - data = {'var': u'\xf2'} + data = {'var': '\xf2'} response = self.client.get('/test_client/get_view/', data) # Check some response details self.assertContains(response, 'This is a test') - self.assertEqual(response.context['var'], u'\xf2') + self.assertEqual(response.context['var'], '\xf2') self.assertEqual(response.templates[0].name, 'GET Template') def test_get_post_view(self): diff --git a/tests/modeltests/timezones/tests.py b/tests/modeltests/timezones/tests.py index bd9c7658f92..aadb8ba842f 100644 --- a/tests/modeltests/timezones/tests.py +++ b/tests/modeltests/timezones/tests.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import datetime import os import sys @@ -873,13 +875,13 @@ class TemplateTests(TestCase): class LegacyFormsTests(TestCase): def test_form(self): - form = EventForm({'dt': u'2011-09-01 13:20:30'}) + form = EventForm({'dt': '2011-09-01 13:20:30'}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 9, 1, 13, 20, 30)) @skipIf(pytz is None, "this test requires pytz") def test_form_with_non_existent_time(self): - form = EventForm({'dt': u'2011-03-27 02:30:00'}) + form = EventForm({'dt': '2011-03-27 02:30:00'}) with timezone.override(pytz.timezone('Europe/Paris')): # this is obviously a bug self.assertTrue(form.is_valid()) @@ -887,19 +889,19 @@ class LegacyFormsTests(TestCase): @skipIf(pytz is None, "this test requires pytz") def test_form_with_ambiguous_time(self): - form = EventForm({'dt': u'2011-10-30 02:30:00'}) + form = EventForm({'dt': '2011-10-30 02:30:00'}) with timezone.override(pytz.timezone('Europe/Paris')): # this is obviously a bug self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 10, 30, 2, 30, 0)) def test_split_form(self): - form = EventSplitForm({'dt_0': u'2011-09-01', 'dt_1': u'13:20:30'}) + form = EventSplitForm({'dt_0': '2011-09-01', 'dt_1': '13:20:30'}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 9, 1, 13, 20, 30)) def test_model_form(self): - EventModelForm({'dt': u'2011-09-01 13:20:30'}).save() + EventModelForm({'dt': '2011-09-01 13:20:30'}).save() e = Event.objects.get() self.assertEqual(e.dt, datetime.datetime(2011, 9, 1, 13, 20, 30)) @@ -909,12 +911,12 @@ class NewFormsTests(TestCase): @requires_tz_support def test_form(self): - form = EventForm({'dt': u'2011-09-01 13:20:30'}) + form = EventForm({'dt': '2011-09-01 13:20:30'}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)) def test_form_with_other_timezone(self): - form = EventForm({'dt': u'2011-09-01 17:20:30'}) + form = EventForm({'dt': '2011-09-01 17:20:30'}) with timezone.override(ICT): self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)) @@ -922,30 +924,30 @@ class NewFormsTests(TestCase): @skipIf(pytz is None, "this test requires pytz") def test_form_with_non_existent_time(self): with timezone.override(pytz.timezone('Europe/Paris')): - form = EventForm({'dt': u'2011-03-27 02:30:00'}) + form = EventForm({'dt': '2011-03-27 02:30:00'}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['dt'], - [u"2011-03-27 02:30:00 couldn't be interpreted in time zone " - u"Europe/Paris; it may be ambiguous or it may not exist."]) + ["2011-03-27 02:30:00 couldn't be interpreted in time zone " + "Europe/Paris; it may be ambiguous or it may not exist."]) @skipIf(pytz is None, "this test requires pytz") def test_form_with_ambiguous_time(self): with timezone.override(pytz.timezone('Europe/Paris')): - form = EventForm({'dt': u'2011-10-30 02:30:00'}) + form = EventForm({'dt': '2011-10-30 02:30:00'}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['dt'], - [u"2011-10-30 02:30:00 couldn't be interpreted in time zone " - u"Europe/Paris; it may be ambiguous or it may not exist."]) + ["2011-10-30 02:30:00 couldn't be interpreted in time zone " + "Europe/Paris; it may be ambiguous or it may not exist."]) @requires_tz_support def test_split_form(self): - form = EventSplitForm({'dt_0': u'2011-09-01', 'dt_1': u'13:20:30'}) + form = EventSplitForm({'dt_0': '2011-09-01', 'dt_1': '13:20:30'}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)) @requires_tz_support def test_model_form(self): - EventModelForm({'dt': u'2011-09-01 13:20:30'}).save() + EventModelForm({'dt': '2011-09-01 13:20:30'}).save() e = Event.objects.get() self.assertEqual(e.dt, datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)) diff --git a/tests/modeltests/transactions/models.py b/tests/modeltests/transactions/models.py index 66acb9fc630..7a51b9ac1c1 100644 --- a/tests/modeltests/transactions/models.py +++ b/tests/modeltests/transactions/models.py @@ -6,6 +6,7 @@ each transaction upon a write, but you can decorate a function to get commit-on-success behavior. Alternatively, you can manage the transaction manually. """ +from __future__ import unicode_literals from django.db import models @@ -19,4 +20,4 @@ class Reporter(models.Model): ordering = ('first_name', 'last_name') def __unicode__(self): - return u"%s %s" % (self.first_name, self.last_name) \ No newline at end of file + return "%s %s" % (self.first_name, self.last_name) diff --git a/tests/modeltests/update/tests.py b/tests/modeltests/update/tests.py index c31f4dfaa95..7a1177c1fda 100644 --- a/tests/modeltests/update/tests.py +++ b/tests/modeltests/update/tests.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from django.test import TestCase @@ -77,7 +77,7 @@ class AdvancedTests(TestCase): resp = DataPoint.objects.filter(value="banana").update( value="pineapple") self.assertEqual(resp, 2) - self.assertEqual(DataPoint.objects.get(name="d2").value, u'pineapple') + self.assertEqual(DataPoint.objects.get(name="d2").value, 'pineapple') def test_update_fk(self): """ @@ -97,8 +97,8 @@ class AdvancedTests(TestCase): value="fruit", another_value="peach") self.assertEqual(resp, 1) d = DataPoint.objects.get(name="d0") - self.assertEqual(d.value, u'fruit') - self.assertEqual(d.another_value, u'peach') + self.assertEqual(d.value, 'fruit') + self.assertEqual(d.another_value, 'peach') def test_update_all(self): """ @@ -107,7 +107,7 @@ class AdvancedTests(TestCase): """ self.assertEqual(DataPoint.objects.update(value='thing'), 3) resp = DataPoint.objects.values('value').distinct() - self.assertEqual(list(resp), [{'value': u'thing'}]) + self.assertEqual(list(resp), [{'value': 'thing'}]) def test_update_slice_fail(self): """ diff --git a/tests/modeltests/validation/models.py b/tests/modeltests/validation/models.py index 1a6fdd7c16c..0adc9fec320 100644 --- a/tests/modeltests/validation/models.py +++ b/tests/modeltests/validation/models.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from datetime import datetime from django.core.exceptions import ValidationError @@ -80,8 +82,8 @@ class FlexibleDatePost(models.Model): posted = models.DateField(blank=True, null=True) class UniqueErrorsModel(models.Model): - name = models.CharField(max_length=100, unique=True, error_messages={'unique': u'Custom unique name message.'}) - no = models.IntegerField(unique=True, error_messages={'unique': u'Custom unique number message.'}) + name = models.CharField(max_length=100, unique=True, error_messages={'unique': 'Custom unique name message.'}) + no = models.IntegerField(unique=True, error_messages={'unique': 'Custom unique number message.'}) class GenericIPAddressTestModel(models.Model): generic_ip = models.GenericIPAddressField(blank=True, null=True, unique=True) @@ -101,4 +103,4 @@ try: auto2 = models.AutoField(primary_key=True) except AssertionError as assertion_error: pass # Fail silently -assert str(assertion_error) == u"A model can't have more than one AutoField." +assert str(assertion_error) == "A model can't have more than one AutoField." diff --git a/tests/modeltests/validation/test_error_messages.py b/tests/modeltests/validation/test_error_messages.py index 4aea3d52de6..62ca4e95c6a 100644 --- a/tests/modeltests/validation/test_error_messages.py +++ b/tests/modeltests/validation/test_error_messages.py @@ -1,4 +1,6 @@ # -*- encoding: utf-8 -*- +from __future__ import unicode_literals + from django.core.exceptions import ValidationError from django.db import models from django.utils.unittest import TestCase @@ -13,8 +15,8 @@ class ValidationMessagesTest(TestCase): def test_autofield_field_raises_error_message(self): f = models.AutoField(primary_key=True) - self._test_validation_messages(f, u'fõo', - [u"'fõo' value must be an integer."]) + self._test_validation_messages(f, 'fõo', + ["'fõo' value must be an integer."]) # primary_key must be True. Refs #12467. with self.assertRaisesRegexp(AssertionError, "AutoFields must have primary_key=True."): @@ -22,73 +24,73 @@ class ValidationMessagesTest(TestCase): def test_integer_field_raises_error_message(self): f = models.IntegerField() - self._test_validation_messages(f, u'fõo', - [u"'fõo' value must be an integer."]) + self._test_validation_messages(f, 'fõo', + ["'fõo' value must be an integer."]) def test_boolean_field_raises_error_message(self): f = models.BooleanField() - self._test_validation_messages(f, u'fõo', - [u"'fõo' value must be either True or False."]) + self._test_validation_messages(f, 'fõo', + ["'fõo' value must be either True or False."]) def test_float_field_raises_error_message(self): f = models.FloatField() - self._test_validation_messages(f, u'fõo', - [u"'fõo' value must be a float."]) + self._test_validation_messages(f, 'fõo', + ["'fõo' value must be a float."]) def test_decimal_field_raises_error_message(self): f = models.DecimalField() - self._test_validation_messages(f, u'fõo', - [u"'fõo' value must be a decimal number."]) + self._test_validation_messages(f, 'fõo', + ["'fõo' value must be a decimal number."]) def test_null_boolean_field_raises_error_message(self): f = models.NullBooleanField() - self._test_validation_messages(f, u'fõo', - [u"'fõo' value must be either None, True or False."]) + self._test_validation_messages(f, 'fõo', + ["'fõo' value must be either None, True or False."]) def test_date_field_raises_error_message(self): f = models.DateField() - self._test_validation_messages(f, u'fõo', - [u"'fõo' value has an invalid date format. " - u"It must be in YYYY-MM-DD format."]) + self._test_validation_messages(f, 'fõo', + ["'fõo' value has an invalid date format. " + "It must be in YYYY-MM-DD format."]) self._test_validation_messages(f, 'aaaa-10-10', - [u"'aaaa-10-10' value has an invalid date format. " - u"It must be in YYYY-MM-DD format."]) + ["'aaaa-10-10' value has an invalid date format. " + "It must be in YYYY-MM-DD format."]) self._test_validation_messages(f, '2011-13-10', - [u"'2011-13-10' value has the correct format (YYYY-MM-DD) " - u"but it is an invalid date."]) + ["'2011-13-10' value has the correct format (YYYY-MM-DD) " + "but it is an invalid date."]) self._test_validation_messages(f, '2011-10-32', - [u"'2011-10-32' value has the correct format (YYYY-MM-DD) " - u"but it is an invalid date."]) + ["'2011-10-32' value has the correct format (YYYY-MM-DD) " + "but it is an invalid date."]) def test_datetime_field_raises_error_message(self): f = models.DateTimeField() # Wrong format - self._test_validation_messages(f, u'fõo', - [u"'fõo' value has an invalid format. It must be " - u"in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]) + self._test_validation_messages(f, 'fõo', + ["'fõo' value has an invalid format. It must be " + "in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]) # Correct format but invalid date self._test_validation_messages(f, '2011-10-32', - [u"'2011-10-32' value has the correct format " - u"(YYYY-MM-DD) but it is an invalid date."]) + ["'2011-10-32' value has the correct format " + "(YYYY-MM-DD) but it is an invalid date."]) # Correct format but invalid date/time self._test_validation_messages(f, '2011-10-32 10:10', - [u"'2011-10-32 10:10' value has the correct format " - u"(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) " - u"but it is an invalid date/time."]) + ["'2011-10-32 10:10' value has the correct format " + "(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) " + "but it is an invalid date/time."]) def test_time_field_raises_error_message(self): f = models.TimeField() # Wrong format - self._test_validation_messages(f, u'fõo', - [u"'fõo' value has an invalid format. It must be in " - u"HH:MM[:ss[.uuuuuu]] format."]) + self._test_validation_messages(f, 'fõo', + ["'fõo' value has an invalid format. It must be in " + "HH:MM[:ss[.uuuuuu]] format."]) # Correct format but invalid time self._test_validation_messages(f, '25:50', - [u"'25:50' value has the correct format " - u"(HH:MM[:ss[.uuuuuu]]) but it is an invalid time."]) + ["'25:50' value has the correct format " + "(HH:MM[:ss[.uuuuuu]]) but it is an invalid time."]) diff --git a/tests/modeltests/validation/test_unique.py b/tests/modeltests/validation/test_unique.py index 8f819b9d9c8..038da164949 100644 --- a/tests/modeltests/validation/test_unique.py +++ b/tests/modeltests/validation/test_unique.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import datetime @@ -83,7 +83,7 @@ class PerformUniqueChecksTest(TestCase): p = Post(title="Django 1.0 is released", posted=datetime.date(2008, 9, 3)) with self.assertRaises(ValidationError) as cm: p.full_clean() - self.assertEqual(cm.exception.message_dict, {'title': [u'Title must be unique for Posted date.']}) + self.assertEqual(cm.exception.message_dict, {'title': ['Title must be unique for Posted date.']}) # Should work without errors p = Post(title="Work on Django 1.1 begins", posted=datetime.date(2008, 9, 3)) @@ -96,17 +96,17 @@ class PerformUniqueChecksTest(TestCase): p = Post(slug="Django 1.0", posted=datetime.datetime(2008, 1, 1)) with self.assertRaises(ValidationError) as cm: p.full_clean() - self.assertEqual(cm.exception.message_dict, {'slug': [u'Slug must be unique for Posted year.']}) + self.assertEqual(cm.exception.message_dict, {'slug': ['Slug must be unique for Posted year.']}) p = Post(subtitle="Finally", posted=datetime.datetime(2008, 9, 30)) with self.assertRaises(ValidationError) as cm: p.full_clean() - self.assertEqual(cm.exception.message_dict, {'subtitle': [u'Subtitle must be unique for Posted month.']}) + self.assertEqual(cm.exception.message_dict, {'subtitle': ['Subtitle must be unique for Posted month.']}) p = Post(title="Django 1.0 is released") with self.assertRaises(ValidationError) as cm: p.full_clean() - self.assertEqual(cm.exception.message_dict, {'posted': [u'This field cannot be null.']}) + self.assertEqual(cm.exception.message_dict, {'posted': ['This field cannot be null.']}) def test_unique_for_date_with_nullable_date(self): p1 = FlexibleDatePost.objects.create(title="Django 1.0 is released", @@ -135,10 +135,10 @@ class PerformUniqueChecksTest(TestCase): m = UniqueErrorsModel(name='Some Name', no=11) with self.assertRaises(ValidationError) as cm: m.full_clean() - self.assertEqual(cm.exception.message_dict, {'name': [u'Custom unique name message.']}) + self.assertEqual(cm.exception.message_dict, {'name': ['Custom unique name message.']}) m = UniqueErrorsModel(name='Some Other Name', no=10) with self.assertRaises(ValidationError) as cm: m.full_clean() - self.assertEqual(cm.exception.message_dict, {'no': [u'Custom unique number message.']}) + self.assertEqual(cm.exception.message_dict, {'no': ['Custom unique number message.']}) diff --git a/tests/modeltests/validation/tests.py b/tests/modeltests/validation/tests.py index f2554983060..4f658203dfd 100644 --- a/tests/modeltests/validation/tests.py +++ b/tests/modeltests/validation/tests.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from django import forms from django.core.exceptions import NON_FIELD_ERRORS @@ -55,7 +55,7 @@ class BaseModelValidationTests(ValidationTestCase): def test_wrong_url_value_raises_error(self): mtv = ModelToValidate(number=10, name='Some Name', url='not a url') - self.assertFieldFailsValidationWithMessage(mtv.full_clean, 'url', [u'Enter a valid value.']) + self.assertFieldFailsValidationWithMessage(mtv.full_clean, 'url', ['Enter a valid value.']) def test_text_greater_that_charfields_max_length_raises_erros(self): mtv = ModelToValidate(number=10, name='Some Name'*100) diff --git a/tests/modeltests/validation/validators.py b/tests/modeltests/validation/validators.py index d82b95e3ad4..e58d9fd4a6e 100644 --- a/tests/modeltests/validation/validators.py +++ b/tests/modeltests/validation/validators.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from . import ValidationTestCase from .models import ModelToValidate @@ -15,5 +15,5 @@ class TestModelsWithValidators(ValidationTestCase): self.assertFieldFailsValidationWithMessage( mtv.full_clean, 'f_with_custom_validator', - [u'This is not the answer to life, universe and everything!'] + ['This is not the answer to life, universe and everything!'] ) diff --git a/tests/modeltests/validators/tests.py b/tests/modeltests/validators/tests.py index a1a48bf97cc..018be6ae597 100644 --- a/tests/modeltests/validators/tests.py +++ b/tests/modeltests/validators/tests.py @@ -1,10 +1,13 @@ # -*- coding: utf-8 -*- +from __future__ import unicode_literals + import re import types from datetime import datetime, timedelta from django.core.exceptions import ValidationError from django.core.validators import * +from django.test.utils import str_prefix from django.utils.unittest import TestCase @@ -176,18 +179,18 @@ def create_simple_test_method(validator, expected, value, num): class TestSimpleValidators(TestCase): def test_single_message(self): v = ValidationError('Not Valid') - self.assertEqual(str(v), "[u'Not Valid']") - self.assertEqual(repr(v), "ValidationError([u'Not Valid'])") + self.assertEqual(str(v), str_prefix("[%(_)s'Not Valid']")) + self.assertEqual(repr(v), str_prefix("ValidationError([%(_)s'Not Valid'])")) def test_message_list(self): v = ValidationError(['First Problem', 'Second Problem']) - self.assertEqual(str(v), "[u'First Problem', u'Second Problem']") - self.assertEqual(repr(v), "ValidationError([u'First Problem', u'Second Problem'])") + self.assertEqual(str(v), str_prefix("[%(_)s'First Problem', %(_)s'Second Problem']")) + self.assertEqual(repr(v), str_prefix("ValidationError([%(_)s'First Problem', %(_)s'Second Problem'])")) def test_message_dict(self): v = ValidationError({'first': 'First Problem'}) - self.assertEqual(str(v), "{'first': 'First Problem'}") - self.assertEqual(repr(v), "ValidationError({'first': 'First Problem'})") + self.assertEqual(str(v), str_prefix("{%(_)s'first': %(_)s'First Problem'}")) + self.assertEqual(repr(v), str_prefix("ValidationError({%(_)s'first': %(_)s'First Problem'})")) test_counter = 0 for validator, value, expected in TEST_DATA: diff --git a/tests/regressiontests/admin_custom_urls/tests.py b/tests/regressiontests/admin_custom_urls/tests.py index 61978277930..4a6235e7d53 100644 --- a/tests/regressiontests/admin_custom_urls/tests.py +++ b/tests/regressiontests/admin_custom_urls/tests.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from django.core.urlresolvers import reverse from django.template.response import TemplateResponse @@ -39,9 +39,9 @@ class AdminCustomUrlsTest(TestCase): A smoke test to ensure POST on add_view works. """ post_data = { - '_popup': u'1', - "name": u'Action added through a popup', - "description": u"Description of added action", + '_popup': '1', + "name": 'Action added through a popup', + "description": "Description of added action", } response = self.client.post('/custom_urls/admin/admin_custom_urls/action/!add/', post_data) self.assertEqual(response.status_code, 200) diff --git a/tests/regressiontests/admin_filters/models.py b/tests/regressiontests/admin_filters/models.py index deb8ee88c35..371c67061f2 100644 --- a/tests/regressiontests/admin_filters/models.py +++ b/tests/regressiontests/admin_filters/models.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.contrib.auth.models import User from django.db import models @@ -9,7 +11,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=u'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 __unicode__(self): return self.title @@ -27,4 +29,4 @@ class Employee(models.Model): name = models.CharField(max_length=100) def __unicode__(self): - return self.name \ No newline at end of file + return self.name diff --git a/tests/regressiontests/admin_filters/tests.py b/tests/regressiontests/admin_filters/tests.py index 8c9788b9855..72cc5d7ee5c 100644 --- a/tests/regressiontests/admin_filters/tests.py +++ b/tests/regressiontests/admin_filters/tests.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import datetime @@ -160,7 +160,7 @@ class ListFiltersTests(TestCase): # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][4] - self.assertEqual(force_unicode(filterspec.title), u'date registered') + self.assertEqual(force_unicode(filterspec.title), 'date registered') choice = select_by(filterspec.choices(changelist), "display", "Today") self.assertEqual(choice['selected'], True) self.assertEqual(choice['query_string'], '?date_registered__gte=%s' @@ -181,7 +181,7 @@ class ListFiltersTests(TestCase): # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][4] - self.assertEqual(force_unicode(filterspec.title), u'date registered') + self.assertEqual(force_unicode(filterspec.title), 'date registered') choice = select_by(filterspec.choices(changelist), "display", "This month") self.assertEqual(choice['selected'], True) self.assertEqual(choice['query_string'], '?date_registered__gte=%s' @@ -202,7 +202,7 @@ class ListFiltersTests(TestCase): # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][4] - self.assertEqual(force_unicode(filterspec.title), u'date registered') + self.assertEqual(force_unicode(filterspec.title), 'date registered') choice = select_by(filterspec.choices(changelist), "display", "This year") self.assertEqual(choice['selected'], True) self.assertEqual(choice['query_string'], '?date_registered__gte=%s' @@ -219,7 +219,7 @@ class ListFiltersTests(TestCase): # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][4] - self.assertEqual(force_unicode(filterspec.title), u'date registered') + self.assertEqual(force_unicode(filterspec.title), 'date registered') choice = select_by(filterspec.choices(changelist), "display", "Past 7 days") self.assertEqual(choice['selected'], True) self.assertEqual(choice['query_string'], '?date_registered__gte=%s' @@ -243,7 +243,7 @@ class ListFiltersTests(TestCase): # Make sure the last choice is None and is selected filterspec = changelist.get_filters(request)[0][0] - self.assertEqual(force_unicode(filterspec.title), u'year') + self.assertEqual(force_unicode(filterspec.title), 'year') choices = list(filterspec.choices(changelist)) self.assertEqual(choices[-1]['selected'], True) self.assertEqual(choices[-1]['query_string'], '?year__isnull=True') @@ -253,7 +253,7 @@ class ListFiltersTests(TestCase): # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][0] - self.assertEqual(force_unicode(filterspec.title), u'year') + self.assertEqual(force_unicode(filterspec.title), 'year') choices = list(filterspec.choices(changelist)) self.assertEqual(choices[2]['selected'], True) self.assertEqual(choices[2]['query_string'], '?year=2002') @@ -270,7 +270,7 @@ class ListFiltersTests(TestCase): # Make sure the last choice is None and is selected filterspec = changelist.get_filters(request)[0][1] - self.assertEqual(force_unicode(filterspec.title), u'Verbose Author') + self.assertEqual(force_unicode(filterspec.title), 'Verbose Author') choices = list(filterspec.choices(changelist)) self.assertEqual(choices[-1]['selected'], True) self.assertEqual(choices[-1]['query_string'], '?author__isnull=True') @@ -280,7 +280,7 @@ class ListFiltersTests(TestCase): # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][1] - self.assertEqual(force_unicode(filterspec.title), u'Verbose Author') + self.assertEqual(force_unicode(filterspec.title), 'Verbose Author') # order of choices depends on User model, which has no order choice = select_by(filterspec.choices(changelist), "display", "alfred") self.assertEqual(choice['selected'], True) @@ -298,7 +298,7 @@ class ListFiltersTests(TestCase): # Make sure the last choice is None and is selected filterspec = changelist.get_filters(request)[0][2] - self.assertEqual(force_unicode(filterspec.title), u'Verbose Contributors') + self.assertEqual(force_unicode(filterspec.title), 'Verbose Contributors') choices = list(filterspec.choices(changelist)) self.assertEqual(choices[-1]['selected'], True) self.assertEqual(choices[-1]['query_string'], '?contributors__isnull=True') @@ -308,7 +308,7 @@ class ListFiltersTests(TestCase): # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][2] - self.assertEqual(force_unicode(filterspec.title), u'Verbose Contributors') + self.assertEqual(force_unicode(filterspec.title), 'Verbose Contributors') choice = select_by(filterspec.choices(changelist), "display", "bob") self.assertEqual(choice['selected'], True) self.assertEqual(choice['query_string'], '?contributors__id__exact=%d' % self.bob.pk) @@ -326,7 +326,7 @@ class ListFiltersTests(TestCase): # Make sure the last choice is None and is selected filterspec = changelist.get_filters(request)[0][0] - self.assertEqual(force_unicode(filterspec.title), u'book') + self.assertEqual(force_unicode(filterspec.title), 'book') choices = list(filterspec.choices(changelist)) self.assertEqual(choices[-1]['selected'], True) self.assertEqual(choices[-1]['query_string'], '?books_authored__isnull=True') @@ -336,7 +336,7 @@ class ListFiltersTests(TestCase): # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][0] - self.assertEqual(force_unicode(filterspec.title), u'book') + self.assertEqual(force_unicode(filterspec.title), 'book') choice = select_by(filterspec.choices(changelist), "display", self.bio_book.title) self.assertEqual(choice['selected'], True) self.assertEqual(choice['query_string'], '?books_authored__id__exact=%d' % self.bio_book.pk) @@ -351,7 +351,7 @@ class ListFiltersTests(TestCase): # Make sure the last choice is None and is selected filterspec = changelist.get_filters(request)[0][1] - self.assertEqual(force_unicode(filterspec.title), u'book') + self.assertEqual(force_unicode(filterspec.title), 'book') choices = list(filterspec.choices(changelist)) self.assertEqual(choices[-1]['selected'], True) self.assertEqual(choices[-1]['query_string'], '?books_contributed__isnull=True') @@ -361,7 +361,7 @@ class ListFiltersTests(TestCase): # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][1] - self.assertEqual(force_unicode(filterspec.title), u'book') + self.assertEqual(force_unicode(filterspec.title), 'book') choice = select_by(filterspec.choices(changelist), "display", self.django_book.title) self.assertEqual(choice['selected'], True) self.assertEqual(choice['query_string'], '?books_contributed__id__exact=%d' % self.django_book.pk) @@ -387,7 +387,7 @@ class ListFiltersTests(TestCase): # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][3] - self.assertEqual(force_unicode(filterspec.title), u'is best seller') + self.assertEqual(force_unicode(filterspec.title), 'is best seller') choice = select_by(filterspec.choices(changelist), "display", "No") self.assertEqual(choice['selected'], True) self.assertEqual(choice['query_string'], '?is_best_seller__exact=0') @@ -401,7 +401,7 @@ class ListFiltersTests(TestCase): # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][3] - self.assertEqual(force_unicode(filterspec.title), u'is best seller') + self.assertEqual(force_unicode(filterspec.title), 'is best seller') choice = select_by(filterspec.choices(changelist), "display", "Yes") self.assertEqual(choice['selected'], True) self.assertEqual(choice['query_string'], '?is_best_seller__exact=1') @@ -415,7 +415,7 @@ class ListFiltersTests(TestCase): # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][3] - self.assertEqual(force_unicode(filterspec.title), u'is best seller') + self.assertEqual(force_unicode(filterspec.title), 'is best seller') choice = select_by(filterspec.choices(changelist), "display", "Unknown") self.assertEqual(choice['selected'], True) self.assertEqual(choice['query_string'], '?is_best_seller__isnull=True') @@ -434,9 +434,9 @@ class ListFiltersTests(TestCase): # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][1] - self.assertEqual(force_unicode(filterspec.title), u'publication decade') + self.assertEqual(force_unicode(filterspec.title), 'publication decade') choices = list(filterspec.choices(changelist)) - self.assertEqual(choices[0]['display'], u'All') + self.assertEqual(choices[0]['display'], 'All') self.assertEqual(choices[0]['selected'], True) self.assertEqual(choices[0]['query_string'], '?') @@ -451,9 +451,9 @@ class ListFiltersTests(TestCase): # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][1] - self.assertEqual(force_unicode(filterspec.title), u'publication decade') + self.assertEqual(force_unicode(filterspec.title), 'publication decade') choices = list(filterspec.choices(changelist)) - self.assertEqual(choices[1]['display'], u'the 1980\'s') + self.assertEqual(choices[1]['display'], 'the 1980\'s') self.assertEqual(choices[1]['selected'], True) self.assertEqual(choices[1]['query_string'], '?publication-decade=the+80s') @@ -468,9 +468,9 @@ class ListFiltersTests(TestCase): # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][1] - self.assertEqual(force_unicode(filterspec.title), u'publication decade') + self.assertEqual(force_unicode(filterspec.title), 'publication decade') choices = list(filterspec.choices(changelist)) - self.assertEqual(choices[2]['display'], u'the 1990\'s') + self.assertEqual(choices[2]['display'], 'the 1990\'s') self.assertEqual(choices[2]['selected'], True) self.assertEqual(choices[2]['query_string'], '?publication-decade=the+90s') @@ -485,9 +485,9 @@ class ListFiltersTests(TestCase): # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][1] - self.assertEqual(force_unicode(filterspec.title), u'publication decade') + self.assertEqual(force_unicode(filterspec.title), 'publication decade') choices = list(filterspec.choices(changelist)) - self.assertEqual(choices[3]['display'], u'the 2000\'s') + self.assertEqual(choices[3]['display'], 'the 2000\'s') self.assertEqual(choices[3]['selected'], True) self.assertEqual(choices[3]['query_string'], '?publication-decade=the+00s') @@ -502,14 +502,14 @@ class ListFiltersTests(TestCase): # Make sure the correct choices are selected filterspec = changelist.get_filters(request)[0][1] - self.assertEqual(force_unicode(filterspec.title), u'publication decade') + self.assertEqual(force_unicode(filterspec.title), 'publication decade') choices = list(filterspec.choices(changelist)) - self.assertEqual(choices[3]['display'], u'the 2000\'s') + self.assertEqual(choices[3]['display'], 'the 2000\'s') self.assertEqual(choices[3]['selected'], True) self.assertEqual(choices[3]['query_string'], '?publication-decade=the+00s&author__id__exact=%s' % self.alfred.pk) filterspec = changelist.get_filters(request)[0][0] - self.assertEqual(force_unicode(filterspec.title), u'Verbose Author') + self.assertEqual(force_unicode(filterspec.title), 'Verbose Author') choice = select_by(filterspec.choices(changelist), "display", "alfred") self.assertEqual(choice['selected'], True) self.assertEqual(choice['query_string'], '?publication-decade=the+00s&author__id__exact=%s' % self.alfred.pk) @@ -561,19 +561,19 @@ class ListFiltersTests(TestCase): changelist = self.get_changelist(request, Book, modeladmin) filterspec = changelist.get_filters(request)[0][0] - self.assertEqual(force_unicode(filterspec.title), u'publication decade') + self.assertEqual(force_unicode(filterspec.title), 'publication decade') choices = list(filterspec.choices(changelist)) self.assertEqual(len(choices), 3) - self.assertEqual(choices[0]['display'], u'All') + self.assertEqual(choices[0]['display'], 'All') self.assertEqual(choices[0]['selected'], True) self.assertEqual(choices[0]['query_string'], '?') - self.assertEqual(choices[1]['display'], u'the 1990\'s') + self.assertEqual(choices[1]['display'], 'the 1990\'s') self.assertEqual(choices[1]['selected'], False) self.assertEqual(choices[1]['query_string'], '?publication-decade=the+90s') - self.assertEqual(choices[2]['display'], u'the 2000\'s') + self.assertEqual(choices[2]['display'], 'the 2000\'s') self.assertEqual(choices[2]['selected'], False) self.assertEqual(choices[2]['query_string'], '?publication-decade=the+00s') @@ -591,7 +591,7 @@ class ListFiltersTests(TestCase): self.assertEqual(list(queryset), [self.bio_book]) filterspec = changelist.get_filters(request)[0][-1] - self.assertEqual(force_unicode(filterspec.title), u'number') + self.assertEqual(force_unicode(filterspec.title), 'number') choices = list(filterspec.choices(changelist)) self.assertEqual(choices[2]['selected'], True) self.assertEqual(choices[2]['query_string'], '?no=207') @@ -614,9 +614,9 @@ class ListFiltersTests(TestCase): # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][0] - self.assertEqual(force_unicode(filterspec.title), u'publication decade') + self.assertEqual(force_unicode(filterspec.title), 'publication decade') choices = list(filterspec.choices(changelist)) - self.assertEqual(choices[2]['display'], u'the 1990\'s') + self.assertEqual(choices[2]['display'], 'the 1990\'s') self.assertEqual(choices[2]['selected'], True) self.assertEqual(choices[2]['query_string'], '?decade__in=the+90s') @@ -631,9 +631,9 @@ class ListFiltersTests(TestCase): # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][0] - self.assertEqual(force_unicode(filterspec.title), u'publication decade') + self.assertEqual(force_unicode(filterspec.title), 'publication decade') choices = list(filterspec.choices(changelist)) - self.assertEqual(choices[2]['display'], u'the 1990\'s') + self.assertEqual(choices[2]['display'], 'the 1990\'s') self.assertEqual(choices[2]['selected'], True) self.assertEqual(choices[2]['query_string'], '?decade__isnull=the+90s') @@ -657,18 +657,18 @@ class ListFiltersTests(TestCase): self.assertEqual(list(queryset), [jack, john]) filterspec = changelist.get_filters(request)[0][-1] - self.assertEqual(force_unicode(filterspec.title), u'department') + self.assertEqual(force_unicode(filterspec.title), 'department') choices = list(filterspec.choices(changelist)) - self.assertEqual(choices[0]['display'], u'All') + self.assertEqual(choices[0]['display'], 'All') self.assertEqual(choices[0]['selected'], True) self.assertEqual(choices[0]['query_string'], '?') - self.assertEqual(choices[1]['display'], u'Development') + self.assertEqual(choices[1]['display'], 'Development') self.assertEqual(choices[1]['selected'], False) self.assertEqual(choices[1]['query_string'], '?department__code__exact=DEV') - self.assertEqual(choices[2]['display'], u'Design') + self.assertEqual(choices[2]['display'], 'Design') self.assertEqual(choices[2]['selected'], False) self.assertEqual(choices[2]['query_string'], '?department__code__exact=DSN') @@ -682,17 +682,17 @@ class ListFiltersTests(TestCase): self.assertEqual(list(queryset), [john]) filterspec = changelist.get_filters(request)[0][-1] - self.assertEqual(force_unicode(filterspec.title), u'department') + self.assertEqual(force_unicode(filterspec.title), 'department') choices = list(filterspec.choices(changelist)) - self.assertEqual(choices[0]['display'], u'All') + self.assertEqual(choices[0]['display'], 'All') self.assertEqual(choices[0]['selected'], False) self.assertEqual(choices[0]['query_string'], '?') - self.assertEqual(choices[1]['display'], u'Development') + self.assertEqual(choices[1]['display'], 'Development') self.assertEqual(choices[1]['selected'], True) self.assertEqual(choices[1]['query_string'], '?department__code__exact=DEV') - self.assertEqual(choices[2]['display'], u'Design') + self.assertEqual(choices[2]['display'], 'Design') self.assertEqual(choices[2]['selected'], False) self.assertEqual(choices[2]['query_string'], '?department__code__exact=DSN') diff --git a/tests/regressiontests/admin_inlines/models.py b/tests/regressiontests/admin_inlines/models.py index f2add00288c..d7526d60205 100644 --- a/tests/regressiontests/admin_inlines/models.py +++ b/tests/regressiontests/admin_inlines/models.py @@ -2,6 +2,8 @@ Testing of admin inline formsets. """ +from __future__ import unicode_literals + from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic @@ -30,7 +32,7 @@ class Child(models.Model): parent = generic.GenericForeignKey() def __unicode__(self): - return u'I am %s, a child of %s' % (self.name, self.parent) + return 'I am %s, a child of %s' % (self.name, self.parent) class Book(models.Model): @@ -145,4 +147,4 @@ class ProfileCollection(models.Model): class Profile(models.Model): collection = models.ForeignKey(ProfileCollection, blank=True, null=True) first_name = models.CharField(max_length=100) - last_name = models.CharField(max_length=100) \ No newline at end of file + last_name = models.CharField(max_length=100) diff --git a/tests/regressiontests/admin_inlines/tests.py b/tests/regressiontests/admin_inlines/tests.py index 2cca67012f6..94790af56c0 100644 --- a/tests/regressiontests/admin_inlines/tests.py +++ b/tests/regressiontests/admin_inlines/tests.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from django.contrib.admin.tests import AdminSeleniumWebDriverTestCase from django.contrib.admin.helpers import InlineAdminForm @@ -67,7 +67,7 @@ class TestInline(TestCase): 'shoppingweakness_set-TOTAL_FORMS': 1, 'shoppingweakness_set-INITIAL_FORMS': 0, 'shoppingweakness_set-MAX_NUM_FORMS': 0, - '_save': u'Save', + '_save': 'Save', 'person': person.id, 'max_weight': 0, 'shoppingweakness_set-0-item': item.id, @@ -85,7 +85,7 @@ class TestInline(TestCase): 'title_set-TOTAL_FORMS': 1, 'title_set-INITIAL_FORMS': 0, 'title_set-MAX_NUM_FORMS': 0, - '_save': u'Save', + '_save': 'Save', 'title_set-0-title1': 'a title', 'title_set-0-title2': 'a different title', } @@ -235,8 +235,8 @@ class TestInlinePermissions(TestCase): permission = Permission.objects.get(codename='change_holder2', content_type=self.holder_ct) self.user.user_permissions.add(permission) - author = Author.objects.create(pk=1, name=u'The Author') - book = author.books.create(name=u'The inline Book') + author = Author.objects.create(pk=1, name='The Author') + book = author.books.create(name='The inline Book') self.author_change_url = '/admin/admin_inlines/author/%i/' % author.id # Get the ID of the automatically created intermediate model for thw Author-Book m2m author_book_auto_m2m_intermediate = Author.books.through.objects.get(author=author, book=book) diff --git a/tests/regressiontests/admin_ordering/tests.py b/tests/regressiontests/admin_ordering/tests.py index b82f150f408..faae834f930 100644 --- a/tests/regressiontests/admin_ordering/tests.py +++ b/tests/regressiontests/admin_ordering/tests.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from django.test import TestCase, RequestFactory from django.contrib.admin.options import ModelAdmin @@ -42,7 +42,7 @@ class TestAdminOrdering(TestCase): """ ma = ModelAdmin(Band, None) names = [b.name for b in ma.queryset(request)] - self.assertEqual([u'Aerosmith', u'Radiohead', u'Van Halen'], names) + self.assertEqual(['Aerosmith', 'Radiohead', 'Van Halen'], names) def test_specified_ordering(self): """ @@ -53,7 +53,7 @@ class TestAdminOrdering(TestCase): ordering = ('rank',) # default ordering is ('name',) ma = BandAdmin(Band, None) names = [b.name for b in ma.queryset(request)] - self.assertEqual([u'Radiohead', u'Van Halen', u'Aerosmith'], names) + self.assertEqual(['Radiohead', 'Van Halen', 'Aerosmith'], names) def test_dynamic_ordering(self): """ @@ -65,10 +65,10 @@ class TestAdminOrdering(TestCase): request.user = super_user ma = DynOrderingBandAdmin(Band, None) names = [b.name for b in ma.queryset(request)] - self.assertEqual([u'Radiohead', u'Van Halen', u'Aerosmith'], names) + self.assertEqual(['Radiohead', 'Van Halen', 'Aerosmith'], names) request.user = other_user names = [b.name for b in ma.queryset(request)] - self.assertEqual([u'Aerosmith', u'Radiohead', u'Van Halen'], names) + self.assertEqual(['Aerosmith', 'Radiohead', 'Van Halen'], names) class TestInlineModelAdminOrdering(TestCase): @@ -95,7 +95,7 @@ class TestInlineModelAdminOrdering(TestCase): """ inline = SongInlineDefaultOrdering(self.b, None) names = [s.name for s in inline.queryset(request)] - self.assertEqual([u'Dude (Looks Like a Lady)', u'Jaded', u'Pink'], names) + self.assertEqual(['Dude (Looks Like a Lady)', 'Jaded', 'Pink'], names) def test_specified_ordering(self): """ @@ -103,4 +103,4 @@ class TestInlineModelAdminOrdering(TestCase): """ inline = SongInlineNewOrdering(self.b, None) names = [s.name for s in inline.queryset(request)] - self.assertEqual([u'Jaded', u'Pink', u'Dude (Looks Like a Lady)'], names) + self.assertEqual(['Jaded', 'Pink', 'Dude (Looks Like a Lady)'], names) diff --git a/tests/regressiontests/admin_util/tests.py b/tests/regressiontests/admin_util/tests.py index 055f494dcd5..ba2be363ca6 100644 --- a/tests/regressiontests/admin_util/tests.py +++ b/tests/regressiontests/admin_util/tests.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from datetime import datetime @@ -138,7 +138,7 @@ class UtilTests(unittest.TestCase): # Regression test for #13071: NullBooleanField has special # handling. display_value = display_for_field(None, models.NullBooleanField()) - expected = u'None' % settings.STATIC_URL + expected = 'None' % settings.STATIC_URL self.assertEqual(display_value, expected) display_value = display_for_field(None, models.DecimalField()) diff --git a/tests/regressiontests/admin_views/admin.py b/tests/regressiontests/admin_views/admin.py index d9607496c3b..01a19e63735 100644 --- a/tests/regressiontests/admin_views/admin.py +++ b/tests/regressiontests/admin_views/admin.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import tempfile import os @@ -171,12 +171,12 @@ class PersonAdmin(admin.ModelAdmin): class FooAccount(Account): """A service-specific account of type Foo.""" - servicename = u'foo' + servicename = 'foo' class BarAccount(Account): """A service-specific account of type Bar.""" - servicename = u'bar' + servicename = 'bar' class FooAccountAdmin(admin.StackedInline): diff --git a/tests/regressiontests/admin_views/models.py b/tests/regressiontests/admin_views/models.py index 17533f9f800..5aa775656bc 100644 --- a/tests/regressiontests/admin_views/models.py +++ b/tests/regressiontests/admin_views/models.py @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*- +from __future__ import unicode_literals + import datetime import tempfile import os @@ -40,14 +42,14 @@ class Book(models.Model): """ A simple book that has chapters. """ - name = models.CharField(max_length=100, verbose_name=u'¿Name?') + name = models.CharField(max_length=100, verbose_name='¿Name?') def __unicode__(self): return self.name class Promo(models.Model): - name = models.CharField(max_length=100, verbose_name=u'¿Name?') + name = models.CharField(max_length=100, verbose_name='¿Name?') book = models.ForeignKey(Book) def __unicode__(self): @@ -55,7 +57,7 @@ class Promo(models.Model): class Chapter(models.Model): - title = models.CharField(max_length=100, verbose_name=u'¿Title?') + title = models.CharField(max_length=100, verbose_name='¿Title?') content = models.TextField() book = models.ForeignKey(Book) @@ -68,19 +70,19 @@ class Chapter(models.Model): class ChapterXtra1(models.Model): - chap = models.OneToOneField(Chapter, verbose_name=u'¿Chap?') - xtra = models.CharField(max_length=100, verbose_name=u'¿Xtra?') + chap = models.OneToOneField(Chapter, verbose_name='¿Chap?') + xtra = models.CharField(max_length=100, verbose_name='¿Xtra?') def __unicode__(self): - return u'¿Xtra1: %s' % self.xtra + return '¿Xtra1: %s' % self.xtra class ChapterXtra2(models.Model): - chap = models.OneToOneField(Chapter, verbose_name=u'¿Chap?') - xtra = models.CharField(max_length=100, verbose_name=u'¿Xtra?') + chap = models.OneToOneField(Chapter, verbose_name='¿Chap?') + xtra = models.CharField(max_length=100, verbose_name='¿Xtra?') def __unicode__(self): - return u'¿Xtra2: %s' % self.xtra + return '¿Xtra2: %s' % self.xtra class RowLevelChangePermissionModel(models.Model): @@ -130,7 +132,7 @@ class Inquisition(models.Model): country = models.CharField(max_length=20) def __unicode__(self): - return u"by %s from %s" % (self.leader, self.country) + return "by %s from %s" % (self.leader, self.country) class Sketch(models.Model): @@ -187,7 +189,7 @@ class Account(models.Model): """ username = models.CharField(blank=False, max_length=80) persona = models.ForeignKey(Persona, related_name="accounts") - servicename = u'generic service' + servicename = 'generic service' def __unicode__(self): return "%s: %s" % (self.servicename, self.username) @@ -195,12 +197,12 @@ class Account(models.Model): class FooAccount(Account): """A service-specific account of type Foo.""" - servicename = u'foo' + servicename = 'foo' class BarAccount(Account): """A service-specific account of type Bar.""" - servicename = u'bar' + servicename = 'bar' class Subscriber(models.Model): @@ -335,7 +337,7 @@ class Category(models.Model): ordering = ('order',) def __unicode__(self): - return u'%s:o%s' % (self.id, self.order) + return '%s:o%s' % (self.id, self.order) class Link(models.Model): @@ -493,14 +495,14 @@ class Reservation(models.Model): DRIVER_CHOICES = ( - (u'bill', 'Bill G'), - (u'steve', 'Steve J'), + ('bill', 'Bill G'), + ('steve', 'Steve J'), ) RESTAURANT_CHOICES = ( - (u'indian', u'A Taste of India'), - (u'thai', u'Thai Pography'), - (u'pizza', u'Pizza Mama'), + ('indian', 'A Taste of India'), + ('thai', 'Thai Pography'), + ('pizza', 'Pizza Mama'), ) diff --git a/tests/regressiontests/admin_views/tests.py b/tests/regressiontests/admin_views/tests.py index f9a9b151145..e220011fdc4 100644 --- a/tests/regressiontests/admin_views/tests.py +++ b/tests/regressiontests/admin_views/tests.py @@ -1,5 +1,5 @@ # coding: utf-8 -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import os import re @@ -119,11 +119,11 @@ class AdminViewBasicTest(TestCase): A smoke test to ensure POST on add_view works. """ post_data = { - "name": u"Another Section", + "name": "Another Section", # inline data - "article_set-TOTAL_FORMS": u"3", - "article_set-INITIAL_FORMS": u"0", - "article_set-MAX_NUM_FORMS": u"0", + "article_set-TOTAL_FORMS": "3", + "article_set-INITIAL_FORMS": "0", + "article_set-MAX_NUM_FORMS": "0", } response = self.client.post('/test_admin/%s/admin_views/section/add/' % self.urlbit, post_data) self.assertEqual(response.status_code, 302) # redirect somewhere @@ -133,56 +133,56 @@ class AdminViewBasicTest(TestCase): Ensure http response from a popup is properly escaped. """ post_data = { - '_popup': u'1', - 'title': u'title with a new\nline', - 'content': u'some content', - 'date_0': u'2010-09-10', - 'date_1': u'14:55:39', + '_popup': '1', + 'title': 'title with a new\nline', + 'content': 'some content', + 'date_0': '2010-09-10', + 'date_1': '14:55:39', } response = self.client.post('/test_admin/%s/admin_views/article/add/' % self.urlbit, post_data) self.assertEqual(response.status_code, 200) self.assertContains(response, 'dismissAddAnotherPopup') - self.assertContains(response, 'title with a new\u000Aline') + self.assertContains(response, 'title with a new\\u000Aline') # Post data for edit inline inline_post_data = { - "name": u"Test section", + "name": "Test section", # inline data - "article_set-TOTAL_FORMS": u"6", - "article_set-INITIAL_FORMS": u"3", - "article_set-MAX_NUM_FORMS": u"0", - "article_set-0-id": u"1", + "article_set-TOTAL_FORMS": "6", + "article_set-INITIAL_FORMS": "3", + "article_set-MAX_NUM_FORMS": "0", + "article_set-0-id": "1", # there is no title in database, give one here or formset will fail. - "article_set-0-title": u"Norske bostaver æøå skaper problemer", - "article_set-0-content": u"<p>Middle content</p>", - "article_set-0-date_0": u"2008-03-18", - "article_set-0-date_1": u"11:54:58", - "article_set-0-section": u"1", - "article_set-1-id": u"2", - "article_set-1-title": u"Need a title.", - "article_set-1-content": u"<p>Oldest content</p>", - "article_set-1-date_0": u"2000-03-18", - "article_set-1-date_1": u"11:54:58", - "article_set-2-id": u"3", - "article_set-2-title": u"Need a title.", - "article_set-2-content": u"<p>Newest content</p>", - "article_set-2-date_0": u"2009-03-18", - "article_set-2-date_1": u"11:54:58", - "article_set-3-id": u"", - "article_set-3-title": u"", - "article_set-3-content": u"", - "article_set-3-date_0": u"", - "article_set-3-date_1": u"", - "article_set-4-id": u"", - "article_set-4-title": u"", - "article_set-4-content": u"", - "article_set-4-date_0": u"", - "article_set-4-date_1": u"", - "article_set-5-id": u"", - "article_set-5-title": u"", - "article_set-5-content": u"", - "article_set-5-date_0": u"", - "article_set-5-date_1": u"", + "article_set-0-title": "Norske bostaver æøå skaper problemer", + "article_set-0-content": "<p>Middle content</p>", + "article_set-0-date_0": "2008-03-18", + "article_set-0-date_1": "11:54:58", + "article_set-0-section": "1", + "article_set-1-id": "2", + "article_set-1-title": "Need a title.", + "article_set-1-content": "<p>Oldest content</p>", + "article_set-1-date_0": "2000-03-18", + "article_set-1-date_1": "11:54:58", + "article_set-2-id": "3", + "article_set-2-title": "Need a title.", + "article_set-2-content": "<p>Newest content</p>", + "article_set-2-date_0": "2009-03-18", + "article_set-2-date_1": "11:54:58", + "article_set-3-id": "", + "article_set-3-title": "", + "article_set-3-content": "", + "article_set-3-date_0": "", + "article_set-3-date_1": "", + "article_set-4-id": "", + "article_set-4-title": "", + "article_set-4-content": "", + "article_set-4-date_0": "", + "article_set-4-date_1": "", + "article_set-5-id": "", + "article_set-5-title": "", + "article_set-5-content": "", + "article_set-5-date_0": "", + "article_set-5-date_1": "", } def testBasicEditPost(self): @@ -198,12 +198,12 @@ class AdminViewBasicTest(TestCase): """ post_data = self.inline_post_data.copy() post_data.update({ - '_saveasnew': u'Save+as+new', - "article_set-1-section": u"1", - "article_set-2-section": u"1", - "article_set-3-section": u"1", - "article_set-4-section": u"1", - "article_set-5-section": u"1", + '_saveasnew': 'Save+as+new', + "article_set-1-section": "1", + "article_set-2-section": "1", + "article_set-3-section": "1", + "article_set-4-section": "1", + "article_set-5-section": "1", }) response = self.client.post('/test_admin/%s/admin_views/section/1/' % self.urlbit, post_data) self.assertEqual(response.status_code, 302) # redirect somewhere @@ -1029,14 +1029,13 @@ class AdminViewPermissionsTest(TestCase): # one error in form should produce singular error message, multiple errors plural change_dict['title'] = '' post = self.client.post('/test_admin/admin/admin_views/article/1/', change_dict) - self.assertEqual(request.status_code, 200) - self.assertTrue('Please correct the error below.' in post.content, - 'Singular error message not found in response to post with one error.') + self.assertContains(post, 'Please correct the error below.', + msg_prefix='Singular error message not found in response to post with one error') + change_dict['content'] = '' post = self.client.post('/test_admin/admin/admin_views/article/1/', change_dict) - self.assertEqual(request.status_code, 200) - self.assertTrue('Please correct the errors below.' in post.content, - 'Plural error message not found in response to post with multiple errors.') + self.assertContains(post, 'Please correct the errors below.', + msg_prefix='Plural error message not found in response to post with multiple errors') self.client.get('/test_admin/admin/logout/') # Test redirection when using row-level change permissions. Refs #11513. @@ -1167,7 +1166,7 @@ class AdminViewPermissionsTest(TestCase): self.assertEqual(mail.outbox[0].subject, 'Greetings from a deleted object') article_ct = ContentType.objects.get_for_model(Article) logged = LogEntry.objects.get(content_type=article_ct, action_flag=DELETION) - self.assertEqual(logged.object_id, u'1') + self.assertEqual(logged.object_id, '1') self.client.get('/test_admin/admin/logout/') def testDisabledPermissionsWhenLoggedIn(self): @@ -1601,29 +1600,29 @@ class AdminViewUnicodeTest(TestCase): A test to ensure that POST on edit_view handles non-ascii characters. """ post_data = { - "name": u"Test lærdommer", + "name": "Test lærdommer", # inline data - "chapter_set-TOTAL_FORMS": u"6", - "chapter_set-INITIAL_FORMS": u"3", - "chapter_set-MAX_NUM_FORMS": u"0", - "chapter_set-0-id": u"1", - "chapter_set-0-title": u"Norske bostaver æøå skaper problemer", - "chapter_set-0-content": u"<p>Svært frustrerende med UnicodeDecodeError</p>", - "chapter_set-1-id": u"2", - "chapter_set-1-title": u"Kjærlighet.", - "chapter_set-1-content": u"<p>La kjærligheten til de lidende seire.</p>", - "chapter_set-2-id": u"3", - "chapter_set-2-title": u"Need a title.", - "chapter_set-2-content": u"<p>Newest content</p>", - "chapter_set-3-id": u"", - "chapter_set-3-title": u"", - "chapter_set-3-content": u"", - "chapter_set-4-id": u"", - "chapter_set-4-title": u"", - "chapter_set-4-content": u"", - "chapter_set-5-id": u"", - "chapter_set-5-title": u"", - "chapter_set-5-content": u"", + "chapter_set-TOTAL_FORMS": "6", + "chapter_set-INITIAL_FORMS": "3", + "chapter_set-MAX_NUM_FORMS": "0", + "chapter_set-0-id": "1", + "chapter_set-0-title": "Norske bostaver æøå skaper problemer", + "chapter_set-0-content": "<p>Svært frustrerende med UnicodeDecodeError</p>", + "chapter_set-1-id": "2", + "chapter_set-1-title": "Kjærlighet.", + "chapter_set-1-content": "<p>La kjærligheten til de lidende seire.</p>", + "chapter_set-2-id": "3", + "chapter_set-2-title": "Need a title.", + "chapter_set-2-content": "<p>Newest content</p>", + "chapter_set-3-id": "", + "chapter_set-3-title": "", + "chapter_set-3-content": "", + "chapter_set-4-id": "", + "chapter_set-4-title": "", + "chapter_set-4-content": "", + "chapter_set-5-id": "", + "chapter_set-5-title": "", + "chapter_set-5-content": "", } response = self.client.post('/test_admin/admin/admin_views/book/1/', post_data) @@ -1940,8 +1939,8 @@ class AdminViewListEditable(TestCase): "form-2-id": "3", "index": "0", - "_selected_action": [u'3'], - "action": [u'', u'delete_selected'], + "_selected_action": ['3'], + "action": ['', 'delete_selected'], } self.client.post('/test_admin/admin/admin_views/person/', data) @@ -1967,8 +1966,8 @@ class AdminViewListEditable(TestCase): "form-2-id": "3", "_save": "Save", - "_selected_action": [u'1'], - "action": [u'', u'delete_selected'], + "_selected_action": ['1'], + "action": ['', 'delete_selected'], } self.client.post('/test_admin/admin/admin_views/person/', data) @@ -2077,8 +2076,8 @@ class AdminInheritedInlinesTest(TestCase): def testInline(self): "Ensure that inline models which inherit from a common parent are correctly handled by admin." - foo_user = u"foo username" - bar_user = u"bar username" + foo_user = "foo username" + bar_user = "bar username" name_re = re.compile('name="(.*?)"') @@ -2090,15 +2089,15 @@ class AdminInheritedInlinesTest(TestCase): # test the add case post_data = { - "name": u"Test Name", + "name": "Test Name", # inline data - "accounts-TOTAL_FORMS": u"1", - "accounts-INITIAL_FORMS": u"0", - "accounts-MAX_NUM_FORMS": u"0", + "accounts-TOTAL_FORMS": "1", + "accounts-INITIAL_FORMS": "0", + "accounts-MAX_NUM_FORMS": "0", "accounts-0-username": foo_user, - "accounts-2-TOTAL_FORMS": u"1", - "accounts-2-INITIAL_FORMS": u"0", - "accounts-2-MAX_NUM_FORMS": u"0", + "accounts-2-TOTAL_FORMS": "1", + "accounts-2-INITIAL_FORMS": "0", + "accounts-2-MAX_NUM_FORMS": "0", "accounts-2-0-username": bar_user, } @@ -2123,19 +2122,19 @@ class AdminInheritedInlinesTest(TestCase): self.assertEqual(len(names), len(set(names))) post_data = { - "name": u"Test Name", + "name": "Test Name", "accounts-TOTAL_FORMS": "2", - "accounts-INITIAL_FORMS": u"1", - "accounts-MAX_NUM_FORMS": u"0", + "accounts-INITIAL_FORMS": "1", + "accounts-MAX_NUM_FORMS": "0", "accounts-0-username": "%s-1" % foo_user, "accounts-0-account_ptr": str(foo_id), "accounts-0-persona": str(persona_id), - "accounts-2-TOTAL_FORMS": u"2", - "accounts-2-INITIAL_FORMS": u"1", - "accounts-2-MAX_NUM_FORMS": u"0", + "accounts-2-TOTAL_FORMS": "2", + "accounts-2-INITIAL_FORMS": "1", + "accounts-2-MAX_NUM_FORMS": "0", "accounts-2-0-username": "%s-1" % bar_user, "accounts-2-0-account_ptr": str(bar_id), @@ -2387,7 +2386,7 @@ class TestCustomChangeList(TestCase): Validate that a custom ChangeList class can be used (#9749) """ # Insert some data - post_data = {"name": u"First Gadget"} + post_data = {"name": "First Gadget"} response = self.client.post('/test_admin/%s/admin_views/gadget/add/' % self.urlbit, post_data) self.assertEqual(response.status_code, 302) # redirect somewhere # Hit the page once to get messages out of the queue message list @@ -2444,12 +2443,12 @@ class AdminCustomQuerysetTest(TestCase): def test_add_model_modeladmin_only_qs(self): # only() is used in ModelAdmin.queryset() - p = Paper.objects.create(title=u"My Paper Title") + p = Paper.objects.create(title="My Paper Title") self.assertEqual(Paper.objects.count(), 1) response = self.client.get('/test_admin/admin/admin_views/paper/%s/' % p.pk) self.assertEqual(response.status_code, 200) post_data = { - "title": u"My Modified Paper Title", + "title": "My Modified Paper Title", "_save": "Save", } response = self.client.post('/test_admin/admin/admin_views/paper/%s/' % p.pk, @@ -2459,12 +2458,12 @@ class AdminCustomQuerysetTest(TestCase): self.assertContains(response, '
      • The paper "Paper_Deferred_author object" was changed successfully.
      • ', html=True) # defer() is used in ModelAdmin.queryset() - cl = CoverLetter.objects.create(author=u"John Doe") + cl = CoverLetter.objects.create(author="John Doe") self.assertEqual(CoverLetter.objects.count(), 1) response = self.client.get('/test_admin/admin/admin_views/coverletter/%s/' % cl.pk) self.assertEqual(response.status_code, 200) post_data = { - "author": u"John Doe II", + "author": "John Doe II", "_save": "Save", } response = self.client.post('/test_admin/admin/admin_views/coverletter/%s/' % cl.pk, @@ -2503,10 +2502,10 @@ class AdminInlineFileUploadTest(TestCase): Test that inline file uploads correctly display prior data (#10002). """ post_data = { - "name": u"Test Gallery", - "pictures-TOTAL_FORMS": u"2", - "pictures-INITIAL_FORMS": u"1", - "pictures-MAX_NUM_FORMS": u"0", + "name": "Test Gallery", + "pictures-TOTAL_FORMS": "2", + "pictures-INITIAL_FORMS": "1", + "pictures-MAX_NUM_FORMS": "0", "pictures-0-id": unicode(self.picture.id), "pictures-0-gallery": unicode(self.gallery.id), "pictures-0-name": "Test Picture", @@ -2527,11 +2526,11 @@ class AdminInlineTests(TestCase): def setUp(self): self.post_data = { - "name": u"Test Name", + "name": "Test Name", "widget_set-TOTAL_FORMS": "3", - "widget_set-INITIAL_FORMS": u"0", - "widget_set-MAX_NUM_FORMS": u"0", + "widget_set-INITIAL_FORMS": "0", + "widget_set-MAX_NUM_FORMS": "0", "widget_set-0-id": "", "widget_set-0-owner": "1", "widget_set-0-name": "", @@ -2543,8 +2542,8 @@ class AdminInlineTests(TestCase): "widget_set-2-name": "", "doohickey_set-TOTAL_FORMS": "3", - "doohickey_set-INITIAL_FORMS": u"0", - "doohickey_set-MAX_NUM_FORMS": u"0", + "doohickey_set-INITIAL_FORMS": "0", + "doohickey_set-MAX_NUM_FORMS": "0", "doohickey_set-0-owner": "1", "doohickey_set-0-code": "", "doohickey_set-0-name": "", @@ -2556,8 +2555,8 @@ class AdminInlineTests(TestCase): "doohickey_set-2-name": "", "grommet_set-TOTAL_FORMS": "3", - "grommet_set-INITIAL_FORMS": u"0", - "grommet_set-MAX_NUM_FORMS": u"0", + "grommet_set-INITIAL_FORMS": "0", + "grommet_set-MAX_NUM_FORMS": "0", "grommet_set-0-code": "", "grommet_set-0-owner": "1", "grommet_set-0-name": "", @@ -2569,8 +2568,8 @@ class AdminInlineTests(TestCase): "grommet_set-2-name": "", "whatsit_set-TOTAL_FORMS": "3", - "whatsit_set-INITIAL_FORMS": u"0", - "whatsit_set-MAX_NUM_FORMS": u"0", + "whatsit_set-INITIAL_FORMS": "0", + "whatsit_set-MAX_NUM_FORMS": "0", "whatsit_set-0-owner": "1", "whatsit_set-0-index": "", "whatsit_set-0-name": "", @@ -2582,8 +2581,8 @@ class AdminInlineTests(TestCase): "whatsit_set-2-name": "", "fancydoodad_set-TOTAL_FORMS": "3", - "fancydoodad_set-INITIAL_FORMS": u"0", - "fancydoodad_set-MAX_NUM_FORMS": u"0", + "fancydoodad_set-INITIAL_FORMS": "0", + "fancydoodad_set-MAX_NUM_FORMS": "0", "fancydoodad_set-0-doodad_ptr": "", "fancydoodad_set-0-owner": "1", "fancydoodad_set-0-name": "", @@ -2969,7 +2968,7 @@ class SeleniumPrePopulatedFirefoxTests(AdminSeleniumWebDriverTestCase): # Main form ---------------------------------------------------------- self.selenium.find_element_by_css_selector('#id_pubdate').send_keys('2012-02-18') self.get_select_option('#id_status', 'option two').click() - self.selenium.find_element_by_css_selector('#id_name').send_keys(u' this is the mAin nÀMë and it\'s awεšome') + self.selenium.find_element_by_css_selector('#id_name').send_keys(' this is the mAin nÀMë and it\'s awεšome') slug1 = self.selenium.find_element_by_css_selector('#id_slug1').get_attribute('value') slug2 = self.selenium.find_element_by_css_selector('#id_slug2').get_attribute('value') self.assertEqual(slug1, 'main-name-and-its-awesome-2012-02-18') @@ -2979,7 +2978,7 @@ class SeleniumPrePopulatedFirefoxTests(AdminSeleniumWebDriverTestCase): # Initial inline self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-0-pubdate').send_keys('2011-12-17') self.get_select_option('#id_relatedprepopulated_set-0-status', 'option one').click() - self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-0-name').send_keys(u' here is a sŤāÇkeð inline ! ') + self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-0-name').send_keys(' here is a sŤāÇkeð inline ! ') slug1 = self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-0-slug1').get_attribute('value') slug2 = self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-0-slug2').get_attribute('value') self.assertEqual(slug1, 'here-stacked-inline-2011-12-17') @@ -2989,7 +2988,7 @@ class SeleniumPrePopulatedFirefoxTests(AdminSeleniumWebDriverTestCase): self.selenium.find_elements_by_link_text('Add another Related Prepopulated')[0].click() self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-1-pubdate').send_keys('1999-01-25') self.get_select_option('#id_relatedprepopulated_set-1-status', 'option two').click() - self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-1-name').send_keys(u' now you haVe anöther sŤāÇkeð inline with a very ... loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooog text... ') + self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-1-name').send_keys(' now you haVe anöther sŤāÇkeð inline with a very ... loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooog text... ') slug1 = self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-1-slug1').get_attribute('value') slug2 = self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-1-slug2').get_attribute('value') self.assertEqual(slug1, 'now-you-have-another-stacked-inline-very-loooooooo') # 50 characters maximum for slug1 field @@ -2999,7 +2998,7 @@ class SeleniumPrePopulatedFirefoxTests(AdminSeleniumWebDriverTestCase): # Initial inline self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-2-0-pubdate').send_keys('1234-12-07') self.get_select_option('#id_relatedprepopulated_set-2-0-status', 'option two').click() - self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-2-0-name').send_keys(u'And now, with a tÃbűlaŘ inline !!!') + self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-2-0-name').send_keys('And now, with a tÃbűlaŘ inline !!!') slug1 = self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-2-0-slug1').get_attribute('value') slug2 = self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-2-0-slug2').get_attribute('value') self.assertEqual(slug1, 'and-now-tabular-inline-1234-12-07') @@ -3009,7 +3008,7 @@ class SeleniumPrePopulatedFirefoxTests(AdminSeleniumWebDriverTestCase): self.selenium.find_elements_by_link_text('Add another Related Prepopulated')[1].click() self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-2-1-pubdate').send_keys('1981-08-22') self.get_select_option('#id_relatedprepopulated_set-2-1-status', 'option one').click() - self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-2-1-name').send_keys(u'a tÃbűlaŘ inline with ignored ;"&*^\%$#@-/`~ characters') + self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-2-1-name').send_keys('a tÃbűlaŘ inline with ignored ;"&*^\%$#@-/`~ characters') slug1 = self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-2-1-slug1').get_attribute('value') slug2 = self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-2-1-slug2').get_attribute('value') self.assertEqual(slug1, 'tabular-inline-ignored-characters-1981-08-22') @@ -3029,7 +3028,7 @@ class SeleniumPrePopulatedFirefoxTests(AdminSeleniumWebDriverTestCase): self.assertEqual(MainPrepopulated.objects.all().count(), 1) MainPrepopulated.objects.get( - name=u' this is the mAin nÀMë and it\'s awεšome', + name=' this is the mAin nÀMë and it\'s awεšome', pubdate='2012-02-18', status='option two', slug1='main-name-and-its-awesome-2012-02-18', @@ -3037,28 +3036,28 @@ class SeleniumPrePopulatedFirefoxTests(AdminSeleniumWebDriverTestCase): ) self.assertEqual(RelatedPrepopulated.objects.all().count(), 4) RelatedPrepopulated.objects.get( - name=u' here is a sŤāÇkeð inline ! ', + name=' here is a sŤāÇkeð inline ! ', pubdate='2011-12-17', status='option one', slug1='here-stacked-inline-2011-12-17', slug2='option-one-here-stacked-inline', ) RelatedPrepopulated.objects.get( - name=u' now you haVe anöther sŤāÇkeð inline with a very ... loooooooooooooooooo', # 75 characters in name field + name=' now you haVe anöther sŤāÇkeð inline with a very ... loooooooooooooooooo', # 75 characters in name field pubdate='1999-01-25', status='option two', slug1='now-you-have-another-stacked-inline-very-loooooooo', slug2='option-two-now-you-have-another-stacked-inline-very-looooooo', ) RelatedPrepopulated.objects.get( - name=u'And now, with a tÃbűlaŘ inline !!!', + name='And now, with a tÃbűlaŘ inline !!!', pubdate='1234-12-07', status='option two', slug1='and-now-tabular-inline-1234-12-07', slug2='option-two-and-now-tabular-inline', ) RelatedPrepopulated.objects.get( - name=u'a tÃbűlaŘ inline with ignored ;"&*^\%$#@-/`~ characters', + name='a tÃbűlaŘ inline with ignored ;"&*^\%$#@-/`~ characters', pubdate='1981-08-22', status='option one', slug1='tabular-inline-ignored-characters-1981-08-22', @@ -3230,7 +3229,7 @@ class UserAdminTest(TestCase): adminform = response.context['adminform'] self.assertTrue('password' not in adminform.form.errors) self.assertEqual(adminform.form.errors['password2'], - [u"The two password fields didn't match."]) + ["The two password fields didn't match."]) def test_user_fk_popup(self): """Quick user addition in a FK popup shouldn't invoke view for further user customization""" @@ -3569,7 +3568,7 @@ class AdminCustomSaveRelatedTests(TestCase): children_names = list(Child.objects.order_by('name').values_list('name', flat=True)) self.assertEqual('Josh Stone', Parent.objects.latest('id').name) - self.assertEqual([u'Catherine Stone', u'Paul Stone'], children_names) + self.assertEqual(['Catherine Stone', 'Paul Stone'], children_names) def test_should_be_able_to_edit_related_objects_on_change_view(self): parent = Parent.objects.create(name='Josh Stone') @@ -3589,7 +3588,7 @@ class AdminCustomSaveRelatedTests(TestCase): children_names = list(Child.objects.order_by('name').values_list('name', flat=True)) self.assertEqual('Josh Stone', Parent.objects.latest('id').name) - self.assertEqual([u'Catherine Stone', u'Paul Stone'], children_names) + self.assertEqual(['Catherine Stone', 'Paul Stone'], children_names) def test_should_be_able_to_edit_related_objects_on_changelist_view(self): parent = Parent.objects.create(name='Josh Rock') @@ -3608,7 +3607,7 @@ class AdminCustomSaveRelatedTests(TestCase): children_names = list(Child.objects.order_by('name').values_list('name', flat=True)) self.assertEqual('Josh Stone', Parent.objects.latest('id').name) - self.assertEqual([u'Catherine Stone', u'Paul Stone'], children_names) + self.assertEqual(['Catherine Stone', 'Paul Stone'], children_names) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) diff --git a/tests/regressiontests/admin_widgets/models.py b/tests/regressiontests/admin_widgets/models.py index 1973d5069f7..81a4ec7abaf 100644 --- a/tests/regressiontests/admin_widgets/models.py +++ b/tests/regressiontests/admin_widgets/models.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.db import models from django.contrib.auth.models import User @@ -60,7 +62,7 @@ class Car(models.Model): model = models.CharField(max_length=30) def __unicode__(self): - return u"%s %s" % (self.make, self.model) + return "%s %s" % (self.make, self.model) class CarTire(models.Model): """ diff --git a/tests/regressiontests/admin_widgets/tests.py b/tests/regressiontests/admin_widgets/tests.py index be1d2940512..4b115431c18 100644 --- a/tests/regressiontests/admin_widgets/tests.py +++ b/tests/regressiontests/admin_widgets/tests.py @@ -1,5 +1,5 @@ # encoding: utf-8 -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from datetime import datetime @@ -169,7 +169,7 @@ class AdminForeignKeyRawIdWidget(DjangoTestCase): pk = band.pk band.delete() post_data = { - "band": u'%s' % pk, + "band": '%s' % pk, } # Try posting with a non-existent pk in a raw id field: this # should result in an error message, not a server exception. @@ -379,10 +379,10 @@ class ManyToManyRawIdWidgetTest(DjangoTestCase): self.assertEqual(w._has_changed(None, None), False) self.assertEqual(w._has_changed([], None), False) - self.assertEqual(w._has_changed(None, [u'1']), True) - self.assertEqual(w._has_changed([1, 2], [u'1', u'2']), False) - self.assertEqual(w._has_changed([1, 2], [u'1']), True) - self.assertEqual(w._has_changed([1, 2], [u'1', u'3']), True) + self.assertEqual(w._has_changed(None, ['1']), True) + self.assertEqual(w._has_changed([1, 2], ['1', '2']), False) + self.assertEqual(w._has_changed([1, 2], ['1']), True) + self.assertEqual(w._has_changed([1, 2], ['1', '3']), True) def test_m2m_related_model_not_in_admin(self): # M2M relationship with model not registered with admin site. Raw ID diff --git a/tests/regressiontests/aggregation_regress/tests.py b/tests/regressiontests/aggregation_regress/tests.py index 36a54c0b174..e5f12e5781c 100644 --- a/tests/regressiontests/aggregation_regress/tests.py +++ b/tests/regressiontests/aggregation_regress/tests.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import datetime import pickle @@ -119,7 +119,7 @@ class AggregationTests(TestCase): self.assertObjectAttrs(obj, contact_id=3, id=2, - isbn=u'067232959', + isbn='067232959', mean_auth_age=45.0, name='Sams Teach Yourself Django in 24 Hours', pages=528, @@ -136,9 +136,9 @@ class AggregationTests(TestCase): self.assertObjectAttrs(obj, contact_id=3, id=2, - isbn=u'067232959', + isbn='067232959', mean_auth_age=45.0, - name=u'Sams Teach Yourself Django in 24 Hours', + name='Sams Teach Yourself Django in 24 Hours', pages=528, price=Decimal("23.09"), pubdate=datetime.date(2008, 3, 3), @@ -156,9 +156,9 @@ class AggregationTests(TestCase): self.assertEqual(obj, { "contact_id": 3, "id": 2, - "isbn": u"067232959", + "isbn": "067232959", "mean_auth_age": 45.0, - "name": u"Sams Teach Yourself Django in 24 Hours", + "name": "Sams Teach Yourself Django in 24 Hours", "pages": 528, "price": Decimal("23.09"), "pubdate": datetime.date(2008, 3, 3), @@ -175,9 +175,9 @@ class AggregationTests(TestCase): self.assertEqual(obj, { 'contact_id': 3, 'id': 2, - 'isbn': u'067232959', + 'isbn': '067232959', 'mean_auth_age': 45.0, - 'name': u'Sams Teach Yourself Django in 24 Hours', + 'name': 'Sams Teach Yourself Django in 24 Hours', 'pages': 528, 'price': Decimal("23.09"), 'pubdate': datetime.date(2008, 3, 3), @@ -189,13 +189,13 @@ class AggregationTests(TestCase): # unless it is explicitly named obj = Book.objects.annotate(mean_auth_age=Avg('authors__age')).extra(select={'price_per_page' : 'price / pages'}).values('name').get(pk=1) self.assertEqual(obj, { - "name": u'The Definitive Guide to Django: Web Development Done Right', + "name": 'The Definitive Guide to Django: Web Development Done Right', }) obj = Book.objects.annotate(mean_auth_age=Avg('authors__age')).extra(select={'price_per_page' : 'price / pages'}).values('name','mean_auth_age').get(pk=1) self.assertEqual(obj, { 'mean_auth_age': 34.5, - 'name': u'The Definitive Guide to Django: Web Development Done Right', + 'name': 'The Definitive Guide to Django: Web Development Done Right', }) # If an annotation isn't included in the values, it can still be used @@ -203,7 +203,7 @@ class AggregationTests(TestCase): qs = Book.objects.annotate(n_authors=Count('authors')).values('name').filter(n_authors__gt=2) self.assertQuerysetEqual( qs, [ - {"name": u'Python Web Development with Django'} + {"name": 'Python Web Development with Django'} ], lambda b: b, ) @@ -213,7 +213,7 @@ class AggregationTests(TestCase): obj = Book.objects.values('name').annotate(mean_auth_age=Avg('authors__age')).extra(select={'price_per_page' : 'price / pages'}).get(pk=1) self.assertEqual(obj, { 'mean_auth_age': 34.5, - 'name': u'The Definitive Guide to Django: Web Development Done Right', + 'name': 'The Definitive Guide to Django: Web Development Done Right', }) # Check that all of the objects are getting counted (allow_nulls) and @@ -298,8 +298,8 @@ class AggregationTests(TestCase): self.assertEqual(obj, { 'contact_id': 8, 'id': 5, - 'isbn': u'013790395', - 'name': u'Artificial Intelligence: A Modern Approach', + 'isbn': '013790395', + 'name': 'Artificial Intelligence: A Modern Approach', 'num_authors': 2, 'pages': 1132, 'price': Decimal("82.8"), @@ -338,8 +338,8 @@ class AggregationTests(TestCase): qs = Publisher.objects.annotate(num_books=Count('book')).filter(num_books__lt=F('num_awards')/2).order_by('name').values('name','num_books','num_awards') self.assertQuerysetEqual( qs, [ - {'num_books': 1, 'name': u'Morgan Kaufmann', 'num_awards': 9}, - {'num_books': 2, 'name': u'Prentice Hall', 'num_awards': 7} + {'num_books': 1, 'name': 'Morgan Kaufmann', 'num_awards': 9}, + {'num_books': 2, 'name': 'Prentice Hall', 'num_awards': 7} ], lambda p: p, ) @@ -347,9 +347,9 @@ class AggregationTests(TestCase): qs = Publisher.objects.annotate(num_books=Count('book')).exclude(num_books__lt=F('num_awards')/2).order_by('name').values('name','num_books','num_awards') self.assertQuerysetEqual( qs, [ - {'num_books': 2, 'name': u'Apress', 'num_awards': 3}, - {'num_books': 0, 'name': u"Jonno's House of Books", 'num_awards': 0}, - {'num_books': 1, 'name': u'Sams', 'num_awards': 1} + {'num_books': 2, 'name': 'Apress', 'num_awards': 3}, + {'num_books': 0, 'name': "Jonno's House of Books", 'num_awards': 0}, + {'num_books': 1, 'name': 'Sams', 'num_awards': 1} ], lambda p: p, ) @@ -358,8 +358,8 @@ class AggregationTests(TestCase): qs = Publisher.objects.annotate(num_books=Count('book')).filter(num_awards__gt=2*F('num_books')).order_by('name').values('name','num_books','num_awards') self.assertQuerysetEqual( qs, [ - {'num_books': 1, 'name': u'Morgan Kaufmann', 'num_awards': 9}, - {'num_books': 2, 'name': u'Prentice Hall', 'num_awards': 7} + {'num_books': 1, 'name': 'Morgan Kaufmann', 'num_awards': 9}, + {'num_books': 2, 'name': 'Prentice Hall', 'num_awards': 7} ], lambda p: p, ) @@ -367,9 +367,9 @@ class AggregationTests(TestCase): qs = Publisher.objects.annotate(num_books=Count('book')).exclude(num_books__lt=F('num_awards')/2).order_by('name').values('name','num_books','num_awards') self.assertQuerysetEqual( qs, [ - {'num_books': 2, 'name': u'Apress', 'num_awards': 3}, - {'num_books': 0, 'name': u"Jonno's House of Books", 'num_awards': 0}, - {'num_books': 1, 'name': u'Sams', 'num_awards': 1} + {'num_books': 2, 'name': 'Apress', 'num_awards': 3}, + {'num_books': 0, 'name': "Jonno's House of Books", 'num_awards': 0}, + {'num_books': 1, 'name': 'Sams', 'num_awards': 1} ], lambda p: p, ) @@ -399,7 +399,7 @@ class AggregationTests(TestCase): qs = Publisher.objects.filter(pk=5).annotate(num_authors=Count('book__authors'), avg_authors=Avg('book__authors'), max_authors=Max('book__authors'), max_price=Max('book__price'), max_rating=Max('book__rating')).values() self.assertQuerysetEqual( qs, [ - {'max_authors': None, 'name': u"Jonno's House of Books", 'num_awards': 0, 'max_price': None, 'num_authors': 0, 'max_rating': None, 'id': 5, 'avg_authors': None} + {'max_authors': None, 'name': "Jonno's House of Books", 'num_awards': 0, 'max_price': None, 'num_authors': 0, 'max_rating': None, 'id': 5, 'avg_authors': None} ], lambda p: p ) @@ -424,10 +424,10 @@ class AggregationTests(TestCase): qs = Book.objects.filter(rating__lt=4.5).select_related().annotate(Avg('authors__age')) self.assertQuerysetEqual( qs, [ - (u'Artificial Intelligence: A Modern Approach', 51.5, u'Prentice Hall', u'Peter Norvig'), - (u'Practical Django Projects', 29.0, u'Apress', u'James Bennett'), - (u'Python Web Development with Django', Approximate(30.333, places=2), u'Prentice Hall', u'Jeffrey Forcier'), - (u'Sams Teach Yourself Django in 24 Hours', 45.0, u'Sams', u'Brad Dayley') + ('Artificial Intelligence: A Modern Approach', 51.5, 'Prentice Hall', 'Peter Norvig'), + ('Practical Django Projects', 29.0, 'Apress', 'James Bennett'), + ('Python Web Development with Django', Approximate(30.333, places=2), 'Prentice Hall', 'Jeffrey Forcier'), + ('Sams Teach Yourself Django in 24 Hours', 45.0, 'Sams', 'Brad Dayley') ], lambda b: (b.name, b.authors__age__avg, b.publisher.name, b.contact.name) ) @@ -491,19 +491,19 @@ class AggregationTests(TestCase): # But age isn't included in the ValuesQuerySet, so it is. results = Author.objects.values('name').annotate(age=Count('book_contact_set')).order_by('name') self.assertEqual(len(results), 9) - self.assertEqual(results[0]['name'], u'Adrian Holovaty') + self.assertEqual(results[0]['name'], 'Adrian Holovaty') self.assertEqual(results[0]['age'], 1) # Same problem, but aggregating over m2m fields results = Author.objects.values('name').annotate(age=Avg('friends__age')).order_by('name') self.assertEqual(len(results), 9) - self.assertEqual(results[0]['name'], u'Adrian Holovaty') + self.assertEqual(results[0]['name'], 'Adrian Holovaty') self.assertEqual(results[0]['age'], 32.0) # Same problem, but colliding with an m2m field results = Author.objects.values('name').annotate(friends=Count('friends')).order_by('name') self.assertEqual(len(results), 9) - self.assertEqual(results[0]['name'], u'Adrian Holovaty') + self.assertEqual(results[0]['name'], 'Adrian Holovaty') self.assertEqual(results[0]['friends'], 2) def test_reverse_relation_name_conflict(self): @@ -531,12 +531,12 @@ class AggregationTests(TestCase): books.aggregate(Avg("authors__age")) self.assertQuerysetEqual( books.all(), [ - u'Artificial Intelligence: A Modern Approach', - u'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp', - u'Practical Django Projects', - u'Python Web Development with Django', - u'Sams Teach Yourself Django in 24 Hours', - u'The Definitive Guide to Django: Web Development Done Right' + 'Artificial Intelligence: A Modern Approach', + 'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp', + 'Practical Django Projects', + 'Python Web Development with Django', + 'Sams Teach Yourself Django in 24 Hours', + 'The Definitive Guide to Django: Web Development Done Right' ], lambda b: b.name ) @@ -632,8 +632,8 @@ class AggregationTests(TestCase): qs = HardbackBook.objects.annotate(n_authors=Count('book_ptr__authors')).values('name', 'n_authors') self.assertQuerysetEqual( qs, [ - {'n_authors': 2, 'name': u'Artificial Intelligence: A Modern Approach'}, - {'n_authors': 1, 'name': u'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp'} + {'n_authors': 2, 'name': 'Artificial Intelligence: A Modern Approach'}, + {'n_authors': 1, 'name': 'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp'} ], lambda h: h ) @@ -641,8 +641,8 @@ class AggregationTests(TestCase): qs = HardbackBook.objects.annotate(n_authors=Count('authors')).values('name', 'n_authors') self.assertQuerysetEqual( qs, [ - {'n_authors': 2, 'name': u'Artificial Intelligence: A Modern Approach'}, - {'n_authors': 1, 'name': u'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp'} + {'n_authors': 2, 'name': 'Artificial Intelligence: A Modern Approach'}, + {'n_authors': 1, 'name': 'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp'} ], lambda h: h, ) diff --git a/tests/regressiontests/backends/models.py b/tests/regressiontests/backends/models.py index 1a78a87ecab..af4952dce83 100644 --- a/tests/regressiontests/backends/models.py +++ b/tests/regressiontests/backends/models.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.db import models, connection @@ -16,7 +18,7 @@ class Person(models.Model): last_name = models.CharField(max_length=20) def __unicode__(self): - return u'%s %s' % (self.first_name, self.last_name) + return '%s %s' % (self.first_name, self.last_name) class SchoolClass(models.Model): @@ -58,7 +60,7 @@ class Reporter(models.Model): last_name = models.CharField(max_length=30) def __unicode__(self): - return u"%s %s" % (self.first_name, self.last_name) + return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): diff --git a/tests/regressiontests/backends/tests.py b/tests/regressiontests/backends/tests.py index 109e1a5bcc3..2569a3236f9 100644 --- a/tests/regressiontests/backends/tests.py +++ b/tests/regressiontests/backends/tests.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # Unit and doctests for specific database backends. -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import datetime import threading @@ -393,9 +393,9 @@ class BackendTestCase(TestCase): qn(f3.column))) cursor = connection.cursor() cursor.execute(query2) - self.assertEqual(cursor.fetchone(), (u'Clark', u'Kent')) - self.assertEqual(list(cursor.fetchmany(2)), [(u'Jane', u'Doe'), (u'John', u'Doe')]) - self.assertEqual(list(cursor.fetchall()), [(u'Mary', u'Agnelline'), (u'Peter', u'Parker')]) + self.assertEqual(cursor.fetchone(), ('Clark', 'Kent')) + self.assertEqual(list(cursor.fetchmany(2)), [('Jane', 'Doe'), ('John', 'Doe')]) + self.assertEqual(list(cursor.fetchall()), [('Mary', 'Agnelline'), ('Peter', 'Parker')]) def test_database_operations_helper_class(self): # Ticket #13630 diff --git a/tests/regressiontests/cache/tests.py b/tests/regressiontests/cache/tests.py index 88fe5471cf2..264ef74abd3 100644 --- a/tests/regressiontests/cache/tests.py +++ b/tests/regressiontests/cache/tests.py @@ -2,7 +2,7 @@ # Unit tests for cache framework # Uses whatever cache backend is set in the test settings file. -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import hashlib import os @@ -139,10 +139,10 @@ class DummyCacheTests(unittest.TestCase): def test_unicode(self): "Unicode values are ignored by the dummy cache" stuff = { - u'ascii': u'ascii_value', - u'unicode_ascii': u'Iñtërnâtiônàlizætiøn1', - u'Iñtërnâtiônàlizætiøn': u'Iñtërnâtiônàlizætiøn2', - u'ascii2': {u'x' : 1 } + 'ascii': 'ascii_value', + 'unicode_ascii': 'Iñtërnâtiônàlizætiøn1', + 'Iñtërnâtiônàlizætiøn': 'Iñtërnâtiônàlizætiøn2', + 'ascii2': {'x' : 1 } } for (key, value) in stuff.items(): self.cache.set(key, value) @@ -337,10 +337,10 @@ class BaseCacheTests(object): def test_unicode(self): # Unicode values can be cached stuff = { - u'ascii': u'ascii_value', - u'unicode_ascii': u'Iñtërnâtiônàlizætiøn1', - u'Iñtërnâtiônàlizætiøn': u'Iñtërnâtiônàlizætiøn2', - u'ascii2': {u'x' : 1 } + 'ascii': 'ascii_value', + 'unicode_ascii': 'Iñtërnâtiônàlizætiøn1', + 'Iñtërnâtiônàlizætiøn': 'Iñtërnâtiônàlizætiøn2', + 'ascii2': {'x' : 1 } } # Test `set` for (key, value) in stuff.items(): @@ -1337,12 +1337,12 @@ class CacheI18nTest(TestCase): request = self._get_request() response = HttpResponse() with timezone.override(CustomTzName()): - CustomTzName.name = 'Hora estándar de Argentina' # 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") - CustomTzName.name = u'Hora estándar de Argentina' # unicode + CustomTzName.name = 'Hora estándar de Argentina' # unicode 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") diff --git a/tests/regressiontests/comment_tests/tests/comment_view_tests.py b/tests/regressiontests/comment_tests/tests/comment_view_tests.py index 5edc58fe2d6..429f3b2bf28 100644 --- a/tests/regressiontests/comment_tests/tests/comment_view_tests.py +++ b/tests/regressiontests/comment_tests/tests/comment_view_tests.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import re @@ -54,7 +54,7 @@ class CommentViewTests(CommentTestCase): a = Article.objects.get(pk=1) data = self.getValidData(a) data["comment"] = "This is another comment" - data["object_pk"] = u'\ufffd' + data["object_pk"] = '\ufffd' response = self.client.post("/post/", data) self.assertEqual(response.status_code, 400) @@ -258,7 +258,7 @@ class CommentViewTests(CommentTestCase): data["comment"] = "This is another comment" response = self.client.post("/post/", data) location = response["Location"] - broken_location = location + u"\ufffd" + broken_location = location + "\ufffd" response = self.client.get(broken_location) self.assertEqual(response.status_code, 200) diff --git a/tests/regressiontests/csrf_tests/tests.py b/tests/regressiontests/csrf_tests/tests.py index 2d9b4f755fa..52fd3ea1c7e 100644 --- a/tests/regressiontests/csrf_tests/tests.py +++ b/tests/regressiontests/csrf_tests/tests.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +from __future__ import unicode_literals from django.conf import settings from django.core.context_processors import csrf @@ -11,7 +12,7 @@ from django.views.decorators.csrf import csrf_exempt, requires_csrf_token, ensur # Response/views used for CsrfResponseMiddleware and CsrfViewMiddleware tests def post_form_response(): - resp = HttpResponse(content=u""" + resp = HttpResponse(content="""

        \u00a1Unicode!
        """, mimetype="text/html") return resp @@ -215,18 +216,18 @@ class CsrfViewMiddlewareTest(TestCase): """ req = self._get_GET_no_csrf_cookie_request() resp = token_view(req) - self.assertEqual(u"", resp.content) + self.assertEqual("", resp.content) def test_token_node_empty_csrf_cookie(self): """ Check that we get a new token if the csrf_cookie is the empty string """ req = self._get_GET_no_csrf_cookie_request() - req.COOKIES[settings.CSRF_COOKIE_NAME] = "" + req.COOKIES[settings.CSRF_COOKIE_NAME] = b"" CsrfViewMiddleware().process_view(req, token_view, (), {}) resp = token_view(req) - self.assertNotEqual(u"", resp.content) + self.assertNotEqual("", resp.content) def test_token_node_with_csrf_cookie(self): """ diff --git a/tests/regressiontests/custom_columns_regress/models.py b/tests/regressiontests/custom_columns_regress/models.py index fcb5a4be44c..c768c127728 100644 --- a/tests/regressiontests/custom_columns_regress/models.py +++ b/tests/regressiontests/custom_columns_regress/models.py @@ -5,6 +5,7 @@ Checks some pathological column naming to make sure it doesn't break table creation or queries. """ +from __future__ import unicode_literals from django.db import models @@ -27,7 +28,7 @@ class Author(models.Model): last_name = models.CharField(max_length=30, db_column='last name') def __unicode__(self): - return u'%s %s' % (self.first_name, self.last_name) + return '%s %s' % (self.first_name, self.last_name) class Meta: db_table = 'my author table' diff --git a/tests/regressiontests/datatypes/tests.py b/tests/regressiontests/datatypes/tests.py index fb94e831ba0..f8f68020415 100644 --- a/tests/regressiontests/datatypes/tests.py +++ b/tests/regressiontests/datatypes/tests.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import datetime @@ -62,7 +62,7 @@ class DataTypesTestCase(TestCase): d2 = Donut.objects.create(name='Apple Fritter', consumed_at = datetime.datetime(year=2007, month=4, day=20, hour=16, minute=19, second=59)) - self.assertEqual([u'Apple Fritter', u'Date Test 2007'], + self.assertEqual(['Apple Fritter', 'Date Test 2007'], list(Donut.objects.filter(consumed_at__year=2007).order_by('name').values_list('name', flat=True))) self.assertEqual(0, Donut.objects.filter(consumed_at__year=2005).count()) @@ -71,7 +71,7 @@ class DataTypesTestCase(TestCase): def test_textfields_unicode(self): """Regression test for #10238: TextField values returned from the database should be unicode.""" - d = Donut.objects.create(name=u'Jelly Donut', review=u'Outstanding') + d = Donut.objects.create(name='Jelly Donut', review='Outstanding') newd = Donut.objects.get(id=d.id) self.assertTrue(isinstance(newd.review, unicode)) diff --git a/tests/regressiontests/defaultfilters/tests.py b/tests/regressiontests/defaultfilters/tests.py index 7d0b8d61b6a..ffa0a01132a 100644 --- a/tests/regressiontests/defaultfilters/tests.py +++ b/tests/regressiontests/defaultfilters/tests.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +from __future__ import unicode_literals import datetime import decimal @@ -12,39 +13,39 @@ from django.utils.safestring import SafeData class DefaultFiltersTests(TestCase): def test_floatformat(self): - self.assertEqual(floatformat(7.7), u'7.7') - self.assertEqual(floatformat(7.0), u'7') - self.assertEqual(floatformat(0.7), u'0.7') - self.assertEqual(floatformat(0.07), u'0.1') - self.assertEqual(floatformat(0.007), u'0.0') - self.assertEqual(floatformat(0.0), u'0') - self.assertEqual(floatformat(7.7, 3), u'7.700') - self.assertEqual(floatformat(6.000000, 3), u'6.000') - self.assertEqual(floatformat(6.200000, 3), u'6.200') - self.assertEqual(floatformat(6.200000, -3), u'6.200') - self.assertEqual(floatformat(13.1031, -3), u'13.103') - self.assertEqual(floatformat(11.1197, -2), u'11.12') - self.assertEqual(floatformat(11.0000, -2), u'11') - self.assertEqual(floatformat(11.000001, -2), u'11.00') - self.assertEqual(floatformat(8.2798, 3), u'8.280') - self.assertEqual(floatformat(5555.555, 2), u'5555.56') - self.assertEqual(floatformat(001.3000, 2), u'1.30') - self.assertEqual(floatformat(0.12345, 2), u'0.12') - self.assertEqual(floatformat(decimal.Decimal('555.555'), 2), u'555.56') - self.assertEqual(floatformat(decimal.Decimal('09.000')), u'9') - self.assertEqual(floatformat(u'foo'), u'') - self.assertEqual(floatformat(13.1031, u'bar'), u'13.1031') - self.assertEqual(floatformat(18.125, 2), u'18.13') - self.assertEqual(floatformat(u'foo', u'bar'), u'') - self.assertEqual(floatformat(u'¿Cómo esta usted?'), u'') - self.assertEqual(floatformat(None), u'') + self.assertEqual(floatformat(7.7), '7.7') + self.assertEqual(floatformat(7.0), '7') + self.assertEqual(floatformat(0.7), '0.7') + self.assertEqual(floatformat(0.07), '0.1') + self.assertEqual(floatformat(0.007), '0.0') + self.assertEqual(floatformat(0.0), '0') + self.assertEqual(floatformat(7.7, 3), '7.700') + self.assertEqual(floatformat(6.000000, 3), '6.000') + self.assertEqual(floatformat(6.200000, 3), '6.200') + self.assertEqual(floatformat(6.200000, -3), '6.200') + self.assertEqual(floatformat(13.1031, -3), '13.103') + self.assertEqual(floatformat(11.1197, -2), '11.12') + self.assertEqual(floatformat(11.0000, -2), '11') + self.assertEqual(floatformat(11.000001, -2), '11.00') + self.assertEqual(floatformat(8.2798, 3), '8.280') + self.assertEqual(floatformat(5555.555, 2), '5555.56') + self.assertEqual(floatformat(001.3000, 2), '1.30') + self.assertEqual(floatformat(0.12345, 2), '0.12') + self.assertEqual(floatformat(decimal.Decimal('555.555'), 2), '555.56') + self.assertEqual(floatformat(decimal.Decimal('09.000')), '9') + self.assertEqual(floatformat('foo'), '') + self.assertEqual(floatformat(13.1031, 'bar'), '13.1031') + self.assertEqual(floatformat(18.125, 2), '18.13') + self.assertEqual(floatformat('foo', 'bar'), '') + self.assertEqual(floatformat('¿Cómo esta usted?'), '') + self.assertEqual(floatformat(None), '') # Check that we're not converting to scientific notation. - self.assertEqual(floatformat(0, 6), u'0.000000') - self.assertEqual(floatformat(0, 7), u'0.0000000') - self.assertEqual(floatformat(0, 10), u'0.0000000000') + self.assertEqual(floatformat(0, 6), '0.000000') + self.assertEqual(floatformat(0, 7), '0.0000000') + self.assertEqual(floatformat(0, 10), '0.0000000000') self.assertEqual(floatformat(0.000000000000000000015, 20), - u'0.00000000000000000002') + '0.00000000000000000002') pos_inf = float(1e30000) self.assertEqual(floatformat(pos_inf), unicode(pos_inf)) @@ -61,18 +62,18 @@ class DefaultFiltersTests(TestCase): def __float__(self): return self.value - self.assertEqual(floatformat(FloatWrapper(11.000001), -2), u'11.00') + self.assertEqual(floatformat(FloatWrapper(11.000001), -2), '11.00') # Regression for #15789 decimal_ctx = decimal.getcontext() old_prec, decimal_ctx.prec = decimal_ctx.prec, 2 try: - self.assertEqual(floatformat(1.2345, 2), u'1.23') - self.assertEqual(floatformat(15.2042, -3), u'15.204') - self.assertEqual(floatformat(1.2345, '2'), u'1.23') - self.assertEqual(floatformat(15.2042, '-3'), u'15.204') - self.assertEqual(floatformat(decimal.Decimal('1.2345'), 2), u'1.23') - self.assertEqual(floatformat(decimal.Decimal('15.2042'), -3), u'15.204') + self.assertEqual(floatformat(1.2345, 2), '1.23') + self.assertEqual(floatformat(15.2042, -3), '15.204') + self.assertEqual(floatformat(1.2345, '2'), '1.23') + self.assertEqual(floatformat(15.2042, '-3'), '15.204') + self.assertEqual(floatformat(decimal.Decimal('1.2345'), 2), '1.23') + self.assertEqual(floatformat(decimal.Decimal('15.2042'), -3), '15.204') finally: decimal_ctx.prec = old_prec @@ -82,290 +83,290 @@ class DefaultFiltersTests(TestCase): # unicode or Decimal. @unittest.expectedFailure def test_floatformat_fail(self): - self.assertEqual(floatformat(1.00000000000000015, 16), u'1.0000000000000002') + self.assertEqual(floatformat(1.00000000000000015, 16), '1.0000000000000002') def test_addslashes(self): - self.assertEqual(addslashes(u'"double quotes" and \'single quotes\''), - u'\\"double quotes\\" and \\\'single quotes\\\'') + self.assertEqual(addslashes('"double quotes" and \'single quotes\''), + '\\"double quotes\\" and \\\'single quotes\\\'') - self.assertEqual(addslashes(ur'\ : backslashes, too'), - u'\\\\ : backslashes, too') + self.assertEqual(addslashes(r'\ : backslashes, too'), + '\\\\ : backslashes, too') def test_capfirst(self): - self.assertEqual(capfirst(u'hello world'), u'Hello world') + self.assertEqual(capfirst('hello world'), 'Hello world') def test_escapejs(self): - self.assertEqual(escapejs_filter(u'"double quotes" and \'single quotes\''), - u'\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027') - self.assertEqual(escapejs_filter(ur'\ : backslashes, too'), - u'\\u005C : backslashes, too') - self.assertEqual(escapejs_filter(u'and lots of whitespace: \r\n\t\v\f\b'), - u'and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008') - self.assertEqual(escapejs_filter(ur''), - u'\\u003Cscript\\u003Eand this\\u003C/script\\u003E') + self.assertEqual(escapejs_filter('"double quotes" and \'single quotes\''), + '\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027') + self.assertEqual(escapejs_filter(r'\ : backslashes, too'), + '\\u005C : backslashes, too') + self.assertEqual(escapejs_filter('and lots of whitespace: \r\n\t\v\f\b'), + 'and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008') + self.assertEqual(escapejs_filter(r''), + '\\u003Cscript\\u003Eand this\\u003C/script\\u003E') self.assertEqual( - escapejs_filter(u'paragraph separator:\u2029and line separator:\u2028'), - u'paragraph separator:\\u2029and line separator:\\u2028') + escapejs_filter('paragraph separator:\u2029and line separator:\u2028'), + 'paragraph separator:\\u2029and line separator:\\u2028') def test_fix_ampersands(self): - self.assertEqual(fix_ampersands_filter(u'Jack & Jill & Jeroboam'), - u'Jack & Jill & Jeroboam') + self.assertEqual(fix_ampersands_filter('Jack & Jill & Jeroboam'), + 'Jack & Jill & Jeroboam') def test_linenumbers(self): - self.assertEqual(linenumbers(u'line 1\nline 2'), - u'1. line 1\n2. line 2') - self.assertEqual(linenumbers(u'\n'.join([u'x'] * 10)), - u'01. x\n02. x\n03. x\n04. x\n05. x\n06. x\n07. '\ - u'x\n08. x\n09. x\n10. x') + self.assertEqual(linenumbers('line 1\nline 2'), + '1. line 1\n2. line 2') + self.assertEqual(linenumbers('\n'.join(['x'] * 10)), + '01. x\n02. x\n03. x\n04. x\n05. x\n06. x\n07. '\ + 'x\n08. x\n09. x\n10. x') def test_lower(self): - self.assertEqual(lower('TEST'), u'test') + self.assertEqual(lower('TEST'), 'test') # uppercase E umlaut - self.assertEqual(lower(u'\xcb'), u'\xeb') + self.assertEqual(lower('\xcb'), '\xeb') def test_make_list(self): - self.assertEqual(make_list('abc'), [u'a', u'b', u'c']) - self.assertEqual(make_list(1234), [u'1', u'2', u'3', u'4']) + self.assertEqual(make_list('abc'), ['a', 'b', 'c']) + self.assertEqual(make_list(1234), ['1', '2', '3', '4']) def test_slugify(self): self.assertEqual(slugify(' Jack & Jill like numbers 1,2,3 and 4 and'\ ' silly characters ?%.$!/'), - u'jack-jill-like-numbers-123-and-4-and-silly-characters') + 'jack-jill-like-numbers-123-and-4-and-silly-characters') - self.assertEqual(slugify(u"Un \xe9l\xe9phant \xe0 l'or\xe9e du bois"), - u'un-elephant-a-loree-du-bois') + self.assertEqual(slugify("Un \xe9l\xe9phant \xe0 l'or\xe9e du bois"), + 'un-elephant-a-loree-du-bois') def test_stringformat(self): - self.assertEqual(stringformat(1, u'03d'), u'001') - self.assertEqual(stringformat(1, u'z'), u'') + self.assertEqual(stringformat(1, '03d'), '001') + self.assertEqual(stringformat(1, 'z'), '') def test_title(self): self.assertEqual(title('a nice title, isn\'t it?'), - u"A Nice Title, Isn't It?") - self.assertEqual(title(u'discoth\xe8que'), u'Discoth\xe8que') + "A Nice Title, Isn't It?") + self.assertEqual(title('discoth\xe8que'), 'Discoth\xe8que') def test_truncatewords(self): self.assertEqual( - truncatewords(u'A sentence with a few words in it', 1), u'A ...') + truncatewords('A sentence with a few words in it', 1), 'A ...') self.assertEqual( - truncatewords(u'A sentence with a few words in it', 5), - u'A sentence with a few ...') + truncatewords('A sentence with a few words in it', 5), + 'A sentence with a few ...') self.assertEqual( - truncatewords(u'A sentence with a few words in it', 100), - u'A sentence with a few words in it') + truncatewords('A sentence with a few words in it', 100), + 'A sentence with a few words in it') self.assertEqual( - truncatewords(u'A sentence with a few words in it', - 'not a number'), u'A sentence with a few words in it') + truncatewords('A sentence with a few words in it', + 'not a number'), 'A sentence with a few words in it') def test_truncatewords_html(self): self.assertEqual(truncatewords_html( - u'

        one two - three
        four
        five

        ', 0), u'') - self.assertEqual(truncatewords_html(u'

        one two - '\ - u'three
        four
        five

        ', 2), - u'

        one two ...

        ') + '

        one two - three
        four
        five

        ', 0), '') + self.assertEqual(truncatewords_html('

        one two - '\ + 'three
        four
        five

        ', 2), + '

        one two ...

        ') self.assertEqual(truncatewords_html( - u'

        one two - three
        four
        five

        ', 4), - u'

        one two - three
        four ...

        ') + '

        one two - three
        four
        five

        ', 4), + '

        one two - three
        four ...

        ') self.assertEqual(truncatewords_html( - u'

        one two - three
        four
        five

        ', 5), - u'

        one two - three
        four
        five

        ') + '

        one two - three
        four
        five

        ', 5), + '

        one two - three
        four
        five

        ') self.assertEqual(truncatewords_html( - u'

        one two - three
        four
        five

        ', 100), - u'

        one two - three
        four
        five

        ') + '

        one two - three
        four
        five

        ', 100), + '

        one two - three
        four
        five

        ') self.assertEqual(truncatewords_html( - u'\xc5ngstr\xf6m was here', 1), u'\xc5ngstr\xf6m ...') + '\xc5ngstr\xf6m was here', 1), '\xc5ngstr\xf6m ...') def test_upper(self): - self.assertEqual(upper(u'Mixed case input'), u'MIXED CASE INPUT') + self.assertEqual(upper('Mixed case input'), 'MIXED CASE INPUT') # lowercase e umlaut - self.assertEqual(upper(u'\xeb'), u'\xcb') + self.assertEqual(upper('\xeb'), '\xcb') def test_urlencode(self): - self.assertEqual(urlencode(u'fran\xe7ois & jill'), - u'fran%C3%A7ois%20%26%20jill') - self.assertEqual(urlencode(1), u'1') + self.assertEqual(urlencode('fran\xe7ois & jill'), + 'fran%C3%A7ois%20%26%20jill') + self.assertEqual(urlencode(1), '1') def test_iriencode(self): - self.assertEqual(iriencode(u'S\xf8r-Tr\xf8ndelag'), - u'S%C3%B8r-Tr%C3%B8ndelag') - self.assertEqual(iriencode(urlencode(u'fran\xe7ois & jill')), - u'fran%C3%A7ois%20%26%20jill') + self.assertEqual(iriencode('S\xf8r-Tr\xf8ndelag'), + 'S%C3%B8r-Tr%C3%B8ndelag') + self.assertEqual(iriencode(urlencode('fran\xe7ois & jill')), + 'fran%C3%A7ois%20%26%20jill') def test_urlizetrunc(self): - self.assertEqual(urlizetrunc(u'http://short.com/', 20), u'http://short.com/') - - self.assertEqual(urlizetrunc(u'http://www.google.co.uk/search?hl=en'\ - u'&q=some+long+url&btnG=Search&meta=', 20), u'http://www.google...') + self.assertEqual(urlizetrunc('http://short.com/', 20), 'http://short.com/') self.assertEqual(urlizetrunc('http://www.google.co.uk/search?hl=en'\ - u'&q=some+long+url&btnG=Search&meta=', 20), u'http://www.google...') + '&q=some+long+url&btnG=Search&meta=', 20), 'http://www.google...') + + self.assertEqual(urlizetrunc('http://www.google.co.uk/search?hl=en'\ + '&q=some+long+url&btnG=Search&meta=', 20), 'http://www.google...') # Check truncating of URIs which are the exact length uri = 'http://31characteruri.com/test/' self.assertEqual(len(uri), 31) self.assertEqual(urlizetrunc(uri, 31), - u''\ - u'http://31characteruri.com/test/') + ''\ + 'http://31characteruri.com/test/') self.assertEqual(urlizetrunc(uri, 30), - u''\ - u'http://31characteruri.com/t...') + ''\ + 'http://31characteruri.com/t...') self.assertEqual(urlizetrunc(uri, 2), - u'...') + '...') def test_urlize(self): # Check normal urlize self.assertEqual(urlize('http://google.com'), - u'http://google.com') + 'http://google.com') self.assertEqual(urlize('http://google.com/'), - u'http://google.com/') + 'http://google.com/') self.assertEqual(urlize('www.google.com'), - u'www.google.com') + 'www.google.com') self.assertEqual(urlize('djangoproject.org'), - u'djangoproject.org') + 'djangoproject.org') self.assertEqual(urlize('info@djangoproject.org'), - u'info@djangoproject.org') + 'info@djangoproject.org') # Check urlize with https addresses self.assertEqual(urlize('https://google.com'), - u'https://google.com') + 'https://google.com') # Check urlize doesn't overquote already quoted urls - see #9655 self.assertEqual(urlize('http://hi.baidu.com/%D6%D8%D0%C2%BF'), - u'' - u'http://hi.baidu.com/%D6%D8%D0%C2%BF') + '' + 'http://hi.baidu.com/%D6%D8%D0%C2%BF') self.assertEqual(urlize('www.mystore.com/30%OffCoupons!'), - u'' - u'www.mystore.com/30%OffCoupons!') + '' + 'www.mystore.com/30%OffCoupons!') self.assertEqual(urlize('http://en.wikipedia.org/wiki/Caf%C3%A9'), - u'' - u'http://en.wikipedia.org/wiki/Caf%C3%A9') + '' + 'http://en.wikipedia.org/wiki/Caf%C3%A9') self.assertEqual(urlize('http://en.wikipedia.org/wiki/Café'), - u'' - u'http://en.wikipedia.org/wiki/Café') + '' + 'http://en.wikipedia.org/wiki/Café') # Check urlize keeps balanced parentheses - see #11911 self.assertEqual(urlize('http://en.wikipedia.org/wiki/Django_(web_framework)'), - u'' - u'http://en.wikipedia.org/wiki/Django_(web_framework)') + '' + 'http://en.wikipedia.org/wiki/Django_(web_framework)') self.assertEqual(urlize('(see http://en.wikipedia.org/wiki/Django_(web_framework))'), - u'(see ' - u'http://en.wikipedia.org/wiki/Django_(web_framework))') + '(see ' + 'http://en.wikipedia.org/wiki/Django_(web_framework))') # Check urlize adds nofollow properly - see #12183 self.assertEqual(urlize('foo@bar.com or www.bar.com'), - u'foo@bar.com or ' - u'www.bar.com') + 'foo@bar.com or ' + 'www.bar.com') # Check urlize handles IDN correctly - see #13704 self.assertEqual(urlize('http://c✶.ws'), - u'http://c✶.ws') + 'http://c✶.ws') self.assertEqual(urlize('www.c✶.ws'), - u'www.c✶.ws') + 'www.c✶.ws') self.assertEqual(urlize('c✶.org'), - u'c✶.org') + 'c✶.org') self.assertEqual(urlize('info@c✶.org'), - u'info@c✶.org') + 'info@c✶.org') # Check urlize doesn't highlight malformed URIs - see #16395 self.assertEqual(urlize('http:///www.google.com'), - u'http:///www.google.com') + 'http:///www.google.com') self.assertEqual(urlize('http://.google.com'), - u'http://.google.com') + 'http://.google.com') self.assertEqual(urlize('http://@foo.com'), - u'http://@foo.com') + 'http://@foo.com') # Check urlize accepts more TLDs - see #16656 self.assertEqual(urlize('usa.gov'), - u'usa.gov') + 'usa.gov') # Check urlize don't crash on invalid email with dot-starting domain - see #17592 self.assertEqual(urlize('email@.stream.ru'), - u'email@.stream.ru') + 'email@.stream.ru') # Check urlize accepts uppercased URL schemes - see #18071 self.assertEqual(urlize('HTTPS://github.com/'), - u'HTTPS://github.com/') + 'HTTPS://github.com/') def test_wordcount(self): self.assertEqual(wordcount(''), 0) - self.assertEqual(wordcount(u'oneword'), 1) - self.assertEqual(wordcount(u'lots of words'), 3) + self.assertEqual(wordcount('oneword'), 1) + self.assertEqual(wordcount('lots of words'), 3) - self.assertEqual(wordwrap(u'this is a long paragraph of text that '\ - u'really needs to be wrapped I\'m afraid', 14), - u"this is a long\nparagraph of\ntext that\nreally needs\nto be "\ - u"wrapped\nI'm afraid") + self.assertEqual(wordwrap('this is a long paragraph of text that '\ + 'really needs to be wrapped I\'m afraid', 14), + "this is a long\nparagraph of\ntext that\nreally needs\nto be "\ + "wrapped\nI'm afraid") - self.assertEqual(wordwrap(u'this is a short paragraph of text.\n '\ - u'But this line should be indented', 14), - u'this is a\nshort\nparagraph of\ntext.\n But this\nline '\ - u'should be\nindented') + self.assertEqual(wordwrap('this is a short paragraph of text.\n '\ + 'But this line should be indented', 14), + 'this is a\nshort\nparagraph of\ntext.\n But this\nline '\ + 'should be\nindented') - self.assertEqual(wordwrap(u'this is a short paragraph of text.\n '\ - u'But this line should be indented',15), u'this is a short\n'\ - u'paragraph of\ntext.\n But this line\nshould be\nindented') + self.assertEqual(wordwrap('this is a short paragraph of text.\n '\ + 'But this line should be indented',15), 'this is a short\n'\ + 'paragraph of\ntext.\n But this line\nshould be\nindented') def test_rjust(self): - self.assertEqual(ljust(u'test', 10), u'test ') - self.assertEqual(ljust(u'test', 3), u'test') - self.assertEqual(rjust(u'test', 10), u' test') - self.assertEqual(rjust(u'test', 3), u'test') + self.assertEqual(ljust('test', 10), 'test ') + self.assertEqual(ljust('test', 3), 'test') + self.assertEqual(rjust('test', 10), ' test') + self.assertEqual(rjust('test', 3), 'test') def test_center(self): - self.assertEqual(center(u'test', 6), u' test ') + self.assertEqual(center('test', 6), ' test ') def test_cut(self): - self.assertEqual(cut(u'a string to be mangled', 'a'), - u' string to be mngled') - self.assertEqual(cut(u'a string to be mangled', 'ng'), - u'a stri to be maled') - self.assertEqual(cut(u'a string to be mangled', 'strings'), - u'a string to be mangled') + self.assertEqual(cut('a string to be mangled', 'a'), + ' string to be mngled') + self.assertEqual(cut('a string to be mangled', 'ng'), + 'a stri to be maled') + self.assertEqual(cut('a string to be mangled', 'strings'), + 'a string to be mangled') def test_force_escape(self): - escaped = force_escape(u' here') + escaped = force_escape(' here') self.assertEqual( - escaped, u'<some html & special characters > here') + escaped, '<some html & special characters > here') self.assertTrue(isinstance(escaped, SafeData)) self.assertEqual( - force_escape(u' here ĐÅ€£'), - u'<some html & special characters > here'\ - u' \u0110\xc5\u20ac\xa3') + force_escape(' here ĐÅ€£'), + '<some html & special characters > here'\ + ' \u0110\xc5\u20ac\xa3') def test_linebreaks(self): - self.assertEqual(linebreaks_filter(u'line 1'), u'

        line 1

        ') - self.assertEqual(linebreaks_filter(u'line 1\nline 2'), - u'

        line 1
        line 2

        ') - self.assertEqual(linebreaks_filter(u'line 1\rline 2'), - u'

        line 1
        line 2

        ') - self.assertEqual(linebreaks_filter(u'line 1\r\nline 2'), - u'

        line 1
        line 2

        ') + self.assertEqual(linebreaks_filter('line 1'), '

        line 1

        ') + self.assertEqual(linebreaks_filter('line 1\nline 2'), + '

        line 1
        line 2

        ') + self.assertEqual(linebreaks_filter('line 1\rline 2'), + '

        line 1
        line 2

        ') + self.assertEqual(linebreaks_filter('line 1\r\nline 2'), + '

        line 1
        line 2

        ') def test_linebreaksbr(self): - self.assertEqual(linebreaksbr(u'line 1\nline 2'), - u'line 1
        line 2') - self.assertEqual(linebreaksbr(u'line 1\rline 2'), - u'line 1
        line 2') - self.assertEqual(linebreaksbr(u'line 1\r\nline 2'), - u'line 1
        line 2') + self.assertEqual(linebreaksbr('line 1\nline 2'), + 'line 1
        line 2') + self.assertEqual(linebreaksbr('line 1\rline 2'), + 'line 1
        line 2') + self.assertEqual(linebreaksbr('line 1\r\nline 2'), + 'line 1
        line 2') def test_removetags(self): - self.assertEqual(removetags(u'some html with disallowed tags', 'script img'), - u'some html with alert("You smell") disallowed tags') - self.assertEqual(striptags(u'some html with disallowed tags'), - u'some html with alert("You smell") disallowed tags') + self.assertEqual(removetags('some html with disallowed tags', 'script img'), + 'some html with alert("You smell") disallowed tags') + self.assertEqual(striptags('some html with disallowed tags'), + 'some html with alert("You smell") disallowed tags') def test_dictsort(self): sorted_dicts = dictsort([{'age': 23, 'name': 'Barbara-Ann'}, @@ -404,81 +405,81 @@ class DefaultFiltersTests(TestCase): def test_first(self): self.assertEqual(first([0,1,2]), 0) - self.assertEqual(first(u''), u'') - self.assertEqual(first(u'test'), u't') + self.assertEqual(first(''), '') + self.assertEqual(first('test'), 't') def test_join(self): - self.assertEqual(join([0,1,2], u'glue'), u'0glue1glue2') + self.assertEqual(join([0,1,2], 'glue'), '0glue1glue2') def test_length(self): - self.assertEqual(length(u'1234'), 4) + self.assertEqual(length('1234'), 4) self.assertEqual(length([1,2,3,4]), 4) self.assertEqual(length_is([], 0), True) self.assertEqual(length_is([], 1), False) self.assertEqual(length_is('a', 1), True) - self.assertEqual(length_is(u'a', 10), False) + self.assertEqual(length_is('a', 10), False) def test_slice(self): - self.assertEqual(slice_filter(u'abcdefg', u'0'), u'') - self.assertEqual(slice_filter(u'abcdefg', u'1'), u'a') - self.assertEqual(slice_filter(u'abcdefg', u'-1'), u'abcdef') - self.assertEqual(slice_filter(u'abcdefg', u'1:2'), u'b') - self.assertEqual(slice_filter(u'abcdefg', u'1:3'), u'bc') - self.assertEqual(slice_filter(u'abcdefg', u'0::2'), u'aceg') + self.assertEqual(slice_filter('abcdefg', '0'), '') + self.assertEqual(slice_filter('abcdefg', '1'), 'a') + self.assertEqual(slice_filter('abcdefg', '-1'), 'abcdef') + self.assertEqual(slice_filter('abcdefg', '1:2'), 'b') + self.assertEqual(slice_filter('abcdefg', '1:3'), 'bc') + self.assertEqual(slice_filter('abcdefg', '0::2'), 'aceg') def test_unordered_list(self): - self.assertEqual(unordered_list([u'item 1', u'item 2']), - u'\t
      • item 1
      • \n\t
      • item 2
      • ') - self.assertEqual(unordered_list([u'item 1', [u'item 1.1']]), - u'\t
      • item 1\n\t
          \n\t\t
        • item 1.1
        • \n\t
        \n\t
      • ') + self.assertEqual(unordered_list(['item 1', 'item 2']), + '\t
      • item 1
      • \n\t
      • item 2
      • ') + self.assertEqual(unordered_list(['item 1', ['item 1.1']]), + '\t
      • item 1\n\t
          \n\t\t
        • item 1.1
        • \n\t
        \n\t
      • ') self.assertEqual( - unordered_list([u'item 1', [u'item 1.1', u'item1.2'], u'item 2']), - u'\t
      • item 1\n\t
          \n\t\t
        • item 1.1
        • \n\t\t
        • item1.2'\ - u'
        • \n\t
        \n\t
      • \n\t
      • item 2
      • ') + unordered_list(['item 1', ['item 1.1', 'item1.2'], 'item 2']), + '\t
      • item 1\n\t
          \n\t\t
        • item 1.1
        • \n\t\t
        • item1.2'\ + '
        • \n\t
        \n\t
      • \n\t
      • item 2
      • ') self.assertEqual( - unordered_list([u'item 1', [u'item 1.1', [u'item 1.1.1', - [u'item 1.1.1.1']]]]), - u'\t
      • item 1\n\t
          \n\t\t
        • item 1.1\n\t\t
            \n\t\t\t
          • '\ - u'item 1.1.1\n\t\t\t
              \n\t\t\t\t
            • item 1.1.1.1
            • \n\t\t\t'\ - u'
            \n\t\t\t
          • \n\t\t
          \n\t\t
        • \n\t
        \n\t
      • ') + unordered_list(['item 1', ['item 1.1', ['item 1.1.1', + ['item 1.1.1.1']]]]), + '\t
      • item 1\n\t
          \n\t\t
        • item 1.1\n\t\t
            \n\t\t\t
          • '\ + 'item 1.1.1\n\t\t\t
              \n\t\t\t\t
            • item 1.1.1.1
            • \n\t\t\t'\ + '
            \n\t\t\t
          • \n\t\t
          \n\t\t
        • \n\t
        \n\t
      • ') self.assertEqual(unordered_list( ['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]), - u'\t
      • States\n\t
          \n\t\t
        • Kansas\n\t\t
            \n\t\t\t
          • '\ - u'Lawrence
          • \n\t\t\t
          • Topeka
          • \n\t\t
          \n\t\t
        • '\ - u'\n\t\t
        • Illinois
        • \n\t
        \n\t
      • ') + '\t
      • States\n\t
          \n\t\t
        • Kansas\n\t\t
            \n\t\t\t
          • '\ + 'Lawrence
          • \n\t\t\t
          • Topeka
          • \n\t\t
          \n\t\t
        • '\ + '\n\t\t
        • Illinois
        • \n\t
        \n\t
      • ') class ULItem(object): def __init__(self, title): self.title = title def __unicode__(self): - return u'ulitem-%s' % str(self.title) + return 'ulitem-%s' % str(self.title) a = ULItem('a') b = ULItem('b') self.assertEqual(unordered_list([a,b]), - u'\t
      • ulitem-a
      • \n\t
      • ulitem-b
      • ') + '\t
      • ulitem-a
      • \n\t
      • ulitem-b
      • ') # Old format for unordered lists should still work - self.assertEqual(unordered_list([u'item 1', []]), u'\t
      • item 1
      • ') + self.assertEqual(unordered_list(['item 1', []]), '\t
      • item 1
      • ') - self.assertEqual(unordered_list([u'item 1', [[u'item 1.1', []]]]), - u'\t
      • item 1\n\t
          \n\t\t
        • item 1.1
        • \n\t
        \n\t
      • ') + self.assertEqual(unordered_list(['item 1', [['item 1.1', []]]]), + '\t
      • item 1\n\t
          \n\t\t
        • item 1.1
        • \n\t
        \n\t
      • ') - self.assertEqual(unordered_list([u'item 1', [[u'item 1.1', []], - [u'item 1.2', []]]]), u'\t
      • item 1\n\t
          \n\t\t
        • item 1.1'\ - u'
        • \n\t\t
        • item 1.2
        • \n\t
        \n\t
      • ') + self.assertEqual(unordered_list(['item 1', [['item 1.1', []], + ['item 1.2', []]]]), '\t
      • item 1\n\t
          \n\t\t
        • item 1.1'\ + '
        • \n\t\t
        • item 1.2
        • \n\t
        \n\t
      • ') self.assertEqual(unordered_list(['States', [['Kansas', [['Lawrence', - []], ['Topeka', []]]], ['Illinois', []]]]), u'\t
      • States\n\t'\ - u'
          \n\t\t
        • Kansas\n\t\t
            \n\t\t\t
          • Lawrence
          • '\ - u'\n\t\t\t
          • Topeka
          • \n\t\t
          \n\t\t
        • \n\t\t
        • '\ - u'Illinois
        • \n\t
        \n\t
      • ') + []], ['Topeka', []]]], ['Illinois', []]]]), '\t
      • States\n\t'\ + '
          \n\t\t
        • Kansas\n\t\t
            \n\t\t\t
          • Lawrence
          • '\ + '\n\t\t\t
          • Topeka
          • \n\t\t
          \n\t\t
        • \n\t\t
        • '\ + 'Illinois
        • \n\t
        \n\t
      • ') def test_add(self): - self.assertEqual(add(u'1', u'2'), 3) + self.assertEqual(add('1', '2'), 3) def test_get_digit(self): self.assertEqual(get_digit(123, 1), 3) @@ -486,148 +487,148 @@ class DefaultFiltersTests(TestCase): self.assertEqual(get_digit(123, 3), 1) self.assertEqual(get_digit(123, 4), 0) self.assertEqual(get_digit(123, 0), 123) - self.assertEqual(get_digit(u'xyz', 0), u'xyz') + self.assertEqual(get_digit('xyz', 0), 'xyz') def test_date(self): # real testing of date() is in dateformat.py - self.assertEqual(date(datetime.datetime(2005, 12, 29), u"d F Y"), - u'29 December 2005') - self.assertEqual(date(datetime.datetime(2005, 12, 29), ur'jS \o\f F'), - u'29th of December') + self.assertEqual(date(datetime.datetime(2005, 12, 29), "d F Y"), + '29 December 2005') + self.assertEqual(date(datetime.datetime(2005, 12, 29), r'jS \o\f F'), + '29th of December') def test_time(self): # real testing of time() is done in dateformat.py - self.assertEqual(time(datetime.time(13), u"h"), u'01') - self.assertEqual(time(datetime.time(0), u"h"), u'12') + self.assertEqual(time(datetime.time(13), "h"), '01') + self.assertEqual(time(datetime.time(0), "h"), '12') def test_timesince(self): # real testing is done in timesince.py, where we can provide our own 'now' self.assertEqual( timesince_filter(datetime.datetime.now() - datetime.timedelta(1)), - u'1 day') + '1 day') self.assertEqual( timesince_filter(datetime.datetime(2005, 12, 29), datetime.datetime(2005, 12, 30)), - u'1 day') + '1 day') def test_timeuntil(self): self.assertEqual( timeuntil_filter(datetime.datetime.now() + datetime.timedelta(1, 1)), - u'1 day') + '1 day') self.assertEqual( timeuntil_filter(datetime.datetime(2005, 12, 30), datetime.datetime(2005, 12, 29)), - u'1 day') + '1 day') def test_default(self): - self.assertEqual(default(u"val", u"default"), u'val') - self.assertEqual(default(None, u"default"), u'default') - self.assertEqual(default(u'', u"default"), u'default') + self.assertEqual(default("val", "default"), 'val') + self.assertEqual(default(None, "default"), 'default') + self.assertEqual(default('', "default"), 'default') def test_if_none(self): - self.assertEqual(default_if_none(u"val", u"default"), u'val') - self.assertEqual(default_if_none(None, u"default"), u'default') - self.assertEqual(default_if_none(u'', u"default"), u'') + self.assertEqual(default_if_none("val", "default"), 'val') + self.assertEqual(default_if_none(None, "default"), 'default') + self.assertEqual(default_if_none('', "default"), '') def test_divisibleby(self): self.assertEqual(divisibleby(4, 2), True) self.assertEqual(divisibleby(4, 3), False) def test_yesno(self): - self.assertEqual(yesno(True), u'yes') - self.assertEqual(yesno(False), u'no') - self.assertEqual(yesno(None), u'maybe') - self.assertEqual(yesno(True, u'certainly,get out of town,perhaps'), - u'certainly') - self.assertEqual(yesno(False, u'certainly,get out of town,perhaps'), - u'get out of town') - self.assertEqual(yesno(None, u'certainly,get out of town,perhaps'), - u'perhaps') - self.assertEqual(yesno(None, u'certainly,get out of town'), - u'get out of town') + self.assertEqual(yesno(True), 'yes') + self.assertEqual(yesno(False), 'no') + self.assertEqual(yesno(None), 'maybe') + self.assertEqual(yesno(True, 'certainly,get out of town,perhaps'), + 'certainly') + self.assertEqual(yesno(False, 'certainly,get out of town,perhaps'), + 'get out of town') + self.assertEqual(yesno(None, 'certainly,get out of town,perhaps'), + 'perhaps') + self.assertEqual(yesno(None, 'certainly,get out of town'), + 'get out of town') def test_filesizeformat(self): - self.assertEqual(filesizeformat(1023), u'1023 bytes') - self.assertEqual(filesizeformat(1024), u'1.0 KB') - self.assertEqual(filesizeformat(10*1024), u'10.0 KB') - self.assertEqual(filesizeformat(1024*1024-1), u'1024.0 KB') - self.assertEqual(filesizeformat(1024*1024), u'1.0 MB') - self.assertEqual(filesizeformat(1024*1024*50), u'50.0 MB') - self.assertEqual(filesizeformat(1024*1024*1024-1), u'1024.0 MB') - self.assertEqual(filesizeformat(1024*1024*1024), u'1.0 GB') - self.assertEqual(filesizeformat(1024*1024*1024*1024), u'1.0 TB') - self.assertEqual(filesizeformat(1024*1024*1024*1024*1024), u'1.0 PB') + self.assertEqual(filesizeformat(1023), '1023 bytes') + self.assertEqual(filesizeformat(1024), '1.0 KB') + self.assertEqual(filesizeformat(10*1024), '10.0 KB') + self.assertEqual(filesizeformat(1024*1024-1), '1024.0 KB') + self.assertEqual(filesizeformat(1024*1024), '1.0 MB') + self.assertEqual(filesizeformat(1024*1024*50), '50.0 MB') + self.assertEqual(filesizeformat(1024*1024*1024-1), '1024.0 MB') + self.assertEqual(filesizeformat(1024*1024*1024), '1.0 GB') + self.assertEqual(filesizeformat(1024*1024*1024*1024), '1.0 TB') + self.assertEqual(filesizeformat(1024*1024*1024*1024*1024), '1.0 PB') self.assertEqual(filesizeformat(1024*1024*1024*1024*1024*2000), - u'2000.0 PB') - self.assertEqual(filesizeformat(complex(1,-1)), u'0 bytes') - self.assertEqual(filesizeformat(""), u'0 bytes') - self.assertEqual(filesizeformat(u"\N{GREEK SMALL LETTER ALPHA}"), - u'0 bytes') + '2000.0 PB') + self.assertEqual(filesizeformat(complex(1,-1)), '0 bytes') + self.assertEqual(filesizeformat(""), '0 bytes') + self.assertEqual(filesizeformat("\N{GREEK SMALL LETTER ALPHA}"), + '0 bytes') def test_localized_filesizeformat(self): with self.settings(USE_L10N=True): with translation.override('de', deactivate=True): - self.assertEqual(filesizeformat(1023), u'1023 Bytes') - self.assertEqual(filesizeformat(1024), u'1,0 KB') - self.assertEqual(filesizeformat(10*1024), u'10,0 KB') - self.assertEqual(filesizeformat(1024*1024-1), u'1024,0 KB') - self.assertEqual(filesizeformat(1024*1024), u'1,0 MB') - self.assertEqual(filesizeformat(1024*1024*50), u'50,0 MB') - self.assertEqual(filesizeformat(1024*1024*1024-1), u'1024,0 MB') - self.assertEqual(filesizeformat(1024*1024*1024), u'1,0 GB') - self.assertEqual(filesizeformat(1024*1024*1024*1024), u'1,0 TB') + self.assertEqual(filesizeformat(1023), '1023 Bytes') + self.assertEqual(filesizeformat(1024), '1,0 KB') + self.assertEqual(filesizeformat(10*1024), '10,0 KB') + self.assertEqual(filesizeformat(1024*1024-1), '1024,0 KB') + self.assertEqual(filesizeformat(1024*1024), '1,0 MB') + self.assertEqual(filesizeformat(1024*1024*50), '50,0 MB') + self.assertEqual(filesizeformat(1024*1024*1024-1), '1024,0 MB') + self.assertEqual(filesizeformat(1024*1024*1024), '1,0 GB') + self.assertEqual(filesizeformat(1024*1024*1024*1024), '1,0 TB') self.assertEqual(filesizeformat(1024*1024*1024*1024*1024), - u'1,0 PB') + '1,0 PB') self.assertEqual(filesizeformat(1024*1024*1024*1024*1024*2000), - u'2000,0 PB') - self.assertEqual(filesizeformat(complex(1,-1)), u'0 Bytes') - self.assertEqual(filesizeformat(""), u'0 Bytes') - self.assertEqual(filesizeformat(u"\N{GREEK SMALL LETTER ALPHA}"), - u'0 Bytes') + '2000,0 PB') + self.assertEqual(filesizeformat(complex(1,-1)), '0 Bytes') + self.assertEqual(filesizeformat(""), '0 Bytes') + self.assertEqual(filesizeformat("\N{GREEK SMALL LETTER ALPHA}"), + '0 Bytes') def test_pluralize(self): - self.assertEqual(pluralize(1), u'') - self.assertEqual(pluralize(0), u's') - self.assertEqual(pluralize(2), u's') - self.assertEqual(pluralize([1]), u'') - self.assertEqual(pluralize([]), u's') - self.assertEqual(pluralize([1,2,3]), u's') - self.assertEqual(pluralize(1,u'es'), u'') - self.assertEqual(pluralize(0,u'es'), u'es') - self.assertEqual(pluralize(2,u'es'), u'es') - self.assertEqual(pluralize(1,u'y,ies'), u'y') - self.assertEqual(pluralize(0,u'y,ies'), u'ies') - self.assertEqual(pluralize(2,u'y,ies'), u'ies') - self.assertEqual(pluralize(0,u'y,ies,error'), u'') + self.assertEqual(pluralize(1), '') + self.assertEqual(pluralize(0), 's') + self.assertEqual(pluralize(2), 's') + self.assertEqual(pluralize([1]), '') + self.assertEqual(pluralize([]), 's') + self.assertEqual(pluralize([1,2,3]), 's') + self.assertEqual(pluralize(1,'es'), '') + self.assertEqual(pluralize(0,'es'), 'es') + self.assertEqual(pluralize(2,'es'), 'es') + self.assertEqual(pluralize(1,'y,ies'), 'y') + self.assertEqual(pluralize(0,'y,ies'), 'ies') + self.assertEqual(pluralize(2,'y,ies'), 'ies') + self.assertEqual(pluralize(0,'y,ies,error'), '') def test_phone2numeric(self): - self.assertEqual(phone2numeric_filter(u'0800 flowers'), u'0800 3569377') + self.assertEqual(phone2numeric_filter('0800 flowers'), '0800 3569377') def test_non_string_input(self): # Filters shouldn't break if passed non-strings - self.assertEqual(addslashes(123), u'123') - self.assertEqual(linenumbers(123), u'1. 123') - self.assertEqual(lower(123), u'123') - self.assertEqual(make_list(123), [u'1', u'2', u'3']) - self.assertEqual(slugify(123), u'123') - self.assertEqual(title(123), u'123') - self.assertEqual(truncatewords(123, 2), u'123') - self.assertEqual(upper(123), u'123') - self.assertEqual(urlencode(123), u'123') - self.assertEqual(urlize(123), u'123') - self.assertEqual(urlizetrunc(123, 1), u'123') + self.assertEqual(addslashes(123), '123') + self.assertEqual(linenumbers(123), '1. 123') + self.assertEqual(lower(123), '123') + self.assertEqual(make_list(123), ['1', '2', '3']) + self.assertEqual(slugify(123), '123') + self.assertEqual(title(123), '123') + self.assertEqual(truncatewords(123, 2), '123') + self.assertEqual(upper(123), '123') + self.assertEqual(urlencode(123), '123') + self.assertEqual(urlize(123), '123') + self.assertEqual(urlizetrunc(123, 1), '123') self.assertEqual(wordcount(123), 1) - self.assertEqual(wordwrap(123, 2), u'123') - self.assertEqual(ljust('123', 4), u'123 ') - self.assertEqual(rjust('123', 4), u' 123') - self.assertEqual(center('123', 5), u' 123 ') - self.assertEqual(center('123', 6), u' 123 ') - self.assertEqual(cut(123, '2'), u'13') - self.assertEqual(escape(123), u'123') - self.assertEqual(linebreaks_filter(123), u'

        123

        ') - self.assertEqual(linebreaksbr(123), u'123') - self.assertEqual(removetags(123, 'a'), u'123') - self.assertEqual(striptags(123), u'123') + self.assertEqual(wordwrap(123, 2), '123') + self.assertEqual(ljust('123', 4), '123 ') + self.assertEqual(rjust('123', 4), ' 123') + self.assertEqual(center('123', 5), ' 123 ') + self.assertEqual(center('123', 6), ' 123 ') + self.assertEqual(cut(123, '2'), '13') + self.assertEqual(escape(123), '123') + self.assertEqual(linebreaks_filter(123), '

        123

        ') + self.assertEqual(linebreaksbr(123), '123') + self.assertEqual(removetags(123, 'a'), '123') + self.assertEqual(striptags(123), '123') diff --git a/tests/regressiontests/expressions_regress/models.py b/tests/regressiontests/expressions_regress/models.py index 0ebccb50846..f3b6999377e 100644 --- a/tests/regressiontests/expressions_regress/models.py +++ b/tests/regressiontests/expressions_regress/models.py @@ -1,3 +1,4 @@ +from __future__ import unicode_literals """ Model for testing arithmetic expressions. """ @@ -9,7 +10,7 @@ class Number(models.Model): float = models.FloatField(null=True, db_column='the_float') def __unicode__(self): - return u'%i, %.3f' % (self.integer, self.float) + return '%i, %.3f' % (self.integer, self.float) class Experiment(models.Model): name = models.CharField(max_length=24) diff --git a/tests/regressiontests/extra_regress/models.py b/tests/regressiontests/extra_regress/models.py index 868331e5087..7d2a6fab34d 100644 --- a/tests/regressiontests/extra_regress/models.py +++ b/tests/regressiontests/extra_regress/models.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import copy import datetime @@ -11,7 +13,7 @@ class RevisionableModel(models.Model): when = models.DateTimeField(default=datetime.datetime.now) def __unicode__(self): - return u"%s (%s, %s)" % (self.title, self.id, self.base.id) + return "%s (%s, %s)" % (self.title, self.id, self.base.id) def save(self, *args, **kwargs): super(RevisionableModel, self).save(*args, **kwargs) @@ -36,5 +38,5 @@ class TestObject(models.Model): third = models.CharField(max_length=20) def __unicode__(self): - return u'TestObject: %s,%s,%s' % (self.first,self.second,self.third) + return 'TestObject: %s,%s,%s' % (self.first,self.second,self.third) diff --git a/tests/regressiontests/extra_regress/tests.py b/tests/regressiontests/extra_regress/tests.py index 3fcafef5de2..f591900afee 100644 --- a/tests/regressiontests/extra_regress/tests.py +++ b/tests/regressiontests/extra_regress/tests.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import datetime @@ -178,100 +178,100 @@ class ExtraRegressTests(TestCase): self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values()), - [{'bar': u'second', 'third': u'third', 'second': u'second', 'whiz': u'third', 'foo': u'first', 'id': obj.pk, 'first': u'first'}] + [{'bar': 'second', 'third': 'third', 'second': 'second', 'whiz': 'third', 'foo': 'first', 'id': obj.pk, 'first': 'first'}] ) # Extra clauses after an empty values clause are still included self.assertEqual( list(TestObject.objects.values().extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third'))))), - [{'bar': u'second', 'third': u'third', 'second': u'second', 'whiz': u'third', 'foo': u'first', 'id': obj.pk, 'first': u'first'}] + [{'bar': 'second', 'third': 'third', 'second': 'second', 'whiz': 'third', 'foo': 'first', 'id': obj.pk, 'first': 'first'}] ) # Extra columns are ignored if not mentioned in the values() clause self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values('first', 'second')), - [{'second': u'second', 'first': u'first'}] + [{'second': 'second', 'first': 'first'}] ) # Extra columns after a non-empty values() clause are ignored self.assertEqual( list(TestObject.objects.values('first', 'second').extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third'))))), - [{'second': u'second', 'first': u'first'}] + [{'second': 'second', 'first': 'first'}] ) # Extra columns can be partially returned self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values('first', 'second', 'foo')), - [{'second': u'second', 'foo': u'first', 'first': u'first'}] + [{'second': 'second', 'foo': 'first', 'first': 'first'}] ) # Also works if only extra columns are included self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values('foo', 'whiz')), - [{'foo': u'first', 'whiz': u'third'}] + [{'foo': 'first', 'whiz': 'third'}] ) # Values list works the same way # All columns are returned for an empty values_list() self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list()), - [(u'first', u'second', u'third', obj.pk, u'first', u'second', u'third')] + [('first', 'second', 'third', obj.pk, 'first', 'second', 'third')] ) # Extra columns after an empty values_list() are still included self.assertEqual( list(TestObject.objects.values_list().extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third'))))), - [(u'first', u'second', u'third', obj.pk, u'first', u'second', u'third')] + [('first', 'second', 'third', obj.pk, 'first', 'second', 'third')] ) # Extra columns ignored completely if not mentioned in values_list() self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('first', 'second')), - [(u'first', u'second')] + [('first', 'second')] ) # Extra columns after a non-empty values_list() clause are ignored completely self.assertEqual( list(TestObject.objects.values_list('first', 'second').extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third'))))), - [(u'first', u'second')] + [('first', 'second')] ) self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('second', flat=True)), - [u'second'] + ['second'] ) # Only the extra columns specified in the values_list() are returned self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('first', 'second', 'whiz')), - [(u'first', u'second', u'third')] + [('first', 'second', 'third')] ) # ...also works if only extra columns are included self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('foo','whiz')), - [(u'first', u'third')] + [('first', 'third')] ) self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('whiz', flat=True)), - [u'third'] + ['third'] ) # ... and values are returned in the order they are specified self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('whiz','foo')), - [(u'third', u'first')] + [('third', 'first')] ) self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('first','id')), - [(u'first', obj.pk)] + [('first', obj.pk)] ) self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('whiz', 'first', 'bar', 'id')), - [(u'third', u'first', u'second', obj.pk)] + [('third', 'first', 'second', obj.pk)] ) def test_regression_10847(self): diff --git a/tests/regressiontests/file_storage/tests.py b/tests/regressiontests/file_storage/tests.py index 87035d96d70..51b22078672 100644 --- a/tests/regressiontests/file_storage/tests.py +++ b/tests/regressiontests/file_storage/tests.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import errno import os @@ -251,9 +251,9 @@ class FileStorageTests(unittest.TestCase): os.mkdir(os.path.join(self.temp_dir, 'storage_dir_1')) dirs, files = self.storage.listdir('') - self.assertEqual(set(dirs), set([u'storage_dir_1'])) + self.assertEqual(set(dirs), set(['storage_dir_1'])) self.assertEqual(set(files), - set([u'storage_test_1', u'storage_test_2'])) + set(['storage_test_1', 'storage_test_2'])) self.storage.delete('storage_test_1') self.storage.delete('storage_test_2') @@ -388,7 +388,7 @@ class UnicodeFileNameTests(unittest.TestCase): out the encoding situation between doctest and this file, but the actual repr doesn't matter; it just shouldn't return a unicode object. """ - uf = UploadedFile(name=u'¿Cómo?',content_type='text') + uf = UploadedFile(name='¿Cómo?',content_type='text') self.assertEqual(type(uf.__repr__()), str) # Tests for a race condition on file saving (#4948). diff --git a/tests/regressiontests/file_uploads/tests.py b/tests/regressiontests/file_uploads/tests.py index c8de8035f9f..a7424639b4f 100644 --- a/tests/regressiontests/file_uploads/tests.py +++ b/tests/regressiontests/file_uploads/tests.py @@ -1,6 +1,5 @@ #! -*- coding: utf-8 -*- - -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import base64 import errno @@ -20,7 +19,7 @@ from . import uploadhandler from .models import FileModel, temp_storage, UPLOAD_TO -UNICODE_FILENAME = u'test-0123456789_中文_Orléans.jpg' +UNICODE_FILENAME = 'test-0123456789_中文_Orléans.jpg' class FileUploadTests(TestCase): def test_simple_upload(self): @@ -71,7 +70,7 @@ class FileUploadTests(TestCase): base64.b64encode(test_string), '--' + client.BOUNDARY + '--', '', - ]) + ]).encode('utf-8') r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, @@ -140,7 +139,7 @@ class FileUploadTests(TestCase): '', ]) - payload = "\r\n".join(payload) + payload = "\r\n".join(payload).encode('utf-8') r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, @@ -167,7 +166,7 @@ class FileUploadTests(TestCase): 'Oops.' '--' + client.BOUNDARY + '--', '', - ]) + ]).encode('utf-8') r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, @@ -192,7 +191,7 @@ class FileUploadTests(TestCase): 'file contents' '--' + client.BOUNDARY + '--', '', - ]) + ]).encode('utf-8') payload = payload[:-10] r = { 'CONTENT_LENGTH': len(payload), @@ -268,11 +267,11 @@ class FileUploadTests(TestCase): response = self.client.post('/file_uploads/getlist_count/', { 'file1': file1, - 'field1': u'test', - 'field2': u'test3', - 'field3': u'test5', - 'field4': u'test6', - 'field5': u'test7', + 'field1': 'test', + 'field2': 'test3', + 'field3': 'test5', + 'field4': 'test6', + 'field5': 'test7', 'file2': (file2, file2a) }) got = json.loads(response.content) diff --git a/tests/regressiontests/file_uploads/views.py b/tests/regressiontests/file_uploads/views.py index ae6842d0a70..73b09cbcff0 100644 --- a/tests/regressiontests/file_uploads/views.py +++ b/tests/regressiontests/file_uploads/views.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import hashlib import json @@ -67,7 +67,7 @@ def file_upload_unicode_name(request): # through file save. uni_named_file = request.FILES['file_unicode'] obj = FileModel.objects.create(testfile=uni_named_file) - full_name = u'%s/%s' % (UPLOAD_TO, uni_named_file.name) + full_name = '%s/%s' % (UPLOAD_TO, uni_named_file.name) if not os.path.exists(full_name): response = HttpResponseServerError() diff --git a/tests/regressiontests/fixtures_regress/models.py b/tests/regressiontests/fixtures_regress/models.py index 5a16f175a1f..5d23a21dcd8 100644 --- a/tests/regressiontests/fixtures_regress/models.py +++ b/tests/regressiontests/fixtures_regress/models.py @@ -1,4 +1,4 @@ -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from django.contrib.auth.models import User from django.db import models @@ -29,7 +29,7 @@ class Stuff(models.Model): owner = models.ForeignKey(User, null=True) def __unicode__(self): - return unicode(self.name) + u' is owned by ' + unicode(self.owner) + return unicode(self.name) + ' is owned by ' + unicode(self.owner) class Absolute(models.Model): @@ -128,7 +128,7 @@ class Book(models.Model): ordering = ('name',) def __unicode__(self): - return u'%s by %s (available at %s)' % ( + return '%s by %s (available at %s)' % ( self.name, self.author.name, ', '.join(s.name for s in self.stores.all()) @@ -148,7 +148,7 @@ class NKChild(Parent): return self.data def __unicode__(self): - return u'NKChild %s:%s' % (self.name, self.data) + return 'NKChild %s:%s' % (self.name, self.data) class RefToNKChild(models.Model): @@ -157,7 +157,7 @@ class RefToNKChild(models.Model): nk_m2m = models.ManyToManyField(NKChild, related_name='ref_m2ms') def __unicode__(self): - return u'%s: Reference to %s [%s]' % ( + return '%s: Reference to %s [%s]' % ( self.text, self.nk_fk, ', '.join(str(o) for o in self.nk_m2m.all()) diff --git a/tests/regressiontests/fixtures_regress/tests.py b/tests/regressiontests/fixtures_regress/tests.py index c0b811bea25..405c5668260 100644 --- a/tests/regressiontests/fixtures_regress/tests.py +++ b/tests/regressiontests/fixtures_regress/tests.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # Unittests for fixtures. -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import os import re @@ -85,7 +85,7 @@ class TestFixtures(TestCase): verbosity=0, commit=False ) - self.assertEqual(Stuff.objects.all()[0].name, u'') + self.assertEqual(Stuff.objects.all()[0].name, '') self.assertEqual(Stuff.objects.all()[0].owner, None) def test_absolute_path(self): diff --git a/tests/regressiontests/forms/models.py b/tests/regressiontests/forms/models.py index 939055785aa..18e6ddce6de 100644 --- a/tests/regressiontests/forms/models.py +++ b/tests/regressiontests/forms/models.py @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*- +from __future__ import unicode_literals + import os import datetime import tempfile @@ -43,7 +45,7 @@ class ChoiceOptionModel(models.Model): ordering = ('name',) def __unicode__(self): - return u'ChoiceOption %d' % self.pk + return 'ChoiceOption %d' % self.pk class ChoiceFieldModel(models.Model): @@ -68,7 +70,7 @@ class Group(models.Model): name = models.CharField(max_length=10) def __unicode__(self): - return u'%s' % self.name + return '%s' % self.name class Cheese(models.Model): diff --git a/tests/regressiontests/forms/tests/error_messages.py b/tests/regressiontests/forms/tests/error_messages.py index 7153a3b0a6d..f69b4194836 100644 --- a/tests/regressiontests/forms/tests/error_messages.py +++ b/tests/regressiontests/forms/tests/error_messages.py @@ -1,6 +1,5 @@ # -*- coding: utf-8 -*- - -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals from django.core.files.uploadedfile import SimpleUploadedFile from django.forms import * @@ -24,9 +23,9 @@ class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): 'max_length': 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s', } f = CharField(min_length=5, max_length=10, error_messages=e) - self.assertFormErrors([u'REQUIRED'], f.clean, '') - self.assertFormErrors([u'LENGTH 4, MIN LENGTH 5'], f.clean, '1234') - self.assertFormErrors([u'LENGTH 11, MAX LENGTH 10'], f.clean, '12345678901') + self.assertFormErrors(['REQUIRED'], f.clean, '') + self.assertFormErrors(['LENGTH 4, MIN LENGTH 5'], f.clean, '1234') + self.assertFormErrors(['LENGTH 11, MAX LENGTH 10'], f.clean, '12345678901') def test_integerfield(self): e = { @@ -36,10 +35,10 @@ class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): 'max_value': 'MAX VALUE IS %(limit_value)s', } f = IntegerField(min_value=5, max_value=10, error_messages=e) - self.assertFormErrors([u'REQUIRED'], f.clean, '') - self.assertFormErrors([u'INVALID'], f.clean, 'abc') - self.assertFormErrors([u'MIN VALUE IS 5'], f.clean, '4') - self.assertFormErrors([u'MAX VALUE IS 10'], f.clean, '11') + self.assertFormErrors(['REQUIRED'], f.clean, '') + self.assertFormErrors(['INVALID'], f.clean, 'abc') + self.assertFormErrors(['MIN VALUE IS 5'], f.clean, '4') + self.assertFormErrors(['MAX VALUE IS 10'], f.clean, '11') def test_floatfield(self): e = { @@ -49,10 +48,10 @@ class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): 'max_value': 'MAX VALUE IS %(limit_value)s', } f = FloatField(min_value=5, max_value=10, error_messages=e) - self.assertFormErrors([u'REQUIRED'], f.clean, '') - self.assertFormErrors([u'INVALID'], f.clean, 'abc') - self.assertFormErrors([u'MIN VALUE IS 5'], f.clean, '4') - self.assertFormErrors([u'MAX VALUE IS 10'], f.clean, '11') + self.assertFormErrors(['REQUIRED'], f.clean, '') + self.assertFormErrors(['INVALID'], f.clean, 'abc') + self.assertFormErrors(['MIN VALUE IS 5'], f.clean, '4') + self.assertFormErrors(['MAX VALUE IS 10'], f.clean, '11') def test_decimalfield(self): e = { @@ -65,15 +64,15 @@ class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): 'max_whole_digits': 'MAX DIGITS BEFORE DP IS %s', } f = DecimalField(min_value=5, max_value=10, error_messages=e) - self.assertFormErrors([u'REQUIRED'], f.clean, '') - self.assertFormErrors([u'INVALID'], f.clean, 'abc') - self.assertFormErrors([u'MIN VALUE IS 5'], f.clean, '4') - self.assertFormErrors([u'MAX VALUE IS 10'], f.clean, '11') + self.assertFormErrors(['REQUIRED'], f.clean, '') + self.assertFormErrors(['INVALID'], f.clean, 'abc') + self.assertFormErrors(['MIN VALUE IS 5'], f.clean, '4') + self.assertFormErrors(['MAX VALUE IS 10'], f.clean, '11') f2 = DecimalField(max_digits=4, decimal_places=2, error_messages=e) - self.assertFormErrors([u'MAX DIGITS IS 4'], f2.clean, '123.45') - self.assertFormErrors([u'MAX DP IS 2'], f2.clean, '1.234') - self.assertFormErrors([u'MAX DIGITS BEFORE DP IS 2'], f2.clean, '123.4') + self.assertFormErrors(['MAX DIGITS IS 4'], f2.clean, '123.45') + self.assertFormErrors(['MAX DP IS 2'], f2.clean, '1.234') + self.assertFormErrors(['MAX DIGITS BEFORE DP IS 2'], f2.clean, '123.4') def test_datefield(self): e = { @@ -81,8 +80,8 @@ class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): 'invalid': 'INVALID', } f = DateField(error_messages=e) - self.assertFormErrors([u'REQUIRED'], f.clean, '') - self.assertFormErrors([u'INVALID'], f.clean, 'abc') + self.assertFormErrors(['REQUIRED'], f.clean, '') + self.assertFormErrors(['INVALID'], f.clean, 'abc') def test_timefield(self): e = { @@ -90,8 +89,8 @@ class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): 'invalid': 'INVALID', } f = TimeField(error_messages=e) - self.assertFormErrors([u'REQUIRED'], f.clean, '') - self.assertFormErrors([u'INVALID'], f.clean, 'abc') + self.assertFormErrors(['REQUIRED'], f.clean, '') + self.assertFormErrors(['INVALID'], f.clean, 'abc') def test_datetimefield(self): e = { @@ -99,8 +98,8 @@ class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): 'invalid': 'INVALID', } f = DateTimeField(error_messages=e) - self.assertFormErrors([u'REQUIRED'], f.clean, '') - self.assertFormErrors([u'INVALID'], f.clean, 'abc') + self.assertFormErrors(['REQUIRED'], f.clean, '') + self.assertFormErrors(['INVALID'], f.clean, 'abc') def test_regexfield(self): e = { @@ -110,10 +109,10 @@ class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): 'max_length': 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s', } f = RegexField(r'^\d+$', min_length=5, max_length=10, error_messages=e) - self.assertFormErrors([u'REQUIRED'], f.clean, '') - self.assertFormErrors([u'INVALID'], f.clean, 'abcde') - self.assertFormErrors([u'LENGTH 4, MIN LENGTH 5'], f.clean, '1234') - self.assertFormErrors([u'LENGTH 11, MAX LENGTH 10'], f.clean, '12345678901') + self.assertFormErrors(['REQUIRED'], f.clean, '') + self.assertFormErrors(['INVALID'], f.clean, 'abcde') + self.assertFormErrors(['LENGTH 4, MIN LENGTH 5'], f.clean, '1234') + self.assertFormErrors(['LENGTH 11, MAX LENGTH 10'], f.clean, '12345678901') def test_emailfield(self): e = { @@ -123,10 +122,10 @@ class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): 'max_length': 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s', } f = EmailField(min_length=8, max_length=10, error_messages=e) - self.assertFormErrors([u'REQUIRED'], f.clean, '') - self.assertFormErrors([u'INVALID'], f.clean, 'abcdefgh') - self.assertFormErrors([u'LENGTH 7, MIN LENGTH 8'], f.clean, 'a@b.com') - self.assertFormErrors([u'LENGTH 11, MAX LENGTH 10'], f.clean, 'aye@bee.com') + self.assertFormErrors(['REQUIRED'], f.clean, '') + self.assertFormErrors(['INVALID'], f.clean, 'abcdefgh') + self.assertFormErrors(['LENGTH 7, MIN LENGTH 8'], f.clean, 'a@b.com') + self.assertFormErrors(['LENGTH 11, MAX LENGTH 10'], f.clean, 'aye@bee.com') def test_filefield(self): e = { @@ -136,10 +135,10 @@ class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): 'empty': 'EMPTY FILE', } f = FileField(error_messages=e) - self.assertFormErrors([u'REQUIRED'], f.clean, '') - self.assertFormErrors([u'INVALID'], f.clean, 'abc') - self.assertFormErrors([u'EMPTY FILE'], f.clean, SimpleUploadedFile('name', None)) - self.assertFormErrors([u'EMPTY FILE'], f.clean, SimpleUploadedFile('name', '')) + self.assertFormErrors(['REQUIRED'], f.clean, '') + self.assertFormErrors(['INVALID'], f.clean, 'abc') + self.assertFormErrors(['EMPTY FILE'], f.clean, SimpleUploadedFile('name', None)) + self.assertFormErrors(['EMPTY FILE'], f.clean, SimpleUploadedFile('name', '')) def test_urlfield(self): e = { @@ -147,15 +146,15 @@ class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): 'invalid': 'INVALID', } f = URLField(error_messages=e) - self.assertFormErrors([u'REQUIRED'], f.clean, '') - self.assertFormErrors([u'INVALID'], f.clean, 'abc.c') + self.assertFormErrors(['REQUIRED'], f.clean, '') + self.assertFormErrors(['INVALID'], f.clean, 'abc.c') def test_booleanfield(self): e = { 'required': 'REQUIRED', } f = BooleanField(error_messages=e) - self.assertFormErrors([u'REQUIRED'], f.clean, '') + self.assertFormErrors(['REQUIRED'], f.clean, '') def test_choicefield(self): e = { @@ -163,8 +162,8 @@ class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): 'invalid_choice': '%(value)s IS INVALID CHOICE', } f = ChoiceField(choices=[('a', 'aye')], error_messages=e) - self.assertFormErrors([u'REQUIRED'], f.clean, '') - self.assertFormErrors([u'b IS INVALID CHOICE'], f.clean, 'b') + self.assertFormErrors(['REQUIRED'], f.clean, '') + self.assertFormErrors(['b IS INVALID CHOICE'], f.clean, 'b') def test_multiplechoicefield(self): e = { @@ -173,9 +172,9 @@ class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): 'invalid_list': 'NOT A LIST', } f = MultipleChoiceField(choices=[('a', 'aye')], error_messages=e) - self.assertFormErrors([u'REQUIRED'], f.clean, '') - self.assertFormErrors([u'NOT A LIST'], f.clean, 'b') - self.assertFormErrors([u'b IS INVALID CHOICE'], f.clean, ['b']) + self.assertFormErrors(['REQUIRED'], f.clean, '') + self.assertFormErrors(['NOT A LIST'], f.clean, 'b') + self.assertFormErrors(['b IS INVALID CHOICE'], f.clean, ['b']) def test_splitdatetimefield(self): e = { @@ -184,8 +183,8 @@ class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): 'invalid_time': 'INVALID TIME', } f = SplitDateTimeField(error_messages=e) - self.assertFormErrors([u'REQUIRED'], f.clean, '') - self.assertFormErrors([u'INVALID DATE', u'INVALID TIME'], f.clean, ['a', 'b']) + self.assertFormErrors(['REQUIRED'], f.clean, '') + self.assertFormErrors(['INVALID DATE', 'INVALID TIME'], f.clean, ['a', 'b']) def test_ipaddressfield(self): e = { @@ -193,8 +192,8 @@ class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): 'invalid': 'INVALID IP ADDRESS', } f = IPAddressField(error_messages=e) - self.assertFormErrors([u'REQUIRED'], f.clean, '') - self.assertFormErrors([u'INVALID IP ADDRESS'], f.clean, '127.0.0') + self.assertFormErrors(['REQUIRED'], f.clean, '') + self.assertFormErrors(['INVALID IP ADDRESS'], f.clean, '127.0.0') def test_generic_ipaddressfield(self): e = { @@ -202,8 +201,8 @@ class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): 'invalid': 'INVALID IP ADDRESS', } f = GenericIPAddressField(error_messages=e) - self.assertFormErrors([u'REQUIRED'], f.clean, '') - self.assertFormErrors([u'INVALID IP ADDRESS'], f.clean, '127.0.0') + self.assertFormErrors(['REQUIRED'], f.clean, '') + self.assertFormErrors(['INVALID IP ADDRESS'], f.clean, '127.0.0') def test_subclassing_errorlist(self): class TestForm(Form): @@ -219,8 +218,8 @@ class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): return self.as_divs() def as_divs(self): - if not self: return u'' - return mark_safe(u'
        %s
        ' % ''.join([u'

        %s

        ' % e for e in self])) + if not self: return '' + return mark_safe('
        %s
        ' % ''.join(['

        %s

        ' % e for e in self])) # This form should print errors the default way. form1 = TestForm({'first_name': 'John'}) @@ -247,8 +246,8 @@ class ModelChoiceFieldErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): 'invalid_choice': 'INVALID CHOICE', } f = ModelChoiceField(queryset=ChoiceModel.objects.all(), error_messages=e) - self.assertFormErrors([u'REQUIRED'], f.clean, '') - self.assertFormErrors([u'INVALID CHOICE'], f.clean, '4') + self.assertFormErrors(['REQUIRED'], f.clean, '') + self.assertFormErrors(['INVALID CHOICE'], f.clean, '4') # ModelMultipleChoiceField e = { @@ -257,6 +256,6 @@ class ModelChoiceFieldErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): 'list': 'NOT A LIST OF VALUES', } f = ModelMultipleChoiceField(queryset=ChoiceModel.objects.all(), error_messages=e) - self.assertFormErrors([u'REQUIRED'], f.clean, '') - self.assertFormErrors([u'NOT A LIST OF VALUES'], f.clean, '3') - self.assertFormErrors([u'4 IS INVALID CHOICE'], f.clean, ['4']) + self.assertFormErrors(['REQUIRED'], f.clean, '') + self.assertFormErrors(['NOT A LIST OF VALUES'], f.clean, '3') + self.assertFormErrors(['4 IS INVALID CHOICE'], f.clean, ['4']) diff --git a/tests/regressiontests/forms/tests/extra.py b/tests/regressiontests/forms/tests/extra.py index c873af7a8ca..25b21123c42 100644 --- a/tests/regressiontests/forms/tests/extra.py +++ b/tests/regressiontests/forms/tests/extra.py @@ -1,6 +1,5 @@ # -*- coding: utf-8 -*- - -from __future__ import absolute_import +from __future__ import absolute_import, unicode_literals import datetime @@ -366,7 +365,7 @@ class FormsExtraTestCase(TestCase, AssertFormErrorsMixin): # Invalid dates shouldn't be allowed c = GetDate({'mydate_month':'2', 'mydate_day':'31', 'mydate_year':'2010'}) self.assertFalse(c.is_valid()) - self.assertEqual(c.errors, {'mydate': [u'Enter a valid date.']}) + self.assertEqual(c.errors, {'mydate': ['Enter a valid date.']}) # label tag is correctly associated with month dropdown d = GetDate({'mydate_month':'1', 'mydate_day':'1', 'mydate_year':'2010'}) @@ -395,7 +394,7 @@ class FormsExtraTestCase(TestCase, AssertFormErrorsMixin): return [None, None, None] def format_output(self, rendered_widgets): - return u'\n'.join(rendered_widgets) + return '\n'.join(rendered_widgets) w = ComplexMultiWidget() self.assertHTMLEqual(w.render('name', 'some text,JP,2007-04-25 06:24:00'), """ @@ -422,11 +421,11 @@ class FormsExtraTestCase(TestCase, AssertFormErrorsMixin): return None f = ComplexField(widget=w) - self.assertEqual(f.clean(['some text', ['J','P'], ['2007-04-25','6:24:00']]), u'some text,JP,2007-04-25 06:24:00') - self.assertFormErrors([u'Select a valid choice. X is not one of the available choices.'], f.clean, ['some text',['X'], ['2007-04-25','6:24:00']]) + self.assertEqual(f.clean(['some text', ['J','P'], ['2007-04-25','6:24:00']]), 'some text,JP,2007-04-25 06:24:00') + self.assertFormErrors(['Select a valid choice. X is not one of the available choices.'], f.clean, ['some text',['X'], ['2007-04-25','6:24:00']]) # If insufficient data is provided, None is substituted - self.assertFormErrors([u'This field is required.'], f.clean, ['some text',['JP']]) + self.assertFormErrors(['This field is required.'], f.clean, ['some text',['JP']]) class ComplexFieldForm(Form): field1 = ComplexField(widget=w) @@ -451,26 +450,26 @@ class FormsExtraTestCase(TestCase, AssertFormErrorsMixin): """) - self.assertEqual(f.cleaned_data['field1'], u'some text,JP,2007-04-25 06:24:00') + self.assertEqual(f.cleaned_data['field1'], 'some text,JP,2007-04-25 06:24:00') def test_ipaddress(self): f = IPAddressField() - self.assertFormErrors([u'This field is required.'], f.clean, '') - self.assertFormErrors([u'This field is required.'], f.clean, None) - self.assertEqual(f.clean('127.0.0.1'), u'127.0.0.1') - self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, 'foo') - self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, '127.0.0.') - self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, '1.2.3.4.5') - self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, '256.125.1.5') + self.assertFormErrors(['This field is required.'], f.clean, '') + self.assertFormErrors(['This field is required.'], f.clean, None) + self.assertEqual(f.clean('127.0.0.1'), '127.0.0.1') + self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, 'foo') + self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '127.0.0.') + self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '1.2.3.4.5') + self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '256.125.1.5') f = IPAddressField(required=False) - self.assertEqual(f.clean(''), u'') - self.assertEqual(f.clean(None), u'') - self.assertEqual(f.clean('127.0.0.1'), u'127.0.0.1') - self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, 'foo') - self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, '127.0.0.') - self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, '1.2.3.4.5') - self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, '256.125.1.5') + self.assertEqual(f.clean(''), '') + self.assertEqual(f.clean(None), '') + self.assertEqual(f.clean('127.0.0.1'), '127.0.0.1') + self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, 'foo') + self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '127.0.0.') + self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '1.2.3.4.5') + self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '256.125.1.5') def test_generic_ipaddress_invalid_arguments(self): self.assertRaises(ValueError, GenericIPAddressField, protocol="hamster") @@ -480,93 +479,93 @@ class FormsExtraTestCase(TestCase, AssertFormErrorsMixin): # The edge cases of the IPv6 validation code are not deeply tested # here, they are covered in the tests for django.utils.ipv6 f = GenericIPAddressField() - self.assertFormErrors([u'This field is required.'], f.clean, '') - self.assertFormErrors([u'This field is required.'], f.clean, None) - self.assertEqual(f.clean('127.0.0.1'), u'127.0.0.1') - self.assertFormErrors([u'Enter a valid IPv4 or IPv6 address.'], f.clean, 'foo') - self.assertFormErrors([u'Enter a valid IPv4 or IPv6 address.'], f.clean, '127.0.0.') - self.assertFormErrors([u'Enter a valid IPv4 or IPv6 address.'], f.clean, '1.2.3.4.5') - self.assertFormErrors([u'Enter a valid IPv4 or IPv6 address.'], f.clean, '256.125.1.5') - self.assertEqual(f.clean('fe80::223:6cff:fe8a:2e8a'), u'fe80::223:6cff:fe8a:2e8a') - self.assertEqual(f.clean('2a02::223:6cff:fe8a:2e8a'), u'2a02::223:6cff:fe8a:2e8a') - self.assertFormErrors([u'Enter a valid IPv4 or IPv6 address.'], f.clean, '12345:2:3:4') - self.assertFormErrors([u'Enter a valid IPv4 or IPv6 address.'], f.clean, '1::2:3::4') - self.assertFormErrors([u'Enter a valid IPv4 or IPv6 address.'], f.clean, 'foo::223:6cff:fe8a:2e8a') - self.assertFormErrors([u'Enter a valid IPv4 or IPv6 address.'], f.clean, '1::2:3:4:5:6:7:8') - self.assertFormErrors([u'Enter a valid IPv4 or IPv6 address.'], f.clean, '1:2') + self.assertFormErrors(['This field is required.'], f.clean, '') + self.assertFormErrors(['This field is required.'], f.clean, None) + self.assertEqual(f.clean('127.0.0.1'), '127.0.0.1') + self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, 'foo') + self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '127.0.0.') + self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '1.2.3.4.5') + self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '256.125.1.5') + self.assertEqual(f.clean('fe80::223:6cff:fe8a:2e8a'), 'fe80::223:6cff:fe8a:2e8a') + self.assertEqual(f.clean('2a02::223:6cff:fe8a:2e8a'), '2a02::223:6cff:fe8a:2e8a') + self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '12345:2:3:4') + self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '1::2:3::4') + self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, 'foo::223:6cff:fe8a:2e8a') + self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '1::2:3:4:5:6:7:8') + self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '1:2') def test_generic_ipaddress_as_ipv4_only(self): f = GenericIPAddressField(protocol="IPv4") - self.assertFormErrors([u'This field is required.'], f.clean, '') - self.assertFormErrors([u'This field is required.'], f.clean, None) - self.assertEqual(f.clean('127.0.0.1'), u'127.0.0.1') - self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, 'foo') - self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, '127.0.0.') - self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, '1.2.3.4.5') - self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, '256.125.1.5') - self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, 'fe80::223:6cff:fe8a:2e8a') - self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, '2a02::223:6cff:fe8a:2e8a') + self.assertFormErrors(['This field is required.'], f.clean, '') + self.assertFormErrors(['This field is required.'], f.clean, None) + self.assertEqual(f.clean('127.0.0.1'), '127.0.0.1') + self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, 'foo') + self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '127.0.0.') + self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '1.2.3.4.5') + self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '256.125.1.5') + self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, 'fe80::223:6cff:fe8a:2e8a') + self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '2a02::223:6cff:fe8a:2e8a') def test_generic_ipaddress_as_ipv6_only(self): f = GenericIPAddressField(protocol="IPv6") - self.assertFormErrors([u'This field is required.'], f.clean, '') - self.assertFormErrors([u'This field is required.'], f.clean, None) - self.assertFormErrors([u'Enter a valid IPv6 address.'], f.clean, '127.0.0.1') - self.assertFormErrors([u'Enter a valid IPv6 address.'], f.clean, 'foo') - self.assertFormErrors([u'Enter a valid IPv6 address.'], f.clean, '127.0.0.') - self.assertFormErrors([u'Enter a valid IPv6 address.'], f.clean, '1.2.3.4.5') - self.assertFormErrors([u'Enter a valid IPv6 address.'], f.clean, '256.125.1.5') - self.assertEqual(f.clean('fe80::223:6cff:fe8a:2e8a'), u'fe80::223:6cff:fe8a:2e8a') - self.assertEqual(f.clean('2a02::223:6cff:fe8a:2e8a'), u'2a02::223:6cff:fe8a:2e8a') - self.assertFormErrors([u'Enter a valid IPv6 address.'], f.clean, '12345:2:3:4') - self.assertFormErrors([u'Enter a valid IPv6 address.'], f.clean, '1::2:3::4') - self.assertFormErrors([u'Enter a valid IPv6 address.'], f.clean, 'foo::223:6cff:fe8a:2e8a') - self.assertFormErrors([u'Enter a valid IPv6 address.'], f.clean, '1::2:3:4:5:6:7:8') - self.assertFormErrors([u'Enter a valid IPv6 address.'], f.clean, '1:2') + self.assertFormErrors(['This field is required.'], f.clean, '') + self.assertFormErrors(['This field is required.'], f.clean, None) + self.assertFormErrors(['Enter a valid IPv6 address.'], f.clean, '127.0.0.1') + self.assertFormErrors(['Enter a valid IPv6 address.'], f.clean, 'foo') + self.assertFormErrors(['Enter a valid IPv6 address.'], f.clean, '127.0.0.') + self.assertFormErrors(['Enter a valid IPv6 address.'], f.clean, '1.2.3.4.5') + self.assertFormErrors(['Enter a valid IPv6 address.'], f.clean, '256.125.1.5') + self.assertEqual(f.clean('fe80::223:6cff:fe8a:2e8a'), 'fe80::223:6cff:fe8a:2e8a') + self.assertEqual(f.clean('2a02::223:6cff:fe8a:2e8a'), '2a02::223:6cff:fe8a:2e8a') + self.assertFormErrors(['Enter a valid IPv6 address.'], f.clean, '12345:2:3:4') + self.assertFormErrors(['Enter a valid IPv6 address.'], f.clean, '1::2:3::4') + self.assertFormErrors(['Enter a valid IPv6 address.'], f.clean, 'foo::223:6cff:fe8a:2e8a') + self.assertFormErrors(['Enter a valid IPv6 address.'], f.clean, '1::2:3:4:5:6:7:8') + self.assertFormErrors(['Enter a valid IPv6 address.'], f.clean, '1:2') def test_generic_ipaddress_as_generic_not_required(self): f = GenericIPAddressField(required=False) - self.assertEqual(f.clean(''), u'') - self.assertEqual(f.clean(None), u'') - self.assertEqual(f.clean('127.0.0.1'), u'127.0.0.1') - self.assertFormErrors([u'Enter a valid IPv4 or IPv6 address.'], f.clean, 'foo') - self.assertFormErrors([u'Enter a valid IPv4 or IPv6 address.'], f.clean, '127.0.0.') - self.assertFormErrors([u'Enter a valid IPv4 or IPv6 address.'], f.clean, '1.2.3.4.5') - self.assertFormErrors([u'Enter a valid IPv4 or IPv6 address.'], f.clean, '256.125.1.5') - self.assertEqual(f.clean('fe80::223:6cff:fe8a:2e8a'), u'fe80::223:6cff:fe8a:2e8a') - self.assertEqual(f.clean('2a02::223:6cff:fe8a:2e8a'), u'2a02::223:6cff:fe8a:2e8a') - self.assertFormErrors([u'Enter a valid IPv4 or IPv6 address.'], f.clean, '12345:2:3:4') - self.assertFormErrors([u'Enter a valid IPv4 or IPv6 address.'], f.clean, '1::2:3::4') - self.assertFormErrors([u'Enter a valid IPv4 or IPv6 address.'], f.clean, 'foo::223:6cff:fe8a:2e8a') - self.assertFormErrors([u'Enter a valid IPv4 or IPv6 address.'], f.clean, '1::2:3:4:5:6:7:8') - self.assertFormErrors([u'Enter a valid IPv4 or IPv6 address.'], f.clean, '1:2') + self.assertEqual(f.clean(''), '') + self.assertEqual(f.clean(None), '') + self.assertEqual(f.clean('127.0.0.1'), '127.0.0.1') + self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, 'foo') + self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '127.0.0.') + self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '1.2.3.4.5') + self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '256.125.1.5') + self.assertEqual(f.clean('fe80::223:6cff:fe8a:2e8a'), 'fe80::223:6cff:fe8a:2e8a') + self.assertEqual(f.clean('2a02::223:6cff:fe8a:2e8a'), '2a02::223:6cff:fe8a:2e8a') + self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '12345:2:3:4') + self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '1::2:3::4') + self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, 'foo::223:6cff:fe8a:2e8a') + self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '1::2:3:4:5:6:7:8') + self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '1:2') def test_generic_ipaddress_normalization(self): # Test the normalising code f = GenericIPAddressField() - self.assertEqual(f.clean('::ffff:0a0a:0a0a'), u'::ffff:10.10.10.10') - self.assertEqual(f.clean('::ffff:10.10.10.10'), u'::ffff:10.10.10.10') - self.assertEqual(f.clean('2001:000:a:0000:0:fe:fe:beef'), u'2001:0:a::fe:fe:beef') - self.assertEqual(f.clean('2001::a:0000:0:fe:fe:beef'), u'2001:0:a::fe:fe:beef') + self.assertEqual(f.clean('::ffff:0a0a:0a0a'), '::ffff:10.10.10.10') + self.assertEqual(f.clean('::ffff:10.10.10.10'), '::ffff:10.10.10.10') + self.assertEqual(f.clean('2001:000:a:0000:0:fe:fe:beef'), '2001:0:a::fe:fe:beef') + self.assertEqual(f.clean('2001::a:0000:0:fe:fe:beef'), '2001:0:a::fe:fe:beef') f = GenericIPAddressField(unpack_ipv4=True) - self.assertEqual(f.clean('::ffff:0a0a:0a0a'), u'10.10.10.10') + self.assertEqual(f.clean('::ffff:0a0a:0a0a'), '10.10.10.10') def test_smart_unicode(self): class Test: def __str__(self): - return 'ŠĐĆŽćžšđ' + return b'ŠĐĆŽćžšđ' class TestU: def __str__(self): return 'Foo' def __unicode__(self): - return u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111' + return '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111' - self.assertEqual(smart_unicode(Test()), u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111') - self.assertEqual(smart_unicode(TestU()), u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111') - self.assertEqual(smart_unicode(1), u'1') - self.assertEqual(smart_unicode('foo'), u'foo') + self.assertEqual(smart_unicode(Test()), '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111') + self.assertEqual(smart_unicode(TestU()), '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111') + self.assertEqual(smart_unicode(1), '1') + self.assertEqual(smart_unicode('foo'), 'foo') def test_accessing_clean(self): class UserForm(Form): @@ -583,7 +582,7 @@ class FormsExtraTestCase(TestCase, AssertFormErrorsMixin): f = UserForm({'username': 'SirRobin', 'password': 'blue'}) self.assertTrue(f.is_valid()) - self.assertEqual(f.cleaned_data['username'], u'sirrobin') + self.assertEqual(f.cleaned_data['username'], 'sirrobin') def test_overriding_errorlist(self): class DivErrorList(ErrorList): @@ -591,8 +590,8 @@ class FormsExtraTestCase(TestCase, AssertFormErrorsMixin): return self.as_divs() def as_divs(self): - if not self: return u'' - return u'
        %s
        ' % ''.join([u'
        %s
        ' % force_unicode(e) for e in self]) + if not self: return '' + return '
        %s
        ' % ''.join(['
        %s
        ' % force_unicode(e) for e in self]) class CommentForm(Form): name = CharField(max_length=50, required=False) @@ -774,7 +773,7 @@ class FormsExtraL10NTestCase(TestCase): a = GetDate({'mydate_month':'2', 'mydate_day':'31', 'mydate_year':'2010'}) self.assertFalse(a.is_valid()) # 'Geef een geldige datum op.' = 'Enter a valid date.' - self.assertEqual(a.errors, {'mydate': [u'Geef een geldige datum op.']}) + self.assertEqual(a.errors, {'mydate': ['Geef een geldige datum op.']}) def test_form_label_association(self): # label tag is correctly associated with first rendered dropdown diff --git a/tests/regressiontests/forms/tests/fields.py b/tests/regressiontests/forms/tests/fields.py index 4d442de3825..ebeb19c8fc4 100644 --- a/tests/regressiontests/forms/tests/fields.py +++ b/tests/regressiontests/forms/tests/fields.py @@ -24,6 +24,8 @@ Each Field's __init__() takes at least these parameters: Other than that, the Field subclasses have class-specific options for __init__(). For example, CharField has a max_length option. """ +from __future__ import unicode_literals + import datetime import pickle import re @@ -56,47 +58,47 @@ class FieldsTests(SimpleTestCase): def test_charfield_1(self): f = CharField() - self.assertEqual(u'1', f.clean(1)) - self.assertEqual(u'hello', f.clean('hello')) - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None) - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '') - self.assertEqual(u'[1, 2, 3]', f.clean([1, 2, 3])) + self.assertEqual('1', f.clean(1)) + self.assertEqual('hello', f.clean('hello')) + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') + self.assertEqual('[1, 2, 3]', f.clean([1, 2, 3])) self.assertEqual(f.max_length, None) self.assertEqual(f.min_length, None) def test_charfield_2(self): f = CharField(required=False) - self.assertEqual(u'1', f.clean(1)) - self.assertEqual(u'hello', f.clean('hello')) - self.assertEqual(u'', f.clean(None)) - self.assertEqual(u'', f.clean('')) - self.assertEqual(u'[1, 2, 3]', f.clean([1, 2, 3])) + self.assertEqual('1', f.clean(1)) + self.assertEqual('hello', f.clean('hello')) + self.assertEqual('', f.clean(None)) + self.assertEqual('', f.clean('')) + self.assertEqual('[1, 2, 3]', f.clean([1, 2, 3])) self.assertEqual(f.max_length, None) self.assertEqual(f.min_length, None) def test_charfield_3(self): f = CharField(max_length=10, required=False) - self.assertEqual(u'12345', f.clean('12345')) - self.assertEqual(u'1234567890', f.clean('1234567890')) - self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at most 10 characters (it has 11).']", f.clean, '1234567890a') + self.assertEqual('12345', f.clean('12345')) + self.assertEqual('1234567890', f.clean('1234567890')) + self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 10 characters (it has 11).'", f.clean, '1234567890a') self.assertEqual(f.max_length, 10) self.assertEqual(f.min_length, None) def test_charfield_4(self): f = CharField(min_length=10, required=False) - self.assertEqual(u'', f.clean('')) - self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at least 10 characters (it has 5).']", f.clean, '12345') - self.assertEqual(u'1234567890', f.clean('1234567890')) - self.assertEqual(u'1234567890a', f.clean('1234567890a')) + self.assertEqual('', f.clean('')) + self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 10 characters (it has 5).'", f.clean, '12345') + self.assertEqual('1234567890', f.clean('1234567890')) + self.assertEqual('1234567890a', f.clean('1234567890a')) self.assertEqual(f.max_length, None) self.assertEqual(f.min_length, 10) def test_charfield_5(self): f = CharField(min_length=10, required=True) - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '') - self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at least 10 characters (it has 5).']", f.clean, '12345') - self.assertEqual(u'1234567890', f.clean('1234567890')) - self.assertEqual(u'1234567890a', f.clean('1234567890a')) + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') + self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 10 characters (it has 5).'", f.clean, '12345') + self.assertEqual('1234567890', f.clean('1234567890')) + self.assertEqual('1234567890a', f.clean('1234567890a')) self.assertEqual(f.max_length, None) self.assertEqual(f.min_length, 10) @@ -121,18 +123,18 @@ class FieldsTests(SimpleTestCase): def test_integerfield_1(self): f = IntegerField() - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '') - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None) + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertEqual(1, f.clean('1')) self.assertEqual(True, isinstance(f.clean('1'), int)) self.assertEqual(23, f.clean('23')) - self.assertRaisesMessage(ValidationError, "[u'Enter a whole number.']", f.clean, 'a') + self.assertRaisesMessage(ValidationError, "'Enter a whole number.'", f.clean, 'a') self.assertEqual(42, f.clean(42)) - self.assertRaisesMessage(ValidationError, "[u'Enter a whole number.']", f.clean, 3.14) + self.assertRaisesMessage(ValidationError, "'Enter a whole number.'", f.clean, 3.14) self.assertEqual(1, f.clean('1 ')) self.assertEqual(1, f.clean(' 1')) self.assertEqual(1, f.clean(' 1 ')) - self.assertRaisesMessage(ValidationError, "[u'Enter a whole number.']", f.clean, '1a') + self.assertRaisesMessage(ValidationError, "'Enter a whole number.'", f.clean, '1a') self.assertEqual(f.max_value, None) self.assertEqual(f.min_value, None) @@ -145,29 +147,29 @@ class FieldsTests(SimpleTestCase): self.assertEqual(1, f.clean('1')) self.assertEqual(True, isinstance(f.clean('1'), int)) self.assertEqual(23, f.clean('23')) - self.assertRaisesMessage(ValidationError, "[u'Enter a whole number.']", f.clean, 'a') + self.assertRaisesMessage(ValidationError, "'Enter a whole number.'", f.clean, 'a') self.assertEqual(1, f.clean('1 ')) self.assertEqual(1, f.clean(' 1')) self.assertEqual(1, f.clean(' 1 ')) - self.assertRaisesMessage(ValidationError, "[u'Enter a whole number.']", f.clean, '1a') + self.assertRaisesMessage(ValidationError, "'Enter a whole number.'", f.clean, '1a') self.assertEqual(f.max_value, None) self.assertEqual(f.min_value, None) def test_integerfield_3(self): f = IntegerField(max_value=10) - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None) + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertEqual(1, f.clean(1)) self.assertEqual(10, f.clean(10)) - self.assertRaisesMessage(ValidationError, "[u'Ensure this value is less than or equal to 10.']", f.clean, 11) + self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 10.'", f.clean, 11) self.assertEqual(10, f.clean('10')) - self.assertRaisesMessage(ValidationError, "[u'Ensure this value is less than or equal to 10.']", f.clean, '11') + self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 10.'", f.clean, '11') self.assertEqual(f.max_value, 10) self.assertEqual(f.min_value, None) def test_integerfield_4(self): f = IntegerField(min_value=10) - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None) - self.assertRaisesMessage(ValidationError, "[u'Ensure this value is greater than or equal to 10.']", f.clean, 1) + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) + self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 10.'", f.clean, 1) self.assertEqual(10, f.clean(10)) self.assertEqual(11, f.clean(11)) self.assertEqual(10, f.clean('10')) @@ -177,14 +179,14 @@ class FieldsTests(SimpleTestCase): def test_integerfield_5(self): f = IntegerField(min_value=10, max_value=20) - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None) - self.assertRaisesMessage(ValidationError, "[u'Ensure this value is greater than or equal to 10.']", f.clean, 1) + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) + self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 10.'", f.clean, 1) self.assertEqual(10, f.clean(10)) self.assertEqual(11, f.clean(11)) self.assertEqual(10, f.clean('10')) self.assertEqual(11, f.clean('11')) self.assertEqual(20, f.clean(20)) - self.assertRaisesMessage(ValidationError, "[u'Ensure this value is less than or equal to 20.']", f.clean, 21) + self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 20.'", f.clean, 21) self.assertEqual(f.max_value, 20) self.assertEqual(f.min_value, 10) @@ -192,19 +194,19 @@ class FieldsTests(SimpleTestCase): def test_floatfield_1(self): f = FloatField() - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '') - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None) + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertEqual(1.0, f.clean('1')) self.assertEqual(True, isinstance(f.clean('1'), float)) self.assertEqual(23.0, f.clean('23')) self.assertEqual(3.1400000000000001, f.clean('3.14')) self.assertEqual(3.1400000000000001, f.clean(3.14)) self.assertEqual(42.0, f.clean(42)) - self.assertRaisesMessage(ValidationError, "[u'Enter a number.']", f.clean, 'a') + self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, 'a') self.assertEqual(1.0, f.clean('1.0 ')) self.assertEqual(1.0, f.clean(' 1.0')) self.assertEqual(1.0, f.clean(' 1.0 ')) - self.assertRaisesMessage(ValidationError, "[u'Enter a number.']", f.clean, '1.0a') + self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '1.0a') self.assertEqual(f.max_value, None) self.assertEqual(f.min_value, None) @@ -218,8 +220,8 @@ class FieldsTests(SimpleTestCase): def test_floatfield_3(self): f = FloatField(max_value=1.5, min_value=0.5) - self.assertRaisesMessage(ValidationError, "[u'Ensure this value is less than or equal to 1.5.']", f.clean, '1.6') - self.assertRaisesMessage(ValidationError, "[u'Ensure this value is greater than or equal to 0.5.']", f.clean, '0.4') + self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'", f.clean, '1.6') + self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'", f.clean, '0.4') self.assertEqual(1.5, f.clean('1.5')) self.assertEqual(0.5, f.clean('0.5')) self.assertEqual(f.max_value, 1.5) @@ -229,34 +231,34 @@ class FieldsTests(SimpleTestCase): def test_decimalfield_1(self): f = DecimalField(max_digits=4, decimal_places=2) - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '') - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None) + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertEqual(f.clean('1'), Decimal("1")) self.assertEqual(True, isinstance(f.clean('1'), Decimal)) self.assertEqual(f.clean('23'), Decimal("23")) self.assertEqual(f.clean('3.14'), Decimal("3.14")) self.assertEqual(f.clean(3.14), Decimal("3.14")) self.assertEqual(f.clean(Decimal('3.14')), Decimal("3.14")) - self.assertRaisesMessage(ValidationError, "[u'Enter a number.']", f.clean, 'NaN') - self.assertRaisesMessage(ValidationError, "[u'Enter a number.']", f.clean, 'Inf') - self.assertRaisesMessage(ValidationError, "[u'Enter a number.']", f.clean, '-Inf') - self.assertRaisesMessage(ValidationError, "[u'Enter a number.']", f.clean, 'a') - self.assertRaisesMessage(ValidationError, "[u'Enter a number.']", f.clean, u'łąść') + self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, 'NaN') + self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, 'Inf') + self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '-Inf') + self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, 'a') + self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, 'łąść') self.assertEqual(f.clean('1.0 '), Decimal("1.0")) self.assertEqual(f.clean(' 1.0'), Decimal("1.0")) self.assertEqual(f.clean(' 1.0 '), Decimal("1.0")) - self.assertRaisesMessage(ValidationError, "[u'Enter a number.']", f.clean, '1.0a') - self.assertRaisesMessage(ValidationError, "[u'Ensure that there are no more than 4 digits in total.']", f.clean, '123.45') - self.assertRaisesMessage(ValidationError, "[u'Ensure that there are no more than 2 decimal places.']", f.clean, '1.234') - self.assertRaisesMessage(ValidationError, "[u'Ensure that there are no more than 2 digits before the decimal point.']", f.clean, '123.4') + self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '1.0a') + self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'", f.clean, '123.45') + self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'", f.clean, '1.234') + self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 digits before the decimal point.'", f.clean, '123.4') self.assertEqual(f.clean('-12.34'), Decimal("-12.34")) - self.assertRaisesMessage(ValidationError, "[u'Ensure that there are no more than 4 digits in total.']", f.clean, '-123.45') + self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'", f.clean, '-123.45') self.assertEqual(f.clean('-.12'), Decimal("-0.12")) self.assertEqual(f.clean('-00.12'), Decimal("-0.12")) self.assertEqual(f.clean('-000.12'), Decimal("-0.12")) - self.assertRaisesMessage(ValidationError, "[u'Ensure that there are no more than 2 decimal places.']", f.clean, '-000.123') - self.assertRaisesMessage(ValidationError, "[u'Ensure that there are no more than 4 digits in total.']", f.clean, '-000.12345') - self.assertRaisesMessage(ValidationError, "[u'Enter a number.']", f.clean, '--0.12') + self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'", f.clean, '-000.123') + self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'", f.clean, '-000.12345') + self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '--0.12') self.assertEqual(f.max_digits, 4) self.assertEqual(f.decimal_places, 2) self.assertEqual(f.max_value, None) @@ -274,8 +276,8 @@ class FieldsTests(SimpleTestCase): def test_decimalfield_3(self): f = DecimalField(max_digits=4, decimal_places=2, max_value=Decimal('1.5'), min_value=Decimal('0.5')) - self.assertRaisesMessage(ValidationError, "[u'Ensure this value is less than or equal to 1.5.']", f.clean, '1.6') - self.assertRaisesMessage(ValidationError, "[u'Ensure this value is greater than or equal to 0.5.']", f.clean, '0.4') + self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'", f.clean, '1.6') + self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'", f.clean, '0.4') self.assertEqual(f.clean('1.5'), Decimal("1.5")) self.assertEqual(f.clean('0.5'), Decimal("0.5")) self.assertEqual(f.clean('.5'), Decimal("0.5")) @@ -287,7 +289,7 @@ class FieldsTests(SimpleTestCase): def test_decimalfield_4(self): f = DecimalField(decimal_places=2) - self.assertRaisesMessage(ValidationError, "[u'Ensure that there are no more than 2 decimal places.']", f.clean, '0.00000001') + self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'", f.clean, '0.00000001') def test_decimalfield_5(self): f = DecimalField(max_digits=3) @@ -297,13 +299,13 @@ class FieldsTests(SimpleTestCase): self.assertEqual(f.clean('0000000.100'), Decimal("0.100")) # Only leading whole zeros "collapse" to one digit. self.assertEqual(f.clean('000000.02'), Decimal('0.02')) - self.assertRaisesMessage(ValidationError, "[u'Ensure that there are no more than 3 digits in total.']", f.clean, '000000.0002') + self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 3 digits in total.'", f.clean, '000000.0002') self.assertEqual(f.clean('.002'), Decimal("0.002")) def test_decimalfield_6(self): f = DecimalField(max_digits=2, decimal_places=2) self.assertEqual(f.clean('.01'), Decimal(".01")) - self.assertRaisesMessage(ValidationError, "[u'Ensure that there are no more than 0 digits before the decimal point.']", f.clean, '1.1') + self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 0 digits before the decimal point.'", f.clean, '1.1') # DateField ################################################################### @@ -321,10 +323,10 @@ class FieldsTests(SimpleTestCase): self.assertEqual(datetime.date(2006, 10, 25), f.clean('October 25, 2006')) self.assertEqual(datetime.date(2006, 10, 25), f.clean('25 October 2006')) self.assertEqual(datetime.date(2006, 10, 25), f.clean('25 October, 2006')) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '2006-4-31') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '200a-10-25') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '25/10/06') - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None) + self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '2006-4-31') + self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '200a-10-25') + self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '25/10/06') + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) def test_datefield_2(self): f = DateField(required=False) @@ -338,9 +340,9 @@ class FieldsTests(SimpleTestCase): self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.date(2006, 10, 25))) self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.datetime(2006, 10, 25, 14, 30))) self.assertEqual(datetime.date(2006, 10, 25), f.clean('2006 10 25')) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '2006-10-25') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '10/25/2006') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '10/25/06') + self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '2006-10-25') + self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '10/25/2006') + self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '10/25/06') def test_datefield_4(self): # Test whitespace stripping behavior (#5714) @@ -351,7 +353,7 @@ class FieldsTests(SimpleTestCase): self.assertEqual(datetime.date(2006, 10, 25), f.clean(' October 25 2006 ')) self.assertEqual(datetime.date(2006, 10, 25), f.clean(' October 25, 2006 ')) self.assertEqual(datetime.date(2006, 10, 25), f.clean(' 25 October 2006 ')) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.']", f.clean, ' ') + self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ' ') # TimeField ################################################################### @@ -361,8 +363,8 @@ class FieldsTests(SimpleTestCase): self.assertEqual(datetime.time(14, 25, 59), f.clean(datetime.time(14, 25, 59))) self.assertEqual(datetime.time(14, 25), f.clean('14:25')) self.assertEqual(datetime.time(14, 25, 59), f.clean('14:25:59')) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid time.']", f.clean, 'hello') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid time.']", f.clean, '1:24 p.m.') + self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, 'hello') + self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, '1:24 p.m.') def test_timefield_2(self): f = TimeField(input_formats=['%I:%M %p']) @@ -370,14 +372,14 @@ class FieldsTests(SimpleTestCase): self.assertEqual(datetime.time(14, 25, 59), f.clean(datetime.time(14, 25, 59))) self.assertEqual(datetime.time(4, 25), f.clean('4:25 AM')) self.assertEqual(datetime.time(16, 25), f.clean('4:25 PM')) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid time.']", f.clean, '14:30:45') + self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, '14:30:45') def test_timefield_3(self): f = TimeField() # Test whitespace stripping behavior (#5714) self.assertEqual(datetime.time(14, 25), f.clean(' 14:25 ')) self.assertEqual(datetime.time(14, 25, 59), f.clean(' 14:25:59 ')) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ' ') + self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ' ') # DateTimeField ############################################################### @@ -403,8 +405,8 @@ class FieldsTests(SimpleTestCase): self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/06 14:30:00')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/06 14:30')) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean('10/25/06')) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid date/time.']", f.clean, 'hello') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid date/time.']", f.clean, '2006-10-25 4:30 p.m.') + self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'", f.clean, 'hello') + self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'", f.clean, '2006-10-25 4:30 p.m.') def test_datetimefield_2(self): f = DateTimeField(input_formats=['%Y %m %d %I:%M %p']) @@ -413,7 +415,7 @@ class FieldsTests(SimpleTestCase): self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59, 200), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('2006 10 25 2:30 PM')) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid date/time.']", f.clean, '2006-10-25 14:30:45') + self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'", f.clean, '2006-10-25 14:30:45') def test_datetimefield_3(self): f = DateTimeField(required=False) @@ -432,51 +434,51 @@ class FieldsTests(SimpleTestCase): self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(' 10/25/2006 ')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean(' 10/25/06 14:30:45 ')) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(' 10/25/06 ')) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid date/time.']", f.clean, ' ') + self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'", f.clean, ' ') def test_datetimefield_5(self): - f = DateTimeField(input_formats=[u'%Y.%m.%d %H:%M:%S.%f']) + f = DateTimeField(input_formats=['%Y.%m.%d %H:%M:%S.%f']) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45, 200), f.clean('2006.10.25 14:30:45.0002')) # RegexField ################################################################## def test_regexfield_1(self): f = RegexField('^\d[A-F]\d$') - self.assertEqual(u'2A2', f.clean('2A2')) - self.assertEqual(u'3F3', f.clean('3F3')) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '3G3') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, ' 2A2') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '2A2 ') - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '') + self.assertEqual('2A2', f.clean('2A2')) + self.assertEqual('3F3', f.clean('3F3')) + self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '3G3') + self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, ' 2A2') + self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '2A2 ') + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') def test_regexfield_2(self): f = RegexField('^\d[A-F]\d$', required=False) - self.assertEqual(u'2A2', f.clean('2A2')) - self.assertEqual(u'3F3', f.clean('3F3')) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '3G3') - self.assertEqual(u'', f.clean('')) + self.assertEqual('2A2', f.clean('2A2')) + self.assertEqual('3F3', f.clean('3F3')) + self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '3G3') + self.assertEqual('', f.clean('')) def test_regexfield_3(self): f = RegexField(re.compile('^\d[A-F]\d$')) - self.assertEqual(u'2A2', f.clean('2A2')) - self.assertEqual(u'3F3', f.clean('3F3')) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '3G3') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, ' 2A2') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '2A2 ') + self.assertEqual('2A2', f.clean('2A2')) + self.assertEqual('3F3', f.clean('3F3')) + self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '3G3') + self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, ' 2A2') + self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '2A2 ') def test_regexfield_4(self): f = RegexField('^\d\d\d\d$', error_message='Enter a four-digit number.') - self.assertEqual(u'1234', f.clean('1234')) - self.assertRaisesMessage(ValidationError, "[u'Enter a four-digit number.']", f.clean, '123') - self.assertRaisesMessage(ValidationError, "[u'Enter a four-digit number.']", f.clean, 'abcd') + self.assertEqual('1234', f.clean('1234')) + self.assertRaisesMessage(ValidationError, "'Enter a four-digit number.'", f.clean, '123') + self.assertRaisesMessage(ValidationError, "'Enter a four-digit number.'", f.clean, 'abcd') def test_regexfield_5(self): f = RegexField('^\d+$', min_length=5, max_length=10) - self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at least 5 characters (it has 3).']", f.clean, '123') - self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at least 5 characters (it has 3).', u'Enter a valid value.']", f.clean, 'abc') - self.assertEqual(u'12345', f.clean('12345')) - self.assertEqual(u'1234567890', f.clean('1234567890')) - self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at most 10 characters (it has 11).']", f.clean, '12345678901') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '12345a') + self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 5 characters (it has 3).'", f.clean, '123') + self.assertRaisesRegexp(ValidationError, "'Ensure this value has at least 5 characters \(it has 3\)\.', u?'Enter a valid value\.'", f.clean, 'abc') + self.assertEqual('12345', f.clean('12345')) + self.assertEqual('1234567890', f.clean('1234567890')) + self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 10 characters (it has 11).'", f.clean, '12345678901') + self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '12345a') def test_regexfield_6(self): """ @@ -489,27 +491,27 @@ class FieldsTests(SimpleTestCase): def test_change_regex_after_init(self): f = RegexField('^[a-z]+$') f.regex = '^\d+$' - self.assertEqual(u'1234', f.clean('1234')) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, 'abcd') + self.assertEqual('1234', f.clean('1234')) + self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, 'abcd') # EmailField ################################################################## def test_emailfield_1(self): f = EmailField() - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '') - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None) - self.assertEqual(u'person@example.com', f.clean('person@example.com')) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo@') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo@bar') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'example@invalid-.com') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'example@-invalid.com') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'example@inv-.alid-.com') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'example@inv-.-alid.com') - self.assertEqual(u'example@valid-----hyphens.com', f.clean('example@valid-----hyphens.com')) - self.assertEqual(u'example@valid-with-hyphens.com', f.clean('example@valid-with-hyphens.com')) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'example@.com') - self.assertEqual(u'local@domain.with.idn.xyz\xe4\xf6\xfc\xdfabc.part.com', f.clean('local@domain.with.idn.xyzäöüßabc.part.com')) + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) + self.assertEqual('person@example.com', f.clean('person@example.com')) + self.assertRaisesMessage(ValidationError, "'Enter a valid e-mail address.'", f.clean, 'foo') + self.assertRaisesMessage(ValidationError, "'Enter a valid e-mail address.'", f.clean, 'foo@') + self.assertRaisesMessage(ValidationError, "'Enter a valid e-mail address.'", f.clean, 'foo@bar') + self.assertRaisesMessage(ValidationError, "'Enter a valid e-mail address.'", f.clean, 'example@invalid-.com') + self.assertRaisesMessage(ValidationError, "'Enter a valid e-mail address.'", f.clean, 'example@-invalid.com') + self.assertRaisesMessage(ValidationError, "'Enter a valid e-mail address.'", f.clean, 'example@inv-.alid-.com') + self.assertRaisesMessage(ValidationError, "'Enter a valid e-mail address.'", f.clean, 'example@inv-.-alid.com') + self.assertEqual('example@valid-----hyphens.com', f.clean('example@valid-----hyphens.com')) + self.assertEqual('example@valid-with-hyphens.com', f.clean('example@valid-with-hyphens.com')) + self.assertRaisesMessage(ValidationError, "'Enter a valid e-mail address.'", f.clean, 'example@.com') + self.assertEqual('local@domain.with.idn.xyz\xe4\xf6\xfc\xdfabc.part.com', f.clean('local@domain.with.idn.xyzäöüßabc.part.com')) def test_email_regexp_for_performance(self): f = EmailField() @@ -517,50 +519,50 @@ class FieldsTests(SimpleTestCase): # if the security fix isn't in place. self.assertRaisesMessage( ValidationError, - "[u'Enter a valid e-mail address.']", + "'Enter a valid e-mail address.'", f.clean, 'viewx3dtextx26qx3d@yahoo.comx26latlngx3d15854521645943074058' ) def test_emailfield_2(self): f = EmailField(required=False) - self.assertEqual(u'', f.clean('')) - self.assertEqual(u'', f.clean(None)) - self.assertEqual(u'person@example.com', f.clean('person@example.com')) - self.assertEqual(u'example@example.com', f.clean(' example@example.com \t \t ')) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo@') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo@bar') + self.assertEqual('', f.clean('')) + self.assertEqual('', f.clean(None)) + self.assertEqual('person@example.com', f.clean('person@example.com')) + self.assertEqual('example@example.com', f.clean(' example@example.com \t \t ')) + self.assertRaisesMessage(ValidationError, "'Enter a valid e-mail address.'", f.clean, 'foo') + self.assertRaisesMessage(ValidationError, "'Enter a valid e-mail address.'", f.clean, 'foo@') + self.assertRaisesMessage(ValidationError, "'Enter a valid e-mail address.'", f.clean, 'foo@bar') def test_emailfield_3(self): f = EmailField(min_length=10, max_length=15) - self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at least 10 characters (it has 9).']", f.clean, 'a@foo.com') - self.assertEqual(u'alf@foo.com', f.clean('alf@foo.com')) - self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at most 15 characters (it has 20).']", f.clean, 'alf123456788@foo.com') + self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 10 characters (it has 9).'", f.clean, 'a@foo.com') + self.assertEqual('alf@foo.com', f.clean('alf@foo.com')) + self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 15 characters (it has 20).'", f.clean, 'alf123456788@foo.com') # FileField ################################################################## def test_filefield_1(self): f = FileField() - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '') - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '', '') + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '', '') self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf')) - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None) - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None, '') + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None, '') self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf')) - self.assertRaisesMessage(ValidationError, "[u'No file was submitted. Check the encoding type on the form.']", f.clean, SimpleUploadedFile('', b'')) - self.assertRaisesMessage(ValidationError, "[u'No file was submitted. Check the encoding type on the form.']", f.clean, SimpleUploadedFile('', b''), '') + self.assertRaisesMessage(ValidationError, "'No file was submitted. Check the encoding type on the form.'", f.clean, SimpleUploadedFile('', b'')) + self.assertRaisesMessage(ValidationError, "'No file was submitted. Check the encoding type on the form.'", f.clean, SimpleUploadedFile('', b''), '') self.assertEqual('files/test3.pdf', f.clean(None, 'files/test3.pdf')) - self.assertRaisesMessage(ValidationError, "[u'No file was submitted. Check the encoding type on the form.']", f.clean, 'some content that is not a file') - self.assertRaisesMessage(ValidationError, "[u'The submitted file is empty.']", f.clean, SimpleUploadedFile('name', None)) - self.assertRaisesMessage(ValidationError, "[u'The submitted file is empty.']", f.clean, SimpleUploadedFile('name', b'')) + self.assertRaisesMessage(ValidationError, "'No file was submitted. Check the encoding type on the form.'", f.clean, 'some content that is not a file') + self.assertRaisesMessage(ValidationError, "'The submitted file is empty.'", f.clean, SimpleUploadedFile('name', None)) + self.assertRaisesMessage(ValidationError, "'The submitted file is empty.'", f.clean, SimpleUploadedFile('name', b'')) self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content')))) - self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', u'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))))) + self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))))) self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content'), 'files/test4.pdf'))) def test_filefield_2(self): f = FileField(max_length = 5) - self.assertRaisesMessage(ValidationError, "[u'Ensure this filename has at most 5 characters (it has 18).']", f.clean, SimpleUploadedFile('test_maxlength.txt', b'hello world')) + self.assertRaisesMessage(ValidationError, "'Ensure this filename has at most 5 characters (it has 18).'", f.clean, SimpleUploadedFile('test_maxlength.txt', b'hello world')) self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf')) self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf')) self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content')))) @@ -574,92 +576,92 @@ class FieldsTests(SimpleTestCase): def test_urlfield_1(self): f = URLField() - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '') - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None) - self.assertEqual(u'http://localhost/', f.clean('http://localhost')) - self.assertEqual(u'http://example.com/', f.clean('http://example.com')) - self.assertEqual(u'http://example.com./', f.clean('http://example.com.')) - self.assertEqual(u'http://www.example.com/', f.clean('http://www.example.com')) - self.assertEqual(u'http://www.example.com:8000/test', f.clean('http://www.example.com:8000/test')) - self.assertEqual(u'http://valid-with-hyphens.com/', f.clean('valid-with-hyphens.com')) - self.assertEqual(u'http://subdomain.domain.com/', f.clean('subdomain.domain.com')) - self.assertEqual(u'http://200.8.9.10/', f.clean('http://200.8.9.10')) - self.assertEqual(u'http://200.8.9.10:8000/test', f.clean('http://200.8.9.10:8000/test')) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'foo') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example.') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'com.') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, '.') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://.com') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://invalid-.com') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://-invalid.com') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://inv-.alid-.com') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://inv-.-alid.com') - self.assertEqual(u'http://valid-----hyphens.com/', f.clean('http://valid-----hyphens.com')) - self.assertEqual(u'http://some.idn.xyz\xe4\xf6\xfc\xdfabc.domain.com:123/blah', f.clean('http://some.idn.xyzäöüßabc.domain.com:123/blah')) - self.assertEqual(u'http://www.example.com/s/http://code.djangoproject.com/ticket/13804', f.clean('www.example.com/s/http://code.djangoproject.com/ticket/13804')) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, '[a') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://[a') + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) + self.assertEqual('http://localhost/', f.clean('http://localhost')) + self.assertEqual('http://example.com/', f.clean('http://example.com')) + self.assertEqual('http://example.com./', f.clean('http://example.com.')) + self.assertEqual('http://www.example.com/', f.clean('http://www.example.com')) + self.assertEqual('http://www.example.com:8000/test', f.clean('http://www.example.com:8000/test')) + self.assertEqual('http://valid-with-hyphens.com/', f.clean('valid-with-hyphens.com')) + self.assertEqual('http://subdomain.domain.com/', f.clean('subdomain.domain.com')) + self.assertEqual('http://200.8.9.10/', f.clean('http://200.8.9.10')) + self.assertEqual('http://200.8.9.10:8000/test', f.clean('http://200.8.9.10:8000/test')) + self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'foo') + self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://') + self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://example') + self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://example.') + self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'com.') + self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, '.') + self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://.com') + self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://invalid-.com') + self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://-invalid.com') + self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://inv-.alid-.com') + self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://inv-.-alid.com') + self.assertEqual('http://valid-----hyphens.com/', f.clean('http://valid-----hyphens.com')) + self.assertEqual('http://some.idn.xyz\xe4\xf6\xfc\xdfabc.domain.com:123/blah', f.clean('http://some.idn.xyzäöüßabc.domain.com:123/blah')) + self.assertEqual('http://www.example.com/s/http://code.djangoproject.com/ticket/13804', f.clean('www.example.com/s/http://code.djangoproject.com/ticket/13804')) + self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, '[a') + self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://[a') def test_url_regex_ticket11198(self): f = URLField() # hangs "forever" if catastrophic backtracking in ticket:#11198 not fixed - self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://%s' % ("X"*200,)) + self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://%s' % ("X"*200,)) # a second test, to make sure the problem is really addressed, even on # domains that don't fail the domain label length check in the regex - self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://%s' % ("X"*60,)) + self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://%s' % ("X"*60,)) def test_urlfield_2(self): f = URLField(required=False) - self.assertEqual(u'', f.clean('')) - self.assertEqual(u'', f.clean(None)) - self.assertEqual(u'http://example.com/', f.clean('http://example.com')) - self.assertEqual(u'http://www.example.com/', f.clean('http://www.example.com')) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'foo') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example.') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://.com') + self.assertEqual('', f.clean('')) + self.assertEqual('', f.clean(None)) + self.assertEqual('http://example.com/', f.clean('http://example.com')) + self.assertEqual('http://www.example.com/', f.clean('http://www.example.com')) + self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'foo') + self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://') + self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://example') + self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://example.') + self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://.com') def test_urlfield_5(self): f = URLField(min_length=15, max_length=20) - self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at least 15 characters (it has 13).']", f.clean, 'http://f.com') - self.assertEqual(u'http://example.com/', f.clean('http://example.com')) - self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at most 20 characters (it has 38).']", f.clean, 'http://abcdefghijklmnopqrstuvwxyz.com') + self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 15 characters (it has 13).'", f.clean, 'http://f.com') + self.assertEqual('http://example.com/', f.clean('http://example.com')) + self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 38).'", f.clean, 'http://abcdefghijklmnopqrstuvwxyz.com') def test_urlfield_6(self): f = URLField(required=False) - self.assertEqual(u'http://example.com/', f.clean('example.com')) - self.assertEqual(u'', f.clean('')) - self.assertEqual(u'https://example.com/', f.clean('https://example.com')) + self.assertEqual('http://example.com/', f.clean('example.com')) + self.assertEqual('', f.clean('')) + self.assertEqual('https://example.com/', f.clean('https://example.com')) def test_urlfield_7(self): f = URLField() - self.assertEqual(u'http://example.com/', f.clean('http://example.com')) - self.assertEqual(u'http://example.com/test', f.clean('http://example.com/test')) + self.assertEqual('http://example.com/', f.clean('http://example.com')) + self.assertEqual('http://example.com/test', f.clean('http://example.com/test')) def test_urlfield_8(self): # ticket #11826 f = URLField() - self.assertEqual(u'http://example.com/?some_param=some_value', f.clean('http://example.com?some_param=some_value')) + self.assertEqual('http://example.com/?some_param=some_value', f.clean('http://example.com?some_param=some_value')) def test_urlfield_9(self): f = URLField() urls = ( - u'http://עברית.idn.icann.org/', - u'http://sãopaulo.com/', - u'http://sãopaulo.com.br/', - u'http://пример.испытание/', - u'http://مثال.إختبار/', - u'http://例子.测试/', - u'http://例子.測試/', - u'http://उदाहरण.परीक्षा/', - u'http://例え.テスト/', - u'http://مثال.آزمایشی/', - u'http://실례.테스트/', - u'http://العربية.idn.icann.org/', + 'http://עברית.idn.icann.org/', + 'http://sãopaulo.com/', + 'http://sãopaulo.com.br/', + 'http://пример.испытание/', + 'http://مثال.إختبار/', + 'http://例子.测试/', + 'http://例子.測試/', + 'http://उदाहरण.परीक्षा/', + 'http://例え.テスト/', + 'http://مثال.آزمایشی/', + 'http://실례.테스트/', + 'http://العربية.idn.icann.org/', ) for url in urls: # Valid IDN @@ -667,21 +669,21 @@ class FieldsTests(SimpleTestCase): def test_urlfield_not_string(self): f = URLField(required=False) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 23) + self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 23) # BooleanField ################################################################ def test_booleanfield_1(self): f = BooleanField() - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '') - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None) + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertEqual(True, f.clean(True)) - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, False) + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, False) self.assertEqual(True, f.clean(1)) - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, 0) + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, 0) self.assertEqual(True, f.clean('Django rocks')) self.assertEqual(True, f.clean('True')) - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, 'False') + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, 'False') def test_booleanfield_2(self): f = BooleanField(required=False) @@ -705,34 +707,34 @@ class FieldsTests(SimpleTestCase): def test_choicefield_1(self): f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')]) - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '') - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None) - self.assertEqual(u'1', f.clean(1)) - self.assertEqual(u'1', f.clean('1')) - self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, '3') + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) + self.assertEqual('1', f.clean(1)) + self.assertEqual('1', f.clean('1')) + self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, '3') def test_choicefield_2(self): f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False) - self.assertEqual(u'', f.clean('')) - self.assertEqual(u'', f.clean(None)) - self.assertEqual(u'1', f.clean(1)) - self.assertEqual(u'1', f.clean('1')) - self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, '3') + self.assertEqual('', f.clean('')) + self.assertEqual('', f.clean(None)) + self.assertEqual('1', f.clean(1)) + self.assertEqual('1', f.clean('1')) + self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, '3') def test_choicefield_3(self): f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')]) - self.assertEqual(u'J', f.clean('J')) - self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. John is not one of the available choices.']", f.clean, 'John') + self.assertEqual('J', f.clean('J')) + self.assertRaisesMessage(ValidationError, "'Select a valid choice. John is not one of the available choices.'", f.clean, 'John') def test_choicefield_4(self): f = ChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3','A'),('4','B'))), ('5','Other')]) - self.assertEqual(u'1', f.clean(1)) - self.assertEqual(u'1', f.clean('1')) - self.assertEqual(u'3', f.clean(3)) - self.assertEqual(u'3', f.clean('3')) - self.assertEqual(u'5', f.clean(5)) - self.assertEqual(u'5', f.clean('5')) - self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. 6 is not one of the available choices.']", f.clean, '6') + self.assertEqual('1', f.clean(1)) + self.assertEqual('1', f.clean('1')) + self.assertEqual('3', f.clean(3)) + self.assertEqual('3', f.clean('3')) + self.assertEqual('5', f.clean(5)) + self.assertEqual('5', f.clean('5')) + self.assertRaisesMessage(ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", f.clean, '6') # TypedChoiceField ############################################################ # TypedChoiceField is just like ChoiceField, except that coerced types will @@ -741,7 +743,7 @@ class FieldsTests(SimpleTestCase): def test_typedchoicefield_1(self): f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) self.assertEqual(1, f.clean('1')) - self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. 2 is not one of the available choices.']", f.clean, '2') + self.assertRaisesMessage(ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", f.clean, '2') def test_typedchoicefield_2(self): # Different coercion, same validation. @@ -755,11 +757,11 @@ class FieldsTests(SimpleTestCase): def test_typedchoicefield_4(self): # Even more weirdness: if you have a valid choice but your coercion function - # can't coerce, you'll still get a validation error. Don't do this! + # can't coerce, yo'll still get a validation error. Don't do this! f = TypedChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int) - self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. B is not one of the available choices.']", f.clean, 'B') + self.assertRaisesMessage(ValidationError, "'Select a valid choice. B is not one of the available choices.'", f.clean, 'B') # Required fields require values - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '') + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') def test_typedchoicefield_5(self): # Non-required fields aren't required @@ -821,42 +823,42 @@ class FieldsTests(SimpleTestCase): def test_multiplechoicefield_1(self): f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')]) - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '') - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None) - self.assertEqual([u'1'], f.clean([1])) - self.assertEqual([u'1'], f.clean(['1'])) - self.assertEqual([u'1', u'2'], f.clean(['1', '2'])) - self.assertEqual([u'1', u'2'], f.clean([1, '2'])) - self.assertEqual([u'1', u'2'], f.clean((1, '2'))) - self.assertRaisesMessage(ValidationError, "[u'Enter a list of values.']", f.clean, 'hello') - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, []) - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, ()) - self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, ['3']) + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) + self.assertEqual(['1'], f.clean([1])) + self.assertEqual(['1'], f.clean(['1'])) + self.assertEqual(['1', '2'], f.clean(['1', '2'])) + self.assertEqual(['1', '2'], f.clean([1, '2'])) + self.assertEqual(['1', '2'], f.clean((1, '2'))) + self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello') + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, []) + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, ()) + self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, ['3']) def test_multiplechoicefield_2(self): f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False) self.assertEqual([], f.clean('')) self.assertEqual([], f.clean(None)) - self.assertEqual([u'1'], f.clean([1])) - self.assertEqual([u'1'], f.clean(['1'])) - self.assertEqual([u'1', u'2'], f.clean(['1', '2'])) - self.assertEqual([u'1', u'2'], f.clean([1, '2'])) - self.assertEqual([u'1', u'2'], f.clean((1, '2'))) - self.assertRaisesMessage(ValidationError, "[u'Enter a list of values.']", f.clean, 'hello') + self.assertEqual(['1'], f.clean([1])) + self.assertEqual(['1'], f.clean(['1'])) + self.assertEqual(['1', '2'], f.clean(['1', '2'])) + self.assertEqual(['1', '2'], f.clean([1, '2'])) + self.assertEqual(['1', '2'], f.clean((1, '2'))) + self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello') self.assertEqual([], f.clean([])) self.assertEqual([], f.clean(())) - self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, ['3']) + self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, ['3']) def test_multiplechoicefield_3(self): f = MultipleChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3','A'),('4','B'))), ('5','Other')]) - self.assertEqual([u'1'], f.clean([1])) - self.assertEqual([u'1'], f.clean(['1'])) - self.assertEqual([u'1', u'5'], f.clean([1, 5])) - self.assertEqual([u'1', u'5'], f.clean([1, '5'])) - self.assertEqual([u'1', u'5'], f.clean(['1', 5])) - self.assertEqual([u'1', u'5'], f.clean(['1', '5'])) - self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. 6 is not one of the available choices.']", f.clean, ['6']) - self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. 6 is not one of the available choices.']", f.clean, ['1','6']) + self.assertEqual(['1'], f.clean([1])) + self.assertEqual(['1'], f.clean(['1'])) + self.assertEqual(['1', '5'], f.clean([1, 5])) + self.assertEqual(['1', '5'], f.clean([1, '5'])) + self.assertEqual(['1', '5'], f.clean(['1', 5])) + self.assertEqual(['1', '5'], f.clean(['1', '5'])) + self.assertRaisesMessage(ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", f.clean, ['6']) + self.assertRaisesMessage(ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", f.clean, ['1','6']) # TypedMultipleChoiceField ############################################################ # TypedMultipleChoiceField is just like MultipleChoiceField, except that coerced types @@ -865,7 +867,7 @@ class FieldsTests(SimpleTestCase): def test_typedmultiplechoicefield_1(self): f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) self.assertEqual([1], f.clean(['1'])) - self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. 2 is not one of the available choices.']", f.clean, ['2']) + self.assertRaisesMessage(ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", f.clean, ['2']) def test_typedmultiplechoicefield_2(self): # Different coercion, same validation. @@ -880,15 +882,15 @@ class FieldsTests(SimpleTestCase): def test_typedmultiplechoicefield_4(self): f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) self.assertEqual([1, -1], f.clean(['1','-1'])) - self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. 2 is not one of the available choices.']", f.clean, ['1','2']) + self.assertRaisesMessage(ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", f.clean, ['1','2']) def test_typedmultiplechoicefield_5(self): # Even more weirdness: if you have a valid choice but your coercion function # can't coerce, you'll still get a validation error. Don't do this! f = TypedMultipleChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int) - self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. B is not one of the available choices.']", f.clean, ['B']) + self.assertRaisesMessage(ValidationError, "'Select a valid choice. B is not one of the available choices.'", f.clean, ['B']) # Required fields require values - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, []) + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, []) def test_typedmultiplechoicefield_6(self): # Non-required fields aren't required @@ -904,19 +906,19 @@ class FieldsTests(SimpleTestCase): def test_combofield_1(self): f = ComboField(fields=[CharField(max_length=20), EmailField()]) - self.assertEqual(u'test@example.com', f.clean('test@example.com')) - self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at most 20 characters (it has 28).']", f.clean, 'longemailaddress@example.com') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'not an e-mail') - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '') - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None) + self.assertEqual('test@example.com', f.clean('test@example.com')) + self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 28).'", f.clean, 'longemailaddress@example.com') + self.assertRaisesMessage(ValidationError, "'Enter a valid e-mail address.'", f.clean, 'not an e-mail') + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) def test_combofield_2(self): f = ComboField(fields=[CharField(max_length=20), EmailField()], required=False) - self.assertEqual(u'test@example.com', f.clean('test@example.com')) - self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at most 20 characters (it has 28).']", f.clean, 'longemailaddress@example.com') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'not an e-mail') - self.assertEqual(u'', f.clean('')) - self.assertEqual(u'', f.clean(None)) + self.assertEqual('test@example.com', f.clean('test@example.com')) + self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 28).'", f.clean, 'longemailaddress@example.com') + self.assertRaisesMessage(ValidationError, "'Enter a valid e-mail address.'", f.clean, 'not an e-mail') + self.assertEqual('', f.clean('')) + self.assertEqual('', f.clean(None)) # FilePathField ############################################################### @@ -943,7 +945,7 @@ class FieldsTests(SimpleTestCase): for exp, got in zip(expected, fix_os_paths(f.choices)): self.assertEqual(exp[1], got[1]) self.assertTrue(got[0].endswith(exp[0])) - self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. fields.py is not one of the available choices.']", f.clean, 'fields.py') + self.assertRaisesMessage(ValidationError, "'Select a valid choice. fields.py is not one of the available choices.'", f.clean, 'fields.py') assert fix_os_paths(f.clean(path + 'fields.py')).endswith('/django/forms/fields.py') def test_filepathfield_3(self): @@ -1018,12 +1020,12 @@ class FieldsTests(SimpleTestCase): f = SplitDateTimeField() assert isinstance(f.widget, SplitDateTimeWidget) self.assertEqual(datetime.datetime(2006, 1, 10, 7, 30), f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)])) - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None) - self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '') - self.assertRaisesMessage(ValidationError, "[u'Enter a list of values.']", f.clean, 'hello') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.', u'Enter a valid time.']", f.clean, ['hello', 'there']) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ['2006-01-10', 'there']) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.']", f.clean, ['hello', '07:30']) + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) + self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') + self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello') + self.assertRaisesRegexp(ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'", f.clean, ['hello', 'there']) + self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', 'there']) + self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ['hello', '07:30']) def test_splitdatetimefield_2(self): f = SplitDateTimeField(required=False) @@ -1033,10 +1035,10 @@ class FieldsTests(SimpleTestCase): self.assertEqual(None, f.clean('')) self.assertEqual(None, f.clean([''])) self.assertEqual(None, f.clean(['', ''])) - self.assertRaisesMessage(ValidationError, "[u'Enter a list of values.']", f.clean, 'hello') - self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.', u'Enter a valid time.']", f.clean, ['hello', 'there']) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ['2006-01-10', 'there']) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.']", f.clean, ['hello', '07:30']) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ['2006-01-10', '']) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ['2006-01-10']) - self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.']", f.clean, ['', '07:30']) + self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello') + self.assertRaisesRegexp(ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'", f.clean, ['hello', 'there']) + self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', 'there']) + self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ['hello', '07:30']) + self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', '']) + self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10']) + self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ['', '07:30']) diff --git a/tests/regressiontests/forms/tests/forms.py b/tests/regressiontests/forms/tests/forms.py index 16cf46fc29b..7e1c8384a05 100644 --- a/tests/regressiontests/forms/tests/forms.py +++ b/tests/regressiontests/forms/tests/forms.py @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*- +from __future__ import unicode_literals + import datetime from django.core.files.uploadedfile import SimpleUploadedFile @@ -6,6 +8,7 @@ from django.forms import * from django.http import QueryDict from django.template import Template, Context from django.test import TestCase +from django.test.utils import str_prefix from django.utils.datastructures import MultiValueDict, MergeDict from django.utils.safestring import mark_safe @@ -29,15 +32,15 @@ class FormsTestCase(TestCase): def test_form(self): # Pass a dictionary to a Form's __init__(). - p = Person({'first_name': u'John', 'last_name': u'Lennon', 'birthday': u'1940-10-9'}) + p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'}) self.assertTrue(p.is_bound) self.assertEqual(p.errors, {}) self.assertTrue(p.is_valid()) - self.assertHTMLEqual(p.errors.as_ul(), u'') - self.assertEqual(p.errors.as_text(), u'') - self.assertEqual(p.cleaned_data["first_name"], u'John') - self.assertEqual(p.cleaned_data["last_name"], u'Lennon') + self.assertHTMLEqual(p.errors.as_ul(), '') + self.assertEqual(p.errors.as_text(), '') + self.assertEqual(p.cleaned_data["first_name"], 'John') + self.assertEqual(p.cleaned_data["last_name"], 'Lennon') self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9)) self.assertHTMLEqual(str(p['first_name']), '') self.assertHTMLEqual(str(p['last_name']), '') @@ -63,9 +66,9 @@ class FormsTestCase(TestCase): form_output.append([boundfield.label, boundfield.data]) self.assertEqual(form_output, [ - ['First name', u'John'], - ['Last name', u'Lennon'], - ['Birthday', u'1940-10-9'] + ['First name', 'John'], + ['Last name', 'Lennon'], + ['Birthday', '1940-10-9'] ]) self.assertHTMLEqual(str(p), """ @@ -75,9 +78,9 @@ class FormsTestCase(TestCase): # Empty dictionaries are valid, too. p = Person({}) self.assertTrue(p.is_bound) - self.assertEqual(p.errors['first_name'], [u'This field is required.']) - self.assertEqual(p.errors['last_name'], [u'This field is required.']) - self.assertEqual(p.errors['birthday'], [u'This field is required.']) + self.assertEqual(p.errors['first_name'], ['This field is required.']) + self.assertEqual(p.errors['last_name'], ['This field is required.']) + self.assertEqual(p.errors['birthday'], ['This field is required.']) self.assertFalse(p.is_valid()) try: p.cleaned_data @@ -128,16 +131,16 @@ class FormsTestCase(TestCase): def test_unicode_values(self): # Unicode values are handled properly. - p = Person({'first_name': u'John', 'last_name': u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111', 'birthday': '1940-10-9'}) - self.assertHTMLEqual(p.as_table(), u'\n\n') - self.assertHTMLEqual(p.as_ul(), u'
      • \n
      • \n
      • ') - self.assertHTMLEqual(p.as_p(), u'

        \n

        \n

        ') + p = Person({'first_name': 'John', 'last_name': '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111', 'birthday': '1940-10-9'}) + self.assertHTMLEqual(p.as_table(), '\n\n') + self.assertHTMLEqual(p.as_ul(), '
      • \n
      • \n
      • ') + self.assertHTMLEqual(p.as_p(), '

        \n

        \n

        ') - p = Person({'last_name': u'Lennon'}) - self.assertEqual(p.errors['first_name'], [u'This field is required.']) - self.assertEqual(p.errors['birthday'], [u'This field is required.']) + p = Person({'last_name': 'Lennon'}) + self.assertEqual(p.errors['first_name'], ['This field is required.']) + self.assertEqual(p.errors['birthday'], ['This field is required.']) self.assertFalse(p.is_valid()) - self.assertHTMLEqual(p.errors.as_ul(), u'
        • first_name
          • This field is required.
        • birthday
          • This field is required.
        ') + self.assertHTMLEqual(p.errors.as_ul(), '
        • first_name
          • This field is required.
        • birthday
          • This field is required.
        ') self.assertEqual(p.errors.as_text(), """* first_name * This field is required. * birthday @@ -147,9 +150,9 @@ class FormsTestCase(TestCase): self.fail('Attempts to access cleaned_data when validation fails should fail.') except AttributeError: pass - self.assertEqual(p['first_name'].errors, [u'This field is required.']) - self.assertHTMLEqual(p['first_name'].errors.as_ul(), u'
        • This field is required.
        ') - self.assertEqual(p['first_name'].errors.as_text(), u'* This field is required.') + self.assertEqual(p['first_name'].errors, ['This field is required.']) + self.assertHTMLEqual(p['first_name'].errors.as_ul(), '
        • This field is required.
        ') + self.assertEqual(p['first_name'].errors.as_text(), '* This field is required.') p = Person() self.assertHTMLEqual(str(p['first_name']), '') @@ -161,11 +164,11 @@ class FormsTestCase(TestCase): # Form, even if you pass extra data when you define the Form. In this # example, we pass a bunch of extra fields to the form constructor, # but cleaned_data contains only the form's fields. - data = {'first_name': u'John', 'last_name': u'Lennon', 'birthday': u'1940-10-9', 'extra1': 'hello', 'extra2': 'hello'} + data = {'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9', 'extra1': 'hello', 'extra2': 'hello'} p = Person(data) self.assertTrue(p.is_valid()) - self.assertEqual(p.cleaned_data['first_name'], u'John') - self.assertEqual(p.cleaned_data['last_name'], u'Lennon') + self.assertEqual(p.cleaned_data['first_name'], 'John') + self.assertEqual(p.cleaned_data['last_name'], 'Lennon') self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9)) def test_optional_data(self): @@ -179,12 +182,12 @@ class FormsTestCase(TestCase): last_name = CharField() nick_name = CharField(required=False) - data = {'first_name': u'John', 'last_name': u'Lennon'} + data = {'first_name': 'John', 'last_name': 'Lennon'} f = OptionalPersonForm(data) self.assertTrue(f.is_valid()) - self.assertEqual(f.cleaned_data['nick_name'], u'') - self.assertEqual(f.cleaned_data['first_name'], u'John') - self.assertEqual(f.cleaned_data['last_name'], u'Lennon') + self.assertEqual(f.cleaned_data['nick_name'], '') + self.assertEqual(f.cleaned_data['first_name'], 'John') + self.assertEqual(f.cleaned_data['last_name'], 'Lennon') # For DateFields, it's set to None. class OptionalPersonForm(Form): @@ -192,12 +195,12 @@ class FormsTestCase(TestCase): last_name = CharField() birth_date = DateField(required=False) - data = {'first_name': u'John', 'last_name': u'Lennon'} + data = {'first_name': 'John', 'last_name': 'Lennon'} f = OptionalPersonForm(data) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['birth_date'], None) - self.assertEqual(f.cleaned_data['first_name'], u'John') - self.assertEqual(f.cleaned_data['last_name'], u'Lennon') + self.assertEqual(f.cleaned_data['first_name'], 'John') + self.assertEqual(f.cleaned_data['last_name'], 'Lennon') def test_auto_id(self): # "auto_id" tells the Form to add an "id" attribute to each form element. @@ -286,9 +289,9 @@ class FormsTestCase(TestCase): # as_textarea(), as_text() and as_hidden() are shortcuts for changing the output # widget type: - self.assertHTMLEqual(f['subject'].as_textarea(), u'') - self.assertHTMLEqual(f['message'].as_text(), u'') - self.assertHTMLEqual(f['message'].as_hidden(), u'') + self.assertHTMLEqual(f['subject'].as_textarea(), '') + self.assertHTMLEqual(f['message'].as_text(), '') + self.assertHTMLEqual(f['message'].as_hidden(), '') # The 'widget' parameter to a Field can also be an instance: class ContactForm(Form): @@ -300,11 +303,11 @@ class FormsTestCase(TestCase): # Instance-level attrs are *not* carried over to as_textarea(), as_text() and # as_hidden(): - self.assertHTMLEqual(f['message'].as_text(), u'') + self.assertHTMLEqual(f['message'].as_text(), '') f = ContactForm({'subject': 'Hello', 'message': 'I love you.'}, auto_id=False) - self.assertHTMLEqual(f['subject'].as_textarea(), u'') - self.assertHTMLEqual(f['message'].as_text(), u'') - self.assertHTMLEqual(f['message'].as_hidden(), u'') + self.assertHTMLEqual(f['subject'].as_textarea(), '') + self.assertHTMLEqual(f['message'].as_text(), '') + self.assertHTMLEqual(f['message'].as_hidden(), '') def test_forms_with_choices(self): # For a form with a ') + self.assertHTMLEqual('\n'.join([str(bf) for bf in f['name']]), '') def test_forms_with_multiple_choice(self): # MultipleChoiceField is a special case, as its data is required to be a list: @@ -582,15 +585,15 @@ class FormsTestCase(TestCase): # When using CheckboxSelectMultiple, the framework expects a list of input and # returns a list of input. f = SongForm({'name': 'Yesterday'}, auto_id=False) - self.assertEqual(f.errors['composers'], [u'This field is required.']) + self.assertEqual(f.errors['composers'], ['This field is required.']) f = SongForm({'name': 'Yesterday', 'composers': ['J']}, auto_id=False) self.assertEqual(f.errors, {}) - self.assertEqual(f.cleaned_data['composers'], [u'J']) - self.assertEqual(f.cleaned_data['name'], u'Yesterday') + self.assertEqual(f.cleaned_data['composers'], ['J']) + self.assertEqual(f.cleaned_data['name'], 'Yesterday') f = SongForm({'name': 'Yesterday', 'composers': ['J', 'P']}, auto_id=False) self.assertEqual(f.errors, {}) - self.assertEqual(f.cleaned_data['composers'], [u'J', u'P']) - self.assertEqual(f.cleaned_data['name'], u'Yesterday') + self.assertEqual(f.cleaned_data['composers'], ['J', 'P']) + self.assertEqual(f.cleaned_data['name'], 'Yesterday') def test_escaping(self): # Validation errors are HTML-escaped when output as HTML. @@ -629,23 +632,23 @@ class FormsTestCase(TestCase): def clean_password2(self): if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']: - raise ValidationError(u'Please make sure your passwords match.') + raise ValidationError('Please make sure your passwords match.') return self.cleaned_data['password2'] f = UserRegistration(auto_id=False) self.assertEqual(f.errors, {}) f = UserRegistration({}, auto_id=False) - self.assertEqual(f.errors['username'], [u'This field is required.']) - self.assertEqual(f.errors['password1'], [u'This field is required.']) - self.assertEqual(f.errors['password2'], [u'This field is required.']) + self.assertEqual(f.errors['username'], ['This field is required.']) + self.assertEqual(f.errors['password1'], ['This field is required.']) + self.assertEqual(f.errors['password2'], ['This field is required.']) f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False) - self.assertEqual(f.errors['password2'], [u'Please make sure your passwords match.']) + self.assertEqual(f.errors['password2'], ['Please make sure your passwords match.']) f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False) self.assertEqual(f.errors, {}) - self.assertEqual(f.cleaned_data['username'], u'adrian') - self.assertEqual(f.cleaned_data['password1'], u'foo') - self.assertEqual(f.cleaned_data['password2'], u'foo') + self.assertEqual(f.cleaned_data['username'], 'adrian') + self.assertEqual(f.cleaned_data['password1'], 'foo') + self.assertEqual(f.cleaned_data['password2'], 'foo') # Another way of doing multiple-field validation is by implementing the # Form's clean() method. If you do this, any ValidationError raised by that @@ -661,7 +664,7 @@ class FormsTestCase(TestCase): def clean(self): if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']: - raise ValidationError(u'Please make sure your passwords match.') + raise ValidationError('Please make sure your passwords match.') return self.cleaned_data @@ -671,11 +674,11 @@ class FormsTestCase(TestCase): self.assertHTMLEqual(f.as_table(), """Username:
        • This field is required.
        Password1:
        • This field is required.
        Password2:
        • This field is required.
        """) - self.assertEqual(f.errors['username'], [u'This field is required.']) - self.assertEqual(f.errors['password1'], [u'This field is required.']) - self.assertEqual(f.errors['password2'], [u'This field is required.']) + self.assertEqual(f.errors['username'], ['This field is required.']) + self.assertEqual(f.errors['password1'], ['This field is required.']) + self.assertEqual(f.errors['password2'], ['This field is required.']) f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False) - self.assertEqual(f.errors['__all__'], [u'Please make sure your passwords match.']) + self.assertEqual(f.errors['__all__'], ['Please make sure your passwords match.']) self.assertHTMLEqual(f.as_table(), """
        • Please make sure your passwords match.
        Username: Password1: @@ -686,9 +689,9 @@ class FormsTestCase(TestCase):
      • Password2:
      • """) f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False) self.assertEqual(f.errors, {}) - self.assertEqual(f.cleaned_data['username'], u'adrian') - self.assertEqual(f.cleaned_data['password1'], u'foo') - self.assertEqual(f.cleaned_data['password2'], u'foo') + self.assertEqual(f.cleaned_data['username'], 'adrian') + self.assertEqual(f.cleaned_data['password1'], 'foo') + self.assertEqual(f.cleaned_data['password2'], 'foo') def test_dynamic_construction(self): # It's possible to construct a Form dynamically by adding to the self.fields @@ -985,10 +988,10 @@ class FormsTestCase(TestCase): # A label can be a Unicode object or a bytestring with special characters. class UserRegistration(Form): username = CharField(max_length=10, label='ŠĐĆŽćžšđ') - password = CharField(widget=PasswordInput, label=u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111') + password = CharField(widget=PasswordInput, label='\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111') p = UserRegistration(auto_id=False) - self.assertHTMLEqual(p.as_ul(), u'
      • \u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111:
      • \n
      • \u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111:
      • ') + self.assertHTMLEqual(p.as_ul(), '
      • \u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111:
      • \n
      • \u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111:
      • ') # If a label is set to the empty string for a field, that field won't get a label. class UserRegistration(Form): @@ -1034,8 +1037,8 @@ class FormsTestCase(TestCase): f = FavoriteForm(auto_id=False, label_suffix='') self.assertHTMLEqual(f.as_ul(), """
      • Favorite color?
      • Favorite animal
      • """) - f = FavoriteForm(auto_id=False, label_suffix=u'\u2192') - self.assertHTMLEqual(f.as_ul(), u'
      • Favorite color?
      • \n
      • Favorite animal\u2192
      • ') + f = FavoriteForm(auto_id=False, label_suffix='\u2192') + self.assertHTMLEqual(f.as_ul(), '
      • Favorite color?
      • \n
      • Favorite animal\u2192
      • ') def test_initial_data(self): # You can specify initial data for a field by using the 'initial' argument to a @@ -1056,10 +1059,10 @@ class FormsTestCase(TestCase): p = UserRegistration({}, auto_id=False) self.assertHTMLEqual(p.as_ul(), """
        • This field is required.
        Username:
        • This field is required.
        Password:
      • """) - p = UserRegistration({'username': u''}, auto_id=False) + p = UserRegistration({'username': ''}, auto_id=False) self.assertHTMLEqual(p.as_ul(), """
        • This field is required.
        Username:
        • This field is required.
        Password:
      • """) - p = UserRegistration({'username': u'foo'}, auto_id=False) + p = UserRegistration({'username': 'foo'}, auto_id=False) self.assertHTMLEqual(p.as_ul(), """
      • Username:
        • This field is required.
        Password:
      • """) @@ -1067,7 +1070,7 @@ class FormsTestCase(TestCase): # example, we don't provide a value for 'username', and the form raises a # validation error rather than using the initial value for 'username'. p = UserRegistration({'password': 'secret'}) - self.assertEqual(p.errors['username'], [u'This field is required.']) + self.assertEqual(p.errors['username'], ['This field is required.']) self.assertFalse(p.is_valid()) def test_dynamic_initial_data(self): @@ -1092,10 +1095,10 @@ class FormsTestCase(TestCase): p = UserRegistration({}, initial={'username': 'django'}, auto_id=False) self.assertHTMLEqual(p.as_ul(), """
        • This field is required.
        Username:
        • This field is required.
        Password:
      • """) - p = UserRegistration({'username': u''}, initial={'username': 'django'}, auto_id=False) + p = UserRegistration({'username': ''}, initial={'username': 'django'}, auto_id=False) self.assertHTMLEqual(p.as_ul(), """
        • This field is required.
        Username:
        • This field is required.
        Password:
      • """) - p = UserRegistration({'username': u'foo'}, initial={'username': 'django'}, auto_id=False) + p = UserRegistration({'username': 'foo'}, initial={'username': 'django'}, auto_id=False) self.assertHTMLEqual(p.as_ul(), """
      • Username:
        • This field is required.
        Password:
      • """) @@ -1103,7 +1106,7 @@ class FormsTestCase(TestCase): # In this example, we don't provide a value for 'username', and the form raises a # validation error rather than using the initial value for 'username'. p = UserRegistration({'password': 'secret'}, initial={'username': 'django'}) - self.assertEqual(p.errors['username'], [u'This field is required.']) + self.assertEqual(p.errors['username'], ['This field is required.']) self.assertFalse(p.is_valid()) # If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(), @@ -1156,7 +1159,7 @@ class FormsTestCase(TestCase): """) - p = UserRegistration({'username': u''}, initial={'username': initial_django}, auto_id=False) + p = UserRegistration({'username': ''}, initial={'username': initial_django}, auto_id=False) self.assertHTMLEqual(p.as_ul(), """
        • This field is required.
        Username:
        • This field is required.
        Password:
        • This field is required.
        Options:
      • """) - p = UserRegistration({'username': u'foo', 'options':['f','b']}, initial={'username': initial_django}, auto_id=False) + p = UserRegistration({'username': 'foo', 'options':['f','b']}, initial={'username': initial_django}, auto_id=False) self.assertHTMLEqual(p.as_ul(), """
      • Username:
        • This field is required.
        Password:
      • Options:
        Choose wisely.""") # The help text is displayed whether or not data is provided for the form. - p = UserRegistration({'username': u'foo'}, auto_id=False) + p = UserRegistration({'username': 'foo'}, auto_id=False) self.assertHTMLEqual(p.as_ul(), """
      • Username: e.g., user@example.com
        • This field is required.
        Password: Choose wisely.
      • """) @@ -1254,7 +1257,7 @@ class FormsTestCase(TestCase): username = CharField(max_length=10, help_text='ŠĐĆŽćžšđ') p = UserRegistration(auto_id=False) - self.assertHTMLEqual(p.as_ul(), u'
      • Username: \u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111
      • ') + self.assertHTMLEqual(p.as_ul(), '
      • Username: \u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111
      • ') def test_subclassing_forms(self): # You can subclass a Form to add fields. The resulting form subclass will have @@ -1312,9 +1315,9 @@ class FormsTestCase(TestCase): birthday = DateField() data = { - 'person1-first_name': u'John', - 'person1-last_name': u'Lennon', - 'person1-birthday': u'1940-10-9' + 'person1-first_name': 'John', + 'person1-last_name': 'Lennon', + 'person1-birthday': '1940-10-9' } p = Person(data, prefix='person1') self.assertHTMLEqual(p.as_ul(), """
      • @@ -1325,22 +1328,22 @@ class FormsTestCase(TestCase): self.assertHTMLEqual(str(p['birthday']), '') self.assertEqual(p.errors, {}) self.assertTrue(p.is_valid()) - self.assertEqual(p.cleaned_data['first_name'], u'John') - self.assertEqual(p.cleaned_data['last_name'], u'Lennon') + self.assertEqual(p.cleaned_data['first_name'], 'John') + self.assertEqual(p.cleaned_data['last_name'], 'Lennon') self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9)) # Let's try submitting some bad data to make sure form.errors and field.errors # work as expected. data = { - 'person1-first_name': u'', - 'person1-last_name': u'', - 'person1-birthday': u'' + 'person1-first_name': '', + 'person1-last_name': '', + 'person1-birthday': '' } p = Person(data, prefix='person1') - self.assertEqual(p.errors['first_name'], [u'This field is required.']) - self.assertEqual(p.errors['last_name'], [u'This field is required.']) - self.assertEqual(p.errors['birthday'], [u'This field is required.']) - self.assertEqual(p['first_name'].errors, [u'This field is required.']) + self.assertEqual(p.errors['first_name'], ['This field is required.']) + self.assertEqual(p.errors['last_name'], ['This field is required.']) + self.assertEqual(p.errors['birthday'], ['This field is required.']) + self.assertEqual(p['first_name'].errors, ['This field is required.']) try: p['person1-first_name'].errors self.fail('Attempts to access non-existent fields should fail.') @@ -1350,34 +1353,34 @@ class FormsTestCase(TestCase): # In this example, the data doesn't have a prefix, but the form requires it, so # the form doesn't "see" the fields. data = { - 'first_name': u'John', - 'last_name': u'Lennon', - 'birthday': u'1940-10-9' + 'first_name': 'John', + 'last_name': 'Lennon', + 'birthday': '1940-10-9' } p = Person(data, prefix='person1') - self.assertEqual(p.errors['first_name'], [u'This field is required.']) - self.assertEqual(p.errors['last_name'], [u'This field is required.']) - self.assertEqual(p.errors['birthday'], [u'This field is required.']) + self.assertEqual(p.errors['first_name'], ['This field is required.']) + self.assertEqual(p.errors['last_name'], ['This field is required.']) + self.assertEqual(p.errors['birthday'], ['This field is required.']) # With prefixes, a single data dictionary can hold data for multiple instances # of the same form. data = { - 'person1-first_name': u'John', - 'person1-last_name': u'Lennon', - 'person1-birthday': u'1940-10-9', - 'person2-first_name': u'Jim', - 'person2-last_name': u'Morrison', - 'person2-birthday': u'1943-12-8' + 'person1-first_name': 'John', + 'person1-last_name': 'Lennon', + 'person1-birthday': '1940-10-9', + 'person2-first_name': 'Jim', + 'person2-last_name': 'Morrison', + 'person2-birthday': '1943-12-8' } p1 = Person(data, prefix='person1') self.assertTrue(p1.is_valid()) - self.assertEqual(p1.cleaned_data['first_name'], u'John') - self.assertEqual(p1.cleaned_data['last_name'], u'Lennon') + self.assertEqual(p1.cleaned_data['first_name'], 'John') + self.assertEqual(p1.cleaned_data['last_name'], 'Lennon') self.assertEqual(p1.cleaned_data['birthday'], datetime.date(1940, 10, 9)) p2 = Person(data, prefix='person2') self.assertTrue(p2.is_valid()) - self.assertEqual(p2.cleaned_data['first_name'], u'Jim') - self.assertEqual(p2.cleaned_data['last_name'], u'Morrison') + self.assertEqual(p2.cleaned_data['first_name'], 'Jim') + self.assertEqual(p2.cleaned_data['last_name'], 'Morrison') self.assertEqual(p2.cleaned_data['birthday'], datetime.date(1943, 12, 8)) # By default, forms append a hyphen between the prefix and the field name, but a @@ -1397,14 +1400,14 @@ class FormsTestCase(TestCase):
      • """) data = { - 'foo-prefix-first_name': u'John', - 'foo-prefix-last_name': u'Lennon', - 'foo-prefix-birthday': u'1940-10-9' + 'foo-prefix-first_name': 'John', + 'foo-prefix-last_name': 'Lennon', + 'foo-prefix-birthday': '1940-10-9' } p = Person(data, prefix='foo') self.assertTrue(p.is_valid()) - self.assertEqual(p.cleaned_data['first_name'], u'John') - self.assertEqual(p.cleaned_data['last_name'], u'Lennon') + self.assertEqual(p.cleaned_data['first_name'], 'John') + self.assertEqual(p.cleaned_data['last_name'], 'Lennon') self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9)) def test_forms_with_null_boolean(self): @@ -1414,37 +1417,37 @@ class FormsTestCase(TestCase): name = CharField() is_cool = NullBooleanField() - p = Person({'name': u'Joe'}, auto_id=False) + p = Person({'name': 'Joe'}, auto_id=False) self.assertHTMLEqual(str(p['is_cool']), """""") - p = Person({'name': u'Joe', 'is_cool': u'1'}, auto_id=False) + p = Person({'name': 'Joe', 'is_cool': '1'}, auto_id=False) self.assertHTMLEqual(str(p['is_cool']), """""") - p = Person({'name': u'Joe', 'is_cool': u'2'}, auto_id=False) + p = Person({'name': 'Joe', 'is_cool': '2'}, auto_id=False) self.assertHTMLEqual(str(p['is_cool']), """""") - p = Person({'name': u'Joe', 'is_cool': u'3'}, auto_id=False) + p = Person({'name': 'Joe', 'is_cool': '3'}, auto_id=False) self.assertHTMLEqual(str(p['is_cool']), """""") - p = Person({'name': u'Joe', 'is_cool': True}, auto_id=False) + p = Person({'name': 'Joe', 'is_cool': True}, auto_id=False) self.assertHTMLEqual(str(p['is_cool']), """""") - p = Person({'name': u'Joe', 'is_cool': False}, auto_id=False) + p = Person({'name': 'Joe', 'is_cool': False}, auto_id=False) self.assertHTMLEqual(str(p['is_cool']), """') self.assertTrue(f.is_valid()) - f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', u'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))}, auto_id=False) + f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))}, auto_id=False) self.assertHTMLEqual(f.as_table(), 'File1:') def test_basic_processing_in_view(self): @@ -1484,7 +1487,7 @@ class FormsTestCase(TestCase): def clean(self): if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']: - raise ValidationError(u'Please make sure your passwords match.') + raise ValidationError('Please make sure your passwords match.') return self.cleaned_data @@ -1520,7 +1523,7 @@ class FormsTestCase(TestCase): """) # Case 3: POST with valid data (the success message).) - self.assertHTMLEqual(my_function('POST', {'username': 'adrian', 'password1': 'secret', 'password2': 'secret'}), "VALID: {'username': u'adrian', 'password1': u'secret', 'password2': u'secret'}") + self.assertHTMLEqual(my_function('POST', {'username': 'adrian', 'password1': 'secret', 'password2': 'secret'}), str_prefix("VALID: {'username': %(_)s'adrian', 'password1': %(_)s'secret', 'password2': %(_)s'secret'}")) def test_templates_with_forms(self): class UserRegistration(Form): @@ -1530,7 +1533,7 @@ class FormsTestCase(TestCase): def clean(self): if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']: - raise ValidationError(u'Please make sure your passwords match.') + raise ValidationError('Please make sure your passwords match.') return self.cleaned_data @@ -1612,7 +1615,7 @@ class FormsTestCase(TestCase):

        Password2:

        """) - self.assertEqual(Template('{{ form.password1.help_text }}').render(Context({'form': UserRegistration(auto_id=False)})), u'') + self.assertEqual(Template('{{ form.password1.help_text }}').render(Context({'form': UserRegistration(auto_id=False)})), '') # The label_tag() method takes an optional attrs argument: a dictionary of HTML # attributes to add to the