summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorClaude Paroz <claude@2xlibre.net>2012-06-07 18:08:47 +0200
committerClaude Paroz <claude@2xlibre.net>2012-06-07 18:08:47 +0200
commit4a103086d5c67fa4fcc53c106c9fdf644c742dd8 (patch)
tree3df00600c27f6369f7561c3b8ddf2f97d2d341d9
parent706fd9adc0b6587c7f96a834c757708e64fcf615 (diff)
Fixed #18269 -- Applied unicode_literals for Python 3 compatibility.
Thanks Vinay Sajip for the support of his django3 branch and Jannis Leidel for the review.
-rw-r--r--django/conf/locale/__init__.py146
-rw-r--r--django/conf/locale/bg/formats.py3
-rw-r--r--django/conf/locale/cs/formats.py3
-rw-r--r--django/conf/locale/en/formats.py4
-rw-r--r--django/conf/locale/es_MX/formats.py3
-rw-r--r--django/conf/locale/et/formats.py3
-rw-r--r--django/conf/locale/fi/formats.py3
-rw-r--r--django/conf/locale/fr/formats.py3
-rw-r--r--django/conf/locale/he/formats.py1
-rw-r--r--django/conf/locale/hu/formats.py3
-rw-r--r--django/conf/locale/ja/formats.py1
-rw-r--r--django/conf/locale/km/formats.py1
-rw-r--r--django/conf/locale/ko/formats.py1
-rw-r--r--django/conf/locale/lv/formats.py3
-rw-r--r--django/conf/locale/nb/formats.py3
-rw-r--r--django/conf/locale/nn/formats.py3
-rw-r--r--django/conf/locale/pl/formats.py3
-rw-r--r--django/conf/locale/pt_BR/formats.py1
-rw-r--r--django/conf/locale/ru/formats.py3
-rw-r--r--django/conf/locale/sk/formats.py3
-rw-r--r--django/conf/locale/sv/formats.py3
-rw-r--r--django/conf/locale/uk/formats.py4
-rw-r--r--django/conf/locale/vi/formats.py1
-rw-r--r--django/contrib/admin/forms.py5
-rw-r--r--django/contrib/admin/helpers.py18
-rw-r--r--django/contrib/admin/models.py4
-rw-r--r--django/contrib/admin/templatetags/admin_list.py18
-rw-r--r--django/contrib/admin/util.py6
-rw-r--r--django/contrib/admin/widgets.py36
-rw-r--r--django/contrib/admindocs/tests/__init__.py8
-rw-r--r--django/contrib/auth/backends.py4
-rw-r--r--django/contrib/auth/hashers.py2
-rw-r--r--django/contrib/auth/management/__init__.py8
-rw-r--r--django/contrib/auth/models.py6
-rw-r--r--django/contrib/auth/tests/auth_backends.py10
-rw-r--r--django/contrib/auth/tests/forms.py6
-rw-r--r--django/contrib/auth/tests/hashers.py18
-rw-r--r--django/contrib/auth/tests/management.py8
-rw-r--r--django/contrib/comments/admin.py6
-rw-r--r--django/contrib/contenttypes/generic.py3
-rw-r--r--django/contrib/contenttypes/tests.py4
-rw-r--r--django/contrib/contenttypes/views.py6
-rw-r--r--django/contrib/databrowse/datastructures.py11
-rw-r--r--django/contrib/databrowse/plugins/calendars.py10
-rw-r--r--django/contrib/databrowse/plugins/fieldchoices.py10
-rw-r--r--django/contrib/databrowse/sites.py4
-rw-r--r--django/contrib/flatpages/models.py4
-rw-r--r--django/contrib/flatpages/tests/forms.py6
-rw-r--r--django/contrib/formtools/tests/__init__.py58
-rw-r--r--django/contrib/formtools/tests/wizard/forms.py10
-rw-r--r--django/contrib/formtools/tests/wizard/namedwizardtests/tests.py24
-rw-r--r--django/contrib/formtools/tests/wizard/wizardtests/tests.py26
-rw-r--r--django/contrib/gis/feeds.py22
-rw-r--r--django/contrib/gis/forms/fields.py10
-rw-r--r--django/contrib/gis/gdal/tests/test_envelope.py2
-rw-r--r--django/contrib/gis/geoip/tests.py8
-rw-r--r--django/contrib/gis/sitemaps/views.py8
-rw-r--r--django/contrib/gis/tests/geoapp/test_feeds.py6
-rw-r--r--django/contrib/gis/tests/geoapp/test_sitemaps.py10
-rw-r--r--django/contrib/gis/views.py6
-rw-r--r--django/contrib/humanize/templatetags/humanize.py27
-rw-r--r--django/contrib/humanize/tests.py11
-rw-r--r--django/contrib/localflavor/ar/ar_provinces.py49
-rw-r--r--django/contrib/localflavor/ar/forms.py12
-rw-r--r--django/contrib/localflavor/at/forms.py8
-rw-r--r--django/contrib/localflavor/au/forms.py8
-rw-r--r--django/contrib/localflavor/br/br_states.py23
-rw-r--r--django/contrib/localflavor/br/forms.py16
-rw-r--r--django/contrib/localflavor/ca/forms.py22
-rw-r--r--django/contrib/localflavor/ch/forms.py10
-rw-r--r--django/contrib/localflavor/cl/cl_regions.py31
-rw-r--r--django/contrib/localflavor/cl/forms.py10
-rw-r--r--django/contrib/localflavor/cn/cn_provinces.py70
-rw-r--r--django/contrib/localflavor/cn/forms.py20
-rw-r--r--django/contrib/localflavor/co/co_departments.py67
-rw-r--r--django/contrib/localflavor/cz/forms.py20
-rw-r--r--django/contrib/localflavor/de/forms.py8
-rw-r--r--django/contrib/localflavor/de_CH/formats.py4
-rw-r--r--django/contrib/localflavor/ec/ec_provinces.py49
-rw-r--r--django/contrib/localflavor/es/forms.py4
-rw-r--r--django/contrib/localflavor/fi/fi_municipalities.py688
-rw-r--r--django/contrib/localflavor/fi/forms.py6
-rw-r--r--django/contrib/localflavor/fr/forms.py6
-rw-r--r--django/contrib/localflavor/fr/fr_department.py219
-rw-r--r--django/contrib/localflavor/gb/forms.py6
-rw-r--r--django/contrib/localflavor/hk/forms.py6
-rw-r--r--django/contrib/localflavor/hr/forms.py22
-rw-r--r--django/contrib/localflavor/hr/hr_choices.py54
-rw-r--r--django/contrib/localflavor/id/forms.py12
-rw-r--r--django/contrib/localflavor/il/forms.py7
-rw-r--r--django/contrib/localflavor/in_/forms.py14
-rw-r--r--django/contrib/localflavor/is_/forms.py8
-rw-r--r--django/contrib/localflavor/is_/is_postalcodes.py295
-rw-r--r--django/contrib/localflavor/it/forms.py12
-rw-r--r--django/contrib/localflavor/it/it_province.py3
-rw-r--r--django/contrib/localflavor/it/it_region.py3
-rw-r--r--django/contrib/localflavor/it/util.py4
-rw-r--r--django/contrib/localflavor/kw/forms.py4
-rw-r--r--django/contrib/localflavor/mk/forms.py14
-rw-r--r--django/contrib/localflavor/mk/mk_choices.py170
-rw-r--r--django/contrib/localflavor/mx/forms.py61
-rw-r--r--django/contrib/localflavor/mx/mx_states.py65
-rw-r--r--django/contrib/localflavor/nl/forms.py10
-rw-r--r--django/contrib/localflavor/no/forms.py6
-rw-r--r--django/contrib/localflavor/no/no_municipalities.py43
-rw-r--r--django/contrib/localflavor/pe/forms.py6
-rw-r--r--django/contrib/localflavor/pe/pe_region.py51
-rw-r--r--django/contrib/localflavor/pl/forms.py36
-rw-r--r--django/contrib/localflavor/pl/pl_administrativeunits.py753
-rw-r--r--django/contrib/localflavor/pt/forms.py8
-rw-r--r--django/contrib/localflavor/py/py_department.py73
-rw-r--r--django/contrib/localflavor/ro/forms.py14
-rw-r--r--django/contrib/localflavor/ro/ro_counties.py85
-rw-r--r--django/contrib/localflavor/ru/forms.py8
-rw-r--r--django/contrib/localflavor/se/forms.py6
-rw-r--r--django/contrib/localflavor/se/se_counties.py43
-rw-r--r--django/contrib/localflavor/si/forms.py18
-rw-r--r--django/contrib/localflavor/si/si_postalcodes.py927
-rw-r--r--django/contrib/localflavor/sk/forms.py4
-rw-r--r--django/contrib/localflavor/tr/forms.py18
-rw-r--r--django/contrib/localflavor/us/forms.py12
-rw-r--r--django/contrib/localflavor/uy/forms.py4
-rw-r--r--django/contrib/localflavor/uy/uy_departaments.py39
-rw-r--r--django/contrib/localflavor/za/forms.py7
-rw-r--r--django/contrib/messages/storage/base.py4
-rw-r--r--django/contrib/sitemaps/tests/flatpages.py10
-rw-r--r--django/contrib/sitemaps/tests/http.py4
-rw-r--r--django/contrib/sites/tests.py8
-rw-r--r--django/contrib/staticfiles/management/commands/collectstatic.py30
-rw-r--r--django/contrib/staticfiles/management/commands/findstatic.py8
-rw-r--r--django/contrib/staticfiles/storage.py11
-rw-r--r--django/contrib/syndication/views.py4
-rw-r--r--django/contrib/webdesign/lorem_ipsum.py12
-rw-r--r--django/contrib/webdesign/templatetags/webdesign.py4
-rw-r--r--django/contrib/webdesign/tests.py5
-rw-r--r--django/core/context_processors.py3
-rw-r--r--django/core/files/base.py4
-rw-r--r--django/core/files/uploadhandler.py6
-rw-r--r--django/core/handlers/base.py8
-rw-r--r--django/core/handlers/wsgi.py12
-rw-r--r--django/core/mail/__init__.py5
-rw-r--r--django/core/mail/message.py8
-rw-r--r--django/core/management/commands/createcachetable.py4
-rw-r--r--django/core/management/commands/loaddata.py5
-rw-r--r--django/core/management/commands/sql.py4
-rw-r--r--django/core/management/commands/sqlall.py4
-rw-r--r--django/core/management/commands/sqlclear.py4
-rw-r--r--django/core/management/commands/sqlcustom.py4
-rw-r--r--django/core/management/commands/sqlflush.py4
-rw-r--r--django/core/management/commands/sqlindexes.py4
-rw-r--r--django/core/management/commands/sqlsequencereset.py4
-rw-r--r--django/core/management/sql.py6
-rw-r--r--django/core/management/validation.py3
-rw-r--r--django/core/serializers/json.py5
-rw-r--r--django/core/serializers/python.py3
-rw-r--r--django/core/serializers/xml_serializer.py4
-rw-r--r--django/core/urlresolvers.py9
-rw-r--r--django/core/validators.py32
-rw-r--r--django/db/backends/mysql/base.py5
-rw-r--r--django/db/backends/oracle/base.py10
-rw-r--r--django/db/backends/postgresql_psycopg2/introspection.py4
-rw-r--r--django/db/backends/postgresql_psycopg2/operations.py14
-rw-r--r--django/db/backends/sqlite3/base.py7
-rw-r--r--django/db/backends/util.py6
-rw-r--r--django/db/models/base.py8
-rw-r--r--django/db/models/fields/__init__.py60
-rw-r--r--django/db/models/fields/files.py2
-rw-r--r--django/forms/extras/widgets.py3
-rw-r--r--django/forms/fields.py72
-rw-r--r--django/forms/forms.py36
-rw-r--r--django/forms/formsets.py22
-rw-r--r--django/forms/models.py20
-rw-r--r--django/forms/util.py22
-rw-r--r--django/forms/widgets.py90
-rw-r--r--django/http/__init__.py8
-rw-r--r--django/http/multipartparser.py14
-rw-r--r--django/template/base.py8
-rw-r--r--django/template/defaultfilters.py81
-rw-r--r--django/template/defaulttags.py15
-rw-r--r--django/templatetags/cache.py6
-rw-r--r--django/templatetags/i18n.py9
-rw-r--r--django/test/client.py2
-rw-r--r--django/test/html.py19
-rw-r--r--django/test/testcases.py52
-rw-r--r--django/test/utils.py2
-rw-r--r--django/utils/crypto.py6
-rw-r--r--django/utils/dateformat.py37
-rw-r--r--django/utils/encoding.py6
-rw-r--r--django/utils/feedgenerator.py161
-rw-r--r--django/utils/html.py42
-rw-r--r--django/utils/regex_helper.py33
-rw-r--r--django/utils/text.py46
-rw-r--r--django/utils/timesince.py4
-rw-r--r--django/utils/translation/__init__.py4
-rw-r--r--django/utils/translation/trans_real.py43
-rw-r--r--django/utils/tzinfo.py4
-rw-r--r--django/utils/version.py2
-rw-r--r--django/views/debug.py6
-rw-r--r--django/views/generic/base.py8
-rw-r--r--django/views/generic/dates.py20
-rw-r--r--django/views/generic/detail.py14
-rw-r--r--django/views/generic/list.py10
-rw-r--r--django/views/static.py7
-rw-r--r--docs/conf.py14
-rw-r--r--docs/ref/files/file.txt3
-rw-r--r--docs/ref/forms/fields.txt2
-rw-r--r--docs/ref/forms/validation.txt4
-rw-r--r--docs/ref/unicode.txt44
-rw-r--r--docs/topics/db/models.txt16
-rw-r--r--docs/topics/i18n/translation.txt4
-rw-r--r--tests/modeltests/aggregation/tests.py100
-rw-r--r--tests/modeltests/basic/tests.py14
-rw-r--r--tests/modeltests/custom_columns/models.py4
-rw-r--r--tests/modeltests/custom_managers/models.py4
-rw-r--r--tests/modeltests/custom_pk/models.py4
-rw-r--r--tests/modeltests/custom_pk/tests.py4
-rw-r--r--tests/modeltests/distinct_on_fields/models.py4
-rw-r--r--tests/modeltests/distinct_on_fields/tests.py4
-rw-r--r--tests/modeltests/expressions/models.py3
-rw-r--r--tests/modeltests/expressions/tests.py20
-rw-r--r--tests/modeltests/field_subclassing/fields.py4
-rw-r--r--tests/modeltests/files/tests.py26
-rw-r--r--tests/modeltests/fixtures_model_package/tests.py26
-rw-r--r--tests/modeltests/generic_relations/models.py4
-rw-r--r--tests/modeltests/generic_relations/tests.py52
-rw-r--r--tests/modeltests/get_or_create/models.py4
-rw-r--r--tests/modeltests/invalid_models/invalid_models/models.py8
-rw-r--r--tests/modeltests/lookup/models.py6
-rw-r--r--tests/modeltests/lookup/tests.py44
-rw-r--r--tests/modeltests/m2m_and_m2o/models.py3
-rw-r--r--tests/modeltests/m2m_intermediary/models.py5
-rw-r--r--tests/modeltests/m2m_through/tests.py2
-rw-r--r--tests/modeltests/many_to_one/models.py3
-rw-r--r--tests/modeltests/many_to_one/tests.py6
-rw-r--r--tests/modeltests/model_forms/models.py3
-rw-r--r--tests/modeltests/model_forms/tests.py226
-rw-r--r--tests/modeltests/model_formsets/models.py10
-rw-r--r--tests/modeltests/model_formsets/tests.py82
-rw-r--r--tests/modeltests/model_inheritance/models.py15
-rw-r--r--tests/modeltests/one_to_one/models.py9
-rw-r--r--tests/modeltests/pagination/tests.py8
-rw-r--r--tests/modeltests/prefetch_related/tests.py38
-rw-r--r--tests/modeltests/proxy_models/tests.py6
-rw-r--r--tests/modeltests/save_delete_hooks/models.py3
-rw-r--r--tests/modeltests/select_related/tests.py6
-rw-r--r--tests/modeltests/serializers/models.py5
-rw-r--r--tests/modeltests/serializers/tests.py6
-rw-r--r--tests/modeltests/signals/models.py5
-rw-r--r--tests/modeltests/str/tests.py4
-rw-r--r--tests/modeltests/test_client/models.py6
-rw-r--r--tests/modeltests/timezones/tests.py32
-rw-r--r--tests/modeltests/transactions/models.py3
-rw-r--r--tests/modeltests/update/tests.py10
-rw-r--r--tests/modeltests/validation/models.py8
-rw-r--r--tests/modeltests/validation/test_error_messages.py70
-rw-r--r--tests/modeltests/validation/test_unique.py14
-rw-r--r--tests/modeltests/validation/tests.py4
-rw-r--r--tests/modeltests/validation/validators.py4
-rw-r--r--tests/modeltests/validators/tests.py15
-rw-r--r--tests/regressiontests/admin_custom_urls/tests.py8
-rw-r--r--tests/regressiontests/admin_filters/models.py6
-rw-r--r--tests/regressiontests/admin_filters/tests.py92
-rw-r--r--tests/regressiontests/admin_inlines/models.py6
-rw-r--r--tests/regressiontests/admin_inlines/tests.py10
-rw-r--r--tests/regressiontests/admin_ordering/tests.py14
-rw-r--r--tests/regressiontests/admin_util/tests.py4
-rw-r--r--tests/regressiontests/admin_views/admin.py6
-rw-r--r--tests/regressiontests/admin_views/models.py40
-rw-r--r--tests/regressiontests/admin_views/tests.py267
-rw-r--r--tests/regressiontests/admin_widgets/models.py4
-rw-r--r--tests/regressiontests/admin_widgets/tests.py12
-rw-r--r--tests/regressiontests/aggregation_regress/tests.py84
-rw-r--r--tests/regressiontests/backends/models.py6
-rw-r--r--tests/regressiontests/backends/tests.py8
-rw-r--r--tests/regressiontests/cache/tests.py22
-rw-r--r--tests/regressiontests/comment_tests/tests/comment_view_tests.py6
-rw-r--r--tests/regressiontests/csrf_tests/tests.py9
-rw-r--r--tests/regressiontests/custom_columns_regress/models.py3
-rw-r--r--tests/regressiontests/datatypes/tests.py6
-rw-r--r--tests/regressiontests/defaultfilters/tests.py649
-rw-r--r--tests/regressiontests/expressions_regress/models.py3
-rw-r--r--tests/regressiontests/extra_regress/models.py6
-rw-r--r--tests/regressiontests/extra_regress/tests.py36
-rw-r--r--tests/regressiontests/file_storage/tests.py8
-rw-r--r--tests/regressiontests/file_uploads/tests.py23
-rw-r--r--tests/regressiontests/file_uploads/views.py4
-rw-r--r--tests/regressiontests/fixtures_regress/models.py10
-rw-r--r--tests/regressiontests/fixtures_regress/tests.py4
-rw-r--r--tests/regressiontests/forms/models.py6
-rw-r--r--tests/regressiontests/forms/tests/error_messages.py117
-rw-r--r--tests/regressiontests/forms/tests/extra.py175
-rw-r--r--tests/regressiontests/forms/tests/fields.py568
-rw-r--r--tests/regressiontests/forms/tests/forms.py255
-rw-r--r--tests/regressiontests/forms/tests/formsets.py88
-rw-r--r--tests/regressiontests/forms/tests/models.py18
-rw-r--r--tests/regressiontests/forms/tests/regressions.py34
-rw-r--r--tests/regressiontests/forms/tests/util.py16
-rw-r--r--tests/regressiontests/forms/tests/widgets.py325
-rw-r--r--tests/regressiontests/generic_inline_admin/tests.py41
-rw-r--r--tests/regressiontests/httpwrappers/tests.py58
-rw-r--r--tests/regressiontests/i18n/contenttypes/tests.py5
-rw-r--r--tests/regressiontests/i18n/patterns/tests.py10
-rw-r--r--tests/regressiontests/i18n/tests.py296
-rw-r--r--tests/regressiontests/inline_formsets/tests.py46
-rw-r--r--tests/regressiontests/introspection/models.py4
-rw-r--r--tests/regressiontests/introspection/tests.py6
-rw-r--r--tests/regressiontests/localflavor/ar/tests.py28
-rw-r--r--tests/regressiontests/localflavor/at/tests.py8
-rw-r--r--tests/regressiontests/localflavor/au/tests.py14
-rw-r--r--tests/regressiontests/localflavor/be/tests.py34
-rw-r--r--tests/regressiontests/localflavor/br/tests.py38
-rw-r--r--tests/regressiontests/localflavor/ca/tests.py12
-rw-r--r--tests/regressiontests/localflavor/ch/tests.py10
-rw-r--r--tests/regressiontests/localflavor/cl/tests.py8
-rw-r--r--tests/regressiontests/localflavor/cn/tests.py37
-rw-r--r--tests/regressiontests/localflavor/co/tests.py4
-rw-r--r--tests/regressiontests/localflavor/cz/tests.py12
-rw-r--r--tests/regressiontests/localflavor/de/tests.py8
-rw-r--r--tests/regressiontests/localflavor/ec/tests.py4
-rw-r--r--tests/regressiontests/localflavor/es/tests.py22
-rw-r--r--tests/regressiontests/localflavor/fi/tests.py8
-rw-r--r--tests/regressiontests/localflavor/fr/tests.py8
-rw-r--r--tests/regressiontests/localflavor/gb/tests.py6
-rw-r--r--tests/regressiontests/localflavor/generic/tests.py6
-rw-r--r--tests/regressiontests/localflavor/hr/tests.py38
-rw-r--r--tests/regressiontests/localflavor/id/tests.py50
-rw-r--r--tests/regressiontests/localflavor/ie/tests.py4
-rw-r--r--tests/regressiontests/localflavor/il/tests.py6
-rw-r--r--tests/regressiontests/localflavor/in_/tests.py10
-rw-r--r--tests/regressiontests/localflavor/is_/tests.py18
-rw-r--r--tests/regressiontests/localflavor/it/tests.py10
-rw-r--r--tests/regressiontests/localflavor/jp/tests.py6
-rw-r--r--tests/regressiontests/localflavor/kw/tests.py4
-rw-r--r--tests/regressiontests/localflavor/mk/tests.py24
-rw-r--r--tests/regressiontests/localflavor/mx/tests.py66
-rw-r--r--tests/regressiontests/localflavor/nl/tests.py10
-rw-r--r--tests/regressiontests/localflavor/pl/tests.py26
-rw-r--r--tests/regressiontests/localflavor/pt/tests.py6
-rw-r--r--tests/regressiontests/localflavor/py/tests.py6
-rw-r--r--tests/regressiontests/localflavor/ro/tests.py42
-rw-r--r--tests/regressiontests/localflavor/ru/tests.py12
-rw-r--r--tests/regressiontests/localflavor/se/tests.py12
-rw-r--r--tests/regressiontests/localflavor/si/tests.py17
-rw-r--r--tests/regressiontests/localflavor/sk/tests.py8
-rw-r--r--tests/regressiontests/localflavor/us/tests.py14
-rw-r--r--tests/regressiontests/localflavor/uy/tests.py14
-rw-r--r--tests/regressiontests/localflavor/za/tests.py6
-rw-r--r--tests/regressiontests/logging_tests/tests.py6
-rw-r--r--tests/regressiontests/m2m_through_regress/models.py4
-rw-r--r--tests/regressiontests/mail/tests.py16
-rw-r--r--tests/regressiontests/many_to_one_regress/models.py3
-rw-r--r--tests/regressiontests/model_fields/tests.py10
-rw-r--r--tests/regressiontests/model_forms_regress/models.py4
-rw-r--r--tests/regressiontests/model_forms_regress/tests.py20
-rw-r--r--tests/regressiontests/model_formsets_regress/tests.py114
-rw-r--r--tests/regressiontests/model_inheritance_regress/models.py12
-rw-r--r--tests/regressiontests/model_inheritance_regress/tests.py19
-rw-r--r--tests/regressiontests/model_inheritance_select_related/models.py5
-rw-r--r--tests/regressiontests/model_regress/tests.py4
-rw-r--r--tests/regressiontests/modeladmin/tests.py16
-rw-r--r--tests/regressiontests/multiple_database/tests.py108
-rw-r--r--tests/regressiontests/null_fk/tests.py10
-rw-r--r--tests/regressiontests/null_fk_ordering/models.py3
-rw-r--r--tests/regressiontests/null_queries/models.py6
-rw-r--r--tests/regressiontests/one_to_one_regress/models.py10
-rw-r--r--tests/regressiontests/pagination_regress/tests.py6
-rw-r--r--tests/regressiontests/queries/models.py5
-rw-r--r--tests/regressiontests/queries/tests.py21
-rw-r--r--tests/regressiontests/requests/tests.py93
-rw-r--r--tests/regressiontests/select_related_regress/models.py10
-rw-r--r--tests/regressiontests/select_related_regress/tests.py26
-rw-r--r--tests/regressiontests/serializers_regress/tests.py4
-rw-r--r--tests/regressiontests/signed_cookies_tests/tests.py8
-rw-r--r--tests/regressiontests/signing/tests.py10
-rw-r--r--tests/regressiontests/staticfiles_tests/tests.py11
-rw-r--r--tests/regressiontests/string_lookup/tests.py6
-rw-r--r--tests/regressiontests/syndication/feeds.py10
-rw-r--r--tests/regressiontests/syndication/tests.py4
-rw-r--r--tests/regressiontests/templates/callables.py18
-rw-r--r--tests/regressiontests/templates/custom.py126
-rw-r--r--tests/regressiontests/templates/filters.py136
-rw-r--r--tests/regressiontests/templates/parser.py32
-rw-r--r--tests/regressiontests/templates/tests.py78
-rw-r--r--tests/regressiontests/templates/unicode.py10
-rw-r--r--tests/regressiontests/templates/urls.py6
-rw-r--r--tests/regressiontests/test_client_regress/tests.py24
-rw-r--r--tests/regressiontests/test_utils/tests.py10
-rw-r--r--tests/regressiontests/text/tests.py87
-rw-r--r--tests/regressiontests/utils/dateformat.py76
-rw-r--r--tests/regressiontests/utils/feedgenerator.py6
-rw-r--r--tests/regressiontests/utils/html.py20
-rw-r--r--tests/regressiontests/utils/ipv6.py20
-rw-r--r--tests/regressiontests/utils/jslex.py2
-rw-r--r--tests/regressiontests/utils/regex_helper.py16
-rw-r--r--tests/regressiontests/utils/simplelazyobject.py8
-rw-r--r--tests/regressiontests/utils/text.py84
-rw-r--r--tests/regressiontests/utils/timesince.py72
-rw-r--r--tests/regressiontests/views/__init__.py9
-rw-r--r--tests/regressiontests/views/generic_urls.py10
-rw-r--r--tests/regressiontests/views/tests/specials.py4
-rw-r--r--tests/regressiontests/wsgi/tests.py4
401 files changed, 6646 insertions, 6156 deletions
diff --git a/django/conf/locale/__init__.py b/django/conf/locale/__init__.py
index af08c00e98..93e98194a4 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 3dc4704972..c5e89737b6 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 56e9e73547..f0b674227b 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 68a9276328..6cf2335f5e 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 af534e60ad..cef6b4e2f9 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 7de0cd44b5..dd0d1a696e 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 198ece66b0..9a658eed40 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 6d8e334f09..3b5e8861d8 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 e83d7085a9..1c8b1b5566 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 53a8fc7cb0..a9298bf022 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 ce9d1acb9a..263aa0a344 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 70afa27c1d..ace2fc1eea 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 af65392934..3c0431e4bf 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 316d777e8b..e4ef524adf 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 8de88512a0..4a896dd80d 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 8de88512a0..4a896dd80d 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 1c538b26ab..021063d474 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 6a44d38651..6d9edeecce 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 e825824751..ec46bff400 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 0443efb376..4b2201f49a 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 ad7d3b3fee..767dbe8d3e 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 8b4606fb64..11293f047a 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 27b4efca25..b491c2d20c 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 e790e2e3b6..398af075b1 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 58130574ee..6c648ecb4a 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('<label%(attrs)s>%(contents)s</label>' % {
"attrs": flatatt(attrs),
"contents": contents,
diff --git a/django/contrib/admin/models.py b/django/contrib/admin/models.py
index 0e5b8a79da..93d8f307c0 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 bda8d4b4cd..30a85ab7f7 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'<span class="this-page">%d</span> ' % (i+1))
+ return mark_safe('<span class="this-page">%d</span> ' % (i+1))
else:
- return mark_safe(u'<a href="%s"%s>%d</a> ' % (escape(cl.get_query_string({PAGE_VAR: i})), (i == cl.paginator.num_pages-1 and ' class="end"' or ''), i+1))
+ return mark_safe('<a href="%s"%s>%d</a> ' % (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'<img src="%s" alt="%s" />' % (icon_url, field_val))
+ return mark_safe('<img src="%s" alt="%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><a href="%s"%s>%s</a></%s>' % \
+ yield mark_safe('<%s%s><a href="%s"%s>%s</a></%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'<td%s>%s</td>' % (row_class, result_repr))
+ yield mark_safe('<td%s>%s</td>' % (row_class, result_repr))
if form and not form[cl.model._meta.pk.name].is_hidden:
- yield mark_safe(u'<td>%s</td>' % force_unicode(form[cl.model._meta.pk.name]))
+ yield mark_safe('<td>%s</td>' % 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 9611b00050..18b10f3cfa 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: <a href="%s">%s</a>' %
+ return mark_safe('%s: <a href="%s">%s</a>' %
(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 980863ed84..18897bdeb1 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'<script type="text/javascript">addEvent(window, "load", function(e) {')
+ output.append('<script type="text/javascript">addEvent(window, "load", function(e) {')
# TODO: "id_" is hard-coded here. This should instead use the correct
# API to determine the ID dynamically.
- output.append(u'SelectFilter.init("id_%s", "%s", %s, "%s"); });</script>\n'
+ output.append('SelectFilter.init("id_%s", "%s", %s, "%s"); });</script>\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'<p class="datetime">%s %s<br />%s %s</p>' % \
+ return mark_safe('<p class="datetime">%s %s<br />%s %s</p>' % \
(_('Date:'), rendered_widgets[0], _('Time:'), rendered_widgets[1]))
class AdminRadioFieldRenderer(RadioFieldRenderer):
def render(self):
"""Outputs a <ul> for this set of radio fields."""
- return mark_safe(u'<ul%s>\n%s\n</ul>' % (
+ return mark_safe('<ul%s>\n%s\n</ul>' % (
flatatt(self.attrs),
- u'\n'.join([u'<li>%s</li>' % force_unicode(w) for w in self]))
+ '\n'.join(['<li>%s</li>' % force_unicode(w) for w in self]))
)
class AdminRadioSelect(forms.RadioSelect):
renderer = AdminRadioFieldRenderer
class AdminFileWidget(forms.ClearableFileInput):
- template_with_initial = (u'<p class="file-upload">%s</p>'
+ template_with_initial = ('<p class="file-upload">%s</p>'
% forms.ClearableFileInput.template_with_initial)
- template_with_clear = (u'<span class="clearable-file-input">%s</span>'
+ template_with_clear = ('<span class="clearable-file-input">%s</span>'
% 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'&amp;'.join([u'%s=%s' % (k, v) for k, v in params.items()])
+ url = '?' + '&amp;'.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'<a href="%s%s" class="related-lookup" id="lookup_id_%s" onclick="return showRelatedObjectLookupPopup(this);"> '
+ extra.append('<a href="%s%s" class="related-lookup" id="lookup_id_%s" onclick="return showRelatedObjectLookupPopup(this);"> '
% (related_url, url, name))
- extra.append(u'<img src="%s" width="16" height="16" alt="%s" /></a>'
+ extra.append('<img src="%s" width="16" height="16" alt="%s" /></a>'
% (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'<a href="%s" class="add-another" id="add_id_%s" onclick="return showAddAnotherPopup(this);"> '
+ output.append('<a href="%s" class="add-another" id="add_id_%s" onclick="return showAddAnotherPopup(this);"> '
% (related_url, name))
- output.append(u'<img src="%s" width="10" height="10" alt="%s"/></a>'
+ output.append('<img src="%s" width="10" height="10" alt="%s"/></a>'
% (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 49a925a453..306475beb1 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 04fbef4788..9088e2fbf6 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 0897de8d84..96ec40ba60 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 66f54f18a8..100acb6c5b 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 090b6d40c8..244721065d 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 7b38acfa50..9a4d8f9b3a 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 fd2b526f17..2ab895804f 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 15fc1d1da7..673263b566 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 81ab0aa052..8d1f7c7965 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 4cb90663a0..0024a1d1b5 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 a6732d7a2e..d5062cabf3 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 0057dd535d..2eaa4c182e 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 8d8e1c7a3e..5c22cb6672 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 9a4ba17e19..6a78b3688b 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'<EasyField for %s.%s>' % (self.model.model._meta.object_name, self.field.name))
+ return smart_str('<EasyField for %s.%s>' % (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'<EasyChoice for %s.%s>' % (self.model.model._meta.object_name, self.field.name))
+ return smart_str('<EasyChoice for %s.%s>' % (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'<EasyInstance for %s (%s)>' % (self.model.model._meta.object_name, self.instance._get_pk_val()))
+ return smart_str('<EasyInstance for %s (%s)>' % (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'<EasyInstanceField for %s.%s>' % (self.model.model._meta.object_name, self.field.name))
+ return smart_str('<EasyInstanceField for %s.%s>' % (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 3416f88ca7..587c752a94 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'<p class="filter"><strong>View calendar by:</strong> %s</p>' % \
- u', '.join(['<a href="calendars/%s/">%s</a>' % (f.name, force_unicode(capfirst(f.verbose_name))) for f in fields.values()]))
+ return ''
+ return mark_safe('<p class="filter"><strong>View calendar by:</strong> %s</p>' % \
+ ', '.join(['<a href="calendars/%s/">%s</a>' % (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 b3210681e9..5a13252ab3 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'<p class="filter"><strong>View by:</strong> %s</p>' % \
- u', '.join(['<a href="fields/%s/">%s</a>' % (f.name, force_unicode(capfirst(f.verbose_name))) for f in fields.values()]))
+ return ''
+ return mark_safe('<p class="filter"><strong>View by:</strong> %s</p>' % \
+ ', '.join(['<a href="fields/%s/">%s</a>' % (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 d90bb562b2..b5cb2639d6 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 85873ac7b1..42ec155f34 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 0e54176aa2..3bdfa15dfe 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 b5d905071f..3bccb55034 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 = '<input type="hidden" name="%s" value="%s" />'
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 8afbd30721..51cfaa661b 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 37913fa078..a860edd9e9 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 a9a81ba70f..a35664b322 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 c14fb858a5..d7c52bf019 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 f806dcb3c6..432f0e1872 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 7574284bba..07e12c0ca7 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 a629d86bbf..1d9132ba6f 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 3a9acad7b0..eb42d0cae8 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 936c1ded46..85e777ae78 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 <rss> 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 <feed> 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 <feed> 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 a5c8f41ba4..5f063dfba3 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 fc51a0bf3a..3fa8f044de 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 b075ff05c7..7a2e5147d8 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 bf6684766b..ecf4b83d6d 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 a0efd4ba33..600ef1eb16 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 1805839ce4..8e252beec9 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 262641bf1f..c531bec2e9 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 19df98dc33..34170fabc8 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 98e54bca2c..ab37b1d223 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 88c7f2efcc..f287d46a9a 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 c3be79968f..ec66e66539 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 649a98ab71..e844a3c57c 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 47db6d3912..d76f6ad834 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 7a9aa2da8c..5991176382 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 fe0aa37cb6..c27cba6423 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 af92ba06ec..43adcf3f01 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 f0989b6ba6..7168f54cc2 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 f3676b230b..c7e81e4037 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 80b6248ed4..a7891d117f 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 d4f324a422..9d56f9f298 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 7e55078be0..db25d26ff8 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 fe237270f5..b5e256ca44 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 4b8b886b8b..6f90e5e02b 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 ddc3b48c54..633f3e5f1b 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 34e4a96bf4..47177db685 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 9f146ac8f9..a2cca957c2 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 <www.insee.fr>.
+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 a6658578b1..bf90f80281 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 852ef7d4b2..8cf9360e19 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 0ff283d6c8..eb4436a78c 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<dd>\d{2})(?P<mm>\d{2})(?P<yyy>\d{3})' + \
r'(?P<rr>\d{2})(?P<bbb>\d{3})(?P<k>\d{1})$')
oib_re = re.compile(r'^\d{11}$')
-plate_re = re.compile(ur'^(?P<prefix>[A-ZČŠŽ]{2})' + \
- ur'(?P<number>\d{3,4})(?P<suffix>[ABCDEFGHIJKLMNOPRSTUVZ]{1,2})$')
+plate_re = re.compile(r'^(?P<prefix>[A-ZČŠŽ]{2})' + \
+ r'(?P<number>\d{3,4})(?P<suffix>[ABCDEFGHIJKLMNOPRSTUVZ]{1,2})$')
postal_code_re = re.compile(r'^\d{5}$')
phone_re = re.compile(r'^(\+385|00385|0)(?P<prefix>\d{2})(?P<number>\d{6,7})$')
jmbag_re = re.compile(r'^601983(?P<copy>\d{1})1(?P<jmbag>\d{10})(?P<k>\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 24d3d42c5b..beb2969405 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 9439dba594..f22b06134e 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 a14358737e..de6ba6b23d 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 11011e1df2..b62ec7bdb2 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 ca7bd5004e..7af9f51cfb 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 4feca9c013..f1f3357c1c 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 0060b486bd..60b1eff951 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 dcaad98c63..5aad1611dd 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 0700b46ea8..e12a1e731b 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 c162ff7eff..ec1b7e3f83 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 e671408ec8..2c2b023e70 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 33dbfc71a0..3189f0dec6 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 d6d1efa049..fb705ca820 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 deecb4ea41..2dcf17d26c 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 2aba63ef26..6ae08ccb12 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 66900808c2..bdd769bd39 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 3e5e58bd1c..4bd780a312 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 d6bacda275..d84915caa2 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 0eca2b8ac7..5100bbf575 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 9863bd3d15..9270bcecf1 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 3e8d73f0f2..12d9f3d763 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 9777ea2b61..f5263f19d2 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 3de7376eac..b27fb577bd 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 28c613b9a0..619bae3edb 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 5c458390b2..bdbed5c476 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 40423ddc87..282cfc5193 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 d01f5a1e3b..03114d0629 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 5c4e2325a9..43d06a08ec 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 db54fb9f39..20090d3b30 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 f1188dd222..aa4b9dac5a 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 7baac94e03..4d027afcff 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 83afeb41b9..11d44cc4d2 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 77a2b41986..1ffbc17361 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 0a79c40a47..33e533b4ce 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 211216222d..658defc0f0 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 97795f8e82..800937c582 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 a9e2cd60c8..a818c14428 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 65e8526b5c..e80818e84e 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 a40876e859..930f24f22c 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 5786aa48d5..d71907e09a 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 828badb386..1bb2495e6b 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 669c04043b..d3977213a9 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 dc4406e458..772220b342 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 fd8f9efb02..e02fec8ec0 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 462b3e94cf..af767e1867 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 4ad175d033..01d8f220f5 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 05d8dc7f54..b870299cda 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 = ['<p>%s</p>' % 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 8907ea3ba7..16ec501e44 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 3ba519188b..325f64d224 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 a2d703c963..04853fad0c 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 88f78904bb..68d540e595 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 4c9dfc07bc..4c07524ecc 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 128ff7ac64..5215101a35 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 1bee0cac9f..08f9702934 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 2618c7f17d..82f6b6900f 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 bcc47e17c8..fd6dbbbd2c 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 078fd6fa27..34f8041d33 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 59b2e77b69..52b2058650 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 ab702bfffb..6d0735a6f9 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 b8f491392b..ec2602d2a3 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 6a984560de..0d46c4ec70 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 19054fbfa9..b98ecfd8ff 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 bf55b0dffc..f95d4f158c 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 6460f00062..7b9e85a9ee 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 53d9736293..993d75aa6b 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 272ac5be41..7cd6958abf 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 fce00600f4..1b9a61750d 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 49120434eb..333161c929 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 a5edeac5af..9d9c023b64 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 78ce00511c..625ec6348b 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 3d4bcc86c8..c7c89786da 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 1df487bd92..ff227b6e7e 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 fe512dfee5..785e4b72a6 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 fbf7a22769..99573b9019 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 395cd92047..46b464b551 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 4fba304e23..75e1d9792c 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 32e0f4f702..775bb3e182 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 13238fc9dc..f52a626d8b 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 d572cce28f..9db76a617b 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 34cf84dbc0..e0c095974d 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 0a2223bc3f..6c39b25a74 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 3811510326..4668eade97 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 09663d173c..22c3057c62 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. '</td></tr>') 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 <tr>s -- excluding the <table></table>."
return self._html_output(
- normal_row = u'<tr%(html_class_attr)s><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>',
- error_row = u'<tr><td colspan="2">%s</td></tr>',
- row_ender = u'</td></tr>',
- help_text_html = u'<br /><span class="helptext">%s</span>',
+ normal_row = '<tr%(html_class_attr)s><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>',
+ error_row = '<tr><td colspan="2">%s</td></tr>',
+ row_ender = '</td></tr>',
+ help_text_html = '<br /><span class="helptext">%s</span>',
errors_on_separate_row = False)
def as_ul(self):
"Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
return self._html_output(
- normal_row = u'<li%(html_class_attr)s>%(errors)s%(label)s %(field)s%(help_text)s</li>',
- error_row = u'<li>%s</li>',
+ normal_row = '<li%(html_class_attr)s>%(errors)s%(label)s %(field)s%(help_text)s</li>',
+ error_row = '<li>%s</li>',
row_ender = '</li>',
- help_text_html = u' <span class="helptext">%s</span>',
+ help_text_html = ' <span class="helptext">%s</span>',
errors_on_separate_row = False)
def as_p(self):
"Returns this form rendered as HTML <p>s."
return self._html_output(
- normal_row = u'<p%(html_class_attr)s>%(label)s %(field)s%(help_text)s</p>',
- error_row = u'%s',
+ normal_row = '<p%(html_class_attr)s>%(label)s %(field)s%(help_text)s</p>',
+ error_row = '%s',
row_ender = '</p>',
- help_text_html = u' <span class="helptext">%s</span>',
+ help_text_html = ' <span class="helptext">%s</span>',
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'<label for="%s"%s>%s</label>' % (widget.id_for_label(id_), attrs, unicode(contents))
+ contents = '<label for="%s"%s>%s</label>' % (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 739a9d44e3..31ca088bdb 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 <p>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 <li>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 5fcf9590eb..26f869155b 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 6690442534..ca53b1f3d4 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'<ul class="errorlist">%s</ul>'
- % ''.join([u'<li>%s%s</li>' % (k, conditional_escape(force_unicode(v)))
+ if not self: return ''
+ return mark_safe('<ul class="errorlist">%s</ul>'
+ % ''.join(['<li>%s%s</li>' % (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'<ul class="errorlist">%s</ul>'
- % ''.join([u'<li>%s</li>' % conditional_escape(force_unicode(e)) for e in self]))
+ if not self: return ''
+ return mark_safe('<ul class="errorlist">%s</ul>'
+ % ''.join(['<li>%s</li>' % 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 4813af69e9..2fddee918a 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'<script type="text/javascript" src="%s"></script>' % self.absolute_path(path) for path in self._js]
+ return ['<script type="text/javascript" src="%s"></script>' % 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'<link href="%s" type="text/css" media="%s" rel="stylesheet" />' % (self.absolute_path(path), medium)
+ ['<link href="%s" type="text/css" media="%s" rel="stylesheet" />' % (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'<input%s />' % flatatt(final_attrs))
+ return mark_safe('<input%s />' % 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'<input%s />' % flatatt(input_attrs))
- return mark_safe(u'\n'.join(inputs))
+ inputs.append('<input%s />' % 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<br />%(input_text)s: %(input)s'
+ template_with_initial = '%(initial_text)s: %(initial)s %(clear_template)s<br />%(input_text)s: %(input)s'
- template_with_clear = u'%(clear)s <label for="%(clear_checkbox_id)s">%(clear_checkbox_label)s</label>'
+ template_with_clear = '%(clear)s <label for="%(clear_checkbox_id)s">%(clear_checkbox_label)s</label>'
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'<a href="%s">%s</a>'
+ substitutions['initial'] = ('<a href="%s">%s</a>'
% (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'<textarea%s>%s</textarea>' % (flatatt(final_attrs),
+ return mark_safe('<textarea%s>%s</textarea>' % (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'<input%s />' % flatatt(final_attrs))
+ return mark_safe('<input%s />' % 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'<select%s>' % flatatt(final_attrs)]
+ output = ['<select%s>' % flatatt(final_attrs)]
options = self.render_options(choices, [value])
if options:
output.append(options)
- output.append(u'</select>')
- return mark_safe(u'\n'.join(output))
+ output.append('</select>')
+ 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'<option value="%s"%s>%s</option>' % (
+ return '<option value="%s"%s>%s</option>' % (
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'<optgroup label="%s">' % escape(force_unicode(option_value)))
+ output.append('<optgroup label="%s">' % escape(force_unicode(option_value)))
for option in option_label:
output.append(self.render_option(selected_choices, *option))
- output.append(u'</optgroup>')
+ output.append('</optgroup>')
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'<select multiple="multiple"%s>' % flatatt(final_attrs)]
+ output = ['<select multiple="multiple"%s>' % flatatt(final_attrs)]
options = self.render_options(choices, value)
if options:
output.append(options)
output.append('</select>')
- 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'<label%s>%s %s</label>' % (label_for, self.tag(), choice_label))
+ return mark_safe('<label%s>%s %s</label>' % (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'<input%s />' % flatatt(final_attrs))
+ return mark_safe('<input%s />' % flatatt(final_attrs))
class RadioFieldRenderer(StrAndUnicode):
"""
@@ -701,7 +701,7 @@ class RadioFieldRenderer(StrAndUnicode):
def render(self):
"""Outputs a <ul> for this set of radio fields."""
- return mark_safe(u'<ul>\n%s\n</ul>' % u'\n'.join([u'<li>%s</li>'
+ return mark_safe('<ul>\n%s\n</ul>' % '\n'.join(['<li>%s</li>'
% 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'<ul>']
+ output = ['<ul>']
# 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'<li><label%s>%s %s</label></li>' % (label_for, rendered_cb, option_label))
- output.append(u'</ul>')
- return mark_safe(u'\n'.join(output))
+ output.append('<li><label%s>%s %s</label></li>' % (label_for, rendered_cb, option_label))
+ output.append('</ul>')
+ 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 bf848deb38..30d7e5dc2f 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 = '<could not parse>'
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 162c08e38d..bbe4b052b7 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 9b2404cdb3..5a91bfda99 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 1a3976f404..d2c5b03f30 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'</%s>' % 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('</%s>' % 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 3073b41049..0de5d9e3db 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"<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='%s' /></div>" % csrf_token)
+ return mark_safe("<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='%s' /></div>" % 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 8183452422..056eadc7de 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 e090781080..231b723d3a 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 3cc6a6e537..79844426f1 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 f1e4897efd..79b198f1be 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</%s>' % self.name
+ output += '>\n'
+ output += ''.join(unicode(c) for c in self.children)
+ output += '\n</%s>' % 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 e2d7b3f82e..95e751d384 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 805117df80..ca4a5e7474 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 0fce06012b..cc59e2e39f 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 e16a2df1f2..d410bce63e 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 6b246ac59b..80e456ba2a 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 7cd15674d6..52f40fb5f1 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 1b1a16a911..014d837bbb 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 = [('(', ')'), ('<', '>'), ('&lt;', '&gt;')]
# List of possible strings used for bullets in bulleted lists.
-DOTS = [u'&middot;', u'*', u'\u2022', u'&#149;', u'&bull;', u'&#8226;']
+DOTS = ['&middot;', '*', '\u2022', '&#149;', '&bull;', '&#8226;']
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'<p>%s</p>' % escape(p).replace('\n', '<br />') for p in paras]
+ paras = ['<p>%s</p>' % escape(p).replace('\n', '<br />') for p in paras]
else:
- paras = [u'<p>%s</p>' % p.replace('\n', '<br />') for p in paras]
- return u'\n\n'.join(paras)
+ paras = ['<p>%s</p>' % p.replace('\n', '<br />') 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'</p>', u'</li>')
+ s = match.group().replace('</p>', '</li>')
for d in DOTS:
- s = s.replace(u'<p>%s' % d, u'<li>')
- return u'<ul>\n%s\n</ul>' % s
+ s = s.replace('<p>%s' % d, '<li>')
+ return '<ul>\n%s\n</ul>' % s
text = hard_coded_bullets_re.sub(replace_p_tags, text)
# Remove stuff like "<p>&nbsp;&nbsp;</p>", 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 f17b263c37..4b8ecea721 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 8ae0bf7663..2546f770b5 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 276108b55a..1721f097bd 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 ac062823a4..0f1f28e5c4 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 135a8cf6d5..0cd13fd6f5 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 a07b635a99..05f4aa6d2f 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 3f108b8af2..3d66b9ef52 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 d95cd62017..25eee4a91a 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 7d3649cbff..c45bc32bf5 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 3e6ab0fa0c..26b172231c 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 4b5281745e..8cc413aa65 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 ae45fd2218..2e852699d5 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 2a756134a6..1d7891e3f4 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 = """
</body>
</html>
"""
-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 2aa3a5c641..659115dfbd 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 10108d1f4f..99547f1c9e 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 d9bfbc5e45..486d49d796 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 f1642148b5..f6cdfc8141 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 46ce4138a4..85e48ae15d 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 <arnbjorg@example.com>'
+ subject = 'My visit to Sør-Trøndelag'
+ sender = 'Arnbjörg Ráðormsdóttir <arnbjorg@example.com>'
recipients = ['Fred <fred@example.com']
- body = u'...'
+ body = '...'
msg = EmailMessage(subject, body, sender, recipients)
- msg.attach(u"Une pièce jointe.pdf", "%PDF-1.4.%...", mimetype="application/pdf")
+ msg.attach("Une pièce jointe.pdf", "%PDF-1.4.%...", mimetype="application/pdf")
msg.send()
Form submission
diff --git a/docs/topics/db/models.txt b/docs/topics/db/models.txt
index cba2c98b0d..4010ff6f9c 100644
--- a/docs/topics/db/models.txt
+++ b/docs/topics/db/models.txt
@@ -156,11 +156,11 @@ ones:
A choices list looks like this::
YEAR_IN_SCHOOL_CHOICES = (
- (u'FR', u'Freshman'),
- (u'SO', u'Sophomore'),
- (u'JR', u'Junior'),
- (u'SR', u'Senior'),
- (u'GR', u'Graduate'),
+ ('FR', 'Freshman'),
+ ('SO', 'Sophomore'),
+ ('JR', 'Junior'),
+ ('SR', 'Senior'),
+ ('GR', 'Graduate'),
)
The first element in each tuple is the value that will be stored in the
@@ -173,9 +173,9 @@ ones:
class Person(models.Model):
SHIRT_SIZES = (
- (u'S', u'Small'),
- (u'M', u'Medium'),
- (u'L', u'Large'),
+ ('S', 'Small'),
+ ('M', 'Medium'),
+ ('L', 'Large'),
)
name = models.CharField(max_length=60)
shirt_size = models.CharField(max_length=2, choices=SHIRT_SIZES)
diff --git a/docs/topics/i18n/translation.txt b/docs/topics/i18n/translation.txt
index a375ef9a47..896ff87744 100644
--- a/docs/topics/i18n/translation.txt
+++ b/docs/topics/i18n/translation.txt
@@ -416,8 +416,8 @@ result is included in a string. For example::
from django.utils.translation import string_concat
...
- name = ugettext_lazy(u'John Lennon')
- instrument = ugettext_lazy(u'guitar')
+ name = ugettext_lazy('John Lennon')
+ instrument = ugettext_lazy('guitar')
result = string_concat(name, ': ', instrument)
In this case, the lazy translations in ``result`` will only be converted to
diff --git a/tests/modeltests/aggregation/tests.py b/tests/modeltests/aggregation/tests.py
index a35dbb345f..433ea1641a 100644
--- a/tests/modeltests/aggregation/tests.py
+++ b/tests/modeltests/aggregation/tests.py
@@ -80,7 +80,7 @@ class BaseAggregateTestCase(TestCase):
b = books.get(pk=1)
self.assertEqual(
b.name,
- u'The Definitive Guide to Django: Web Development Done Right'
+ 'The Definitive Guide to Django: Web Development Done Right'
)
self.assertEqual(b.mean_age, 34.5)
@@ -88,10 +88,10 @@ class BaseAggregateTestCase(TestCase):
books = Book.objects.filter(rating__lt=4.5).annotate(Avg("authors__age")).order_by("name")
self.assertQuerysetEqual(
books, [
- (u'Artificial Intelligence: A Modern Approach', 51.5),
- (u'Practical Django Projects', 29.0),
- (u'Python Web Development with Django', Approximate(30.3, places=1)),
- (u'Sams Teach Yourself Django in 24 Hours', 45.0)
+ ('Artificial Intelligence: A Modern Approach', 51.5),
+ ('Practical Django Projects', 29.0),
+ ('Python Web Development with Django', Approximate(30.3, places=1)),
+ ('Sams Teach Yourself Django in 24 Hours', 45.0)
],
lambda b: (b.name, b.authors__age__avg),
)
@@ -99,12 +99,12 @@ class BaseAggregateTestCase(TestCase):
books = Book.objects.annotate(num_authors=Count("authors")).order_by("name")
self.assertQuerysetEqual(
books, [
- (u'Artificial Intelligence: A Modern Approach', 2),
- (u'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp', 1),
- (u'Practical Django Projects', 1),
- (u'Python Web Development with Django', 3),
- (u'Sams Teach Yourself Django in 24 Hours', 1),
- (u'The Definitive Guide to Django: Web Development Done Right', 2)
+ ('Artificial Intelligence: A Modern Approach', 2),
+ ('Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp', 1),
+ ('Practical Django Projects', 1),
+ ('Python Web Development with Django', 3),
+ ('Sams Teach Yourself Django in 24 Hours', 1),
+ ('The Definitive Guide to Django: Web Development Done Right', 2)
],
lambda b: (b.name, b.num_authors)
)
@@ -113,12 +113,12 @@ class BaseAggregateTestCase(TestCase):
authors = Author.objects.filter(name__contains="a").annotate(Avg("book__rating")).order_by("name")
self.assertQuerysetEqual(
authors, [
- (u'Adrian Holovaty', 4.5),
- (u'Brad Dayley', 3.0),
- (u'Jacob Kaplan-Moss', 4.5),
- (u'James Bennett', 4.0),
- (u'Paul Bissex', 4.0),
- (u'Stuart Russell', 4.0)
+ ('Adrian Holovaty', 4.5),
+ ('Brad Dayley', 3.0),
+ ('Jacob Kaplan-Moss', 4.5),
+ ('James Bennett', 4.0),
+ ('Paul Bissex', 4.0),
+ ('Stuart Russell', 4.0)
],
lambda a: (a.name, a.book__rating__avg)
)
@@ -126,15 +126,15 @@ class BaseAggregateTestCase(TestCase):
authors = Author.objects.annotate(num_books=Count("book")).order_by("name")
self.assertQuerysetEqual(
authors, [
- (u'Adrian Holovaty', 1),
- (u'Brad Dayley', 1),
- (u'Jacob Kaplan-Moss', 1),
- (u'James Bennett', 1),
- (u'Jeffrey Forcier', 1),
- (u'Paul Bissex', 1),
- (u'Peter Norvig', 2),
- (u'Stuart Russell', 1),
- (u'Wesley J. Chun', 1)
+ ('Adrian Holovaty', 1),
+ ('Brad Dayley', 1),
+ ('Jacob Kaplan-Moss', 1),
+ ('James Bennett', 1),
+ ('Jeffrey Forcier', 1),
+ ('Paul Bissex', 1),
+ ('Peter Norvig', 2),
+ ('Stuart Russell', 1),
+ ('Wesley J. Chun', 1)
],
lambda a: (a.name, a.num_books)
)
@@ -143,12 +143,12 @@ class BaseAggregateTestCase(TestCase):
books = Book.objects.annotate(Sum("publisher__num_awards")).order_by("name")
self.assertQuerysetEqual(
books, [
- (u'Artificial Intelligence: A Modern Approach', 7),
- (u'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp', 9),
- (u'Practical Django Projects', 3),
- (u'Python Web Development with Django', 7),
- (u'Sams Teach Yourself Django in 24 Hours', 1),
- (u'The Definitive Guide to Django: Web Development Done Right', 3)
+ ('Artificial Intelligence: A Modern Approach', 7),
+ ('Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp', 9),
+ ('Practical Django Projects', 3),
+ ('Python Web Development with Django', 7),
+ ('Sams Teach Yourself Django in 24 Hours', 1),
+ ('The Definitive Guide to Django: Web Development Done Right', 3)
],
lambda b: (b.name, b.publisher__num_awards__sum)
)
@@ -156,11 +156,11 @@ class BaseAggregateTestCase(TestCase):
publishers = Publisher.objects.annotate(Sum("book__price")).order_by("name")
self.assertQuerysetEqual(
publishers, [
- (u'Apress', Decimal("59.69")),
- (u"Jonno's House of Books", None),
- (u'Morgan Kaufmann', Decimal("75.00")),
- (u'Prentice Hall', Decimal("112.49")),
- (u'Sams', Decimal("23.09"))
+ ('Apress', Decimal("59.69")),
+ ("Jonno's House of Books", None),
+ ('Morgan Kaufmann', Decimal("75.00")),
+ ('Prentice Hall', Decimal("112.49")),
+ ('Sams', Decimal("23.09"))
],
lambda p: (p.name, p.book__price__sum)
)
@@ -252,15 +252,15 @@ class BaseAggregateTestCase(TestCase):
self.assertEqual(len(authors), 9)
self.assertQuerysetEqual(
authors, [
- (u'Adrian Holovaty', 32.0),
- (u'Brad Dayley', None),
- (u'Jacob Kaplan-Moss', 29.5),
- (u'James Bennett', 34.0),
- (u'Jeffrey Forcier', 27.0),
- (u'Paul Bissex', 31.0),
- (u'Peter Norvig', 46.0),
- (u'Stuart Russell', 57.0),
- (u'Wesley J. Chun', Approximate(33.66, places=1))
+ ('Adrian Holovaty', 32.0),
+ ('Brad Dayley', None),
+ ('Jacob Kaplan-Moss', 29.5),
+ ('James Bennett', 34.0),
+ ('Jeffrey Forcier', 27.0),
+ ('Paul Bissex', 31.0),
+ ('Peter Norvig', 46.0),
+ ('Stuart Russell', 57.0),
+ ('Wesley J. Chun', Approximate(33.66, places=1))
],
lambda a: (a.name, a.friends__age__avg)
)
@@ -498,25 +498,25 @@ class BaseAggregateTestCase(TestCase):
'earliest_book': datetime.date(1991, 10, 15),
'num_awards': 9,
'id': 4,
- 'name': u'Morgan Kaufmann'
+ 'name': 'Morgan Kaufmann'
},
{
'earliest_book': datetime.date(1995, 1, 15),
'num_awards': 7,
'id': 3,
- 'name': u'Prentice Hall'
+ 'name': 'Prentice Hall'
},
{
'earliest_book': datetime.date(2007, 12, 6),
'num_awards': 3,
'id': 1,
- 'name': u'Apress'
+ 'name': 'Apress'
},
{
'earliest_book': datetime.date(2008, 3, 3),
'num_awards': 1,
'id': 2,
- 'name': u'Sams'
+ 'name': 'Sams'
}
]
)
diff --git a/tests/modeltests/basic/tests.py b/tests/modeltests/basic/tests.py
index 84e20487c5..3f00fb25fe 100644
--- a/tests/modeltests/basic/tests.py
+++ b/tests/modeltests/basic/tests.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from datetime import datetime
@@ -187,7 +187,7 @@ class ModelTest(TestCase):
# the default.
a6 = Article(pub_date=datetime(2005, 7, 31))
a6.save()
- self.assertEqual(a6.headline, u'Default headline')
+ self.assertEqual(a6.headline, 'Default headline')
# For DateTimeFields, Django saves as much precision (in seconds)
# as you give it.
@@ -466,7 +466,7 @@ class ModelTest(TestCase):
)
a101.save()
a101 = Article.objects.get(pk=101)
- self.assertEqual(a101.headline, u'Article 101')
+ self.assertEqual(a101.headline, 'Article 101')
def test_create_method(self):
# You can create saved objects in a single step
@@ -493,12 +493,12 @@ class ModelTest(TestCase):
def test_unicode_data(self):
# Unicode data works, too.
a = Article(
- headline=u'\u6797\u539f \u3081\u3050\u307f',
+ headline='\u6797\u539f \u3081\u3050\u307f',
pub_date=datetime(2005, 7, 28),
)
a.save()
self.assertEqual(Article.objects.get(pk=a.id).headline,
- u'\u6797\u539f \u3081\u3050\u307f')
+ '\u6797\u539f \u3081\u3050\u307f')
def test_hash_function(self):
# Model instances have a hash function, so they can be used in sets
@@ -557,7 +557,7 @@ class ModelTest(TestCase):
select={'dashed-value': '1'}
).values('headline', 'dashed-value')
self.assertEqual([sorted(d.items()) for d in dicts],
- [[('dashed-value', 1), ('headline', u'Article 11')], [('dashed-value', 1), ('headline', u'Article 12')]])
+ [[('dashed-value', 1), ('headline', 'Article 11')], [('dashed-value', 1), ('headline', 'Article 12')]])
def test_extra_method_select_argument_with_dashes(self):
# If you use 'select' with extra() and names containing dashes on a
@@ -586,7 +586,7 @@ class ModelTest(TestCase):
Test that ugettext_lazy objects work when saving model instances
through various methods. Refs #10498.
"""
- notlazy = u'test'
+ notlazy = 'test'
lazy = ugettext_lazy(notlazy)
reporter = Article.objects.create(headline=lazy, pub_date=datetime.now())
article = Article.objects.get()
diff --git a/tests/modeltests/custom_columns/models.py b/tests/modeltests/custom_columns/models.py
index 17d3d79f7b..39f1274a8f 100644
--- a/tests/modeltests/custom_columns/models.py
+++ b/tests/modeltests/custom_columns/models.py
@@ -15,6 +15,8 @@ from the default generated name, use the ``db_table`` parameter on the
"""
+from __future__ import unicode_literals
+
from django.db import models
@@ -23,7 +25,7 @@ class Author(models.Model):
last_name = models.CharField(max_length=30, db_column='last')
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/modeltests/custom_managers/models.py b/tests/modeltests/custom_managers/models.py
index 1052552bb3..a9845ad414 100644
--- a/tests/modeltests/custom_managers/models.py
+++ b/tests/modeltests/custom_managers/models.py
@@ -9,6 +9,8 @@ There are two reasons you might want to customize a ``Manager``: to add extra
returns.
"""
+from __future__ import unicode_literals
+
from django.db import models
# An example of a custom manager called "objects".
@@ -24,7 +26,7 @@ class Person(models.Model):
objects = PersonManager()
def __unicode__(self):
- return u"%s %s" % (self.first_name, self.last_name)
+ return "%s %s" % (self.first_name, self.last_name)
# An example of a custom manager that sets get_query_set().
diff --git a/tests/modeltests/custom_pk/models.py b/tests/modeltests/custom_pk/models.py
index e8647800cd..8199b05a1a 100644
--- a/tests/modeltests/custom_pk/models.py
+++ b/tests/modeltests/custom_pk/models.py
@@ -6,7 +6,7 @@ By default, Django adds an ``"id"`` field to each model. But you can override
this behavior by explicitly adding ``primary_key=True`` to a field.
"""
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from django.db import models
@@ -21,7 +21,7 @@ class Employee(models.Model):
ordering = ('last_name', 'first_name')
def __unicode__(self):
- return u"%s %s" % (self.first_name, self.last_name)
+ return "%s %s" % (self.first_name, self.last_name)
class Business(models.Model):
name = models.CharField(max_length=20, primary_key=True)
diff --git a/tests/modeltests/custom_pk/tests.py b/tests/modeltests/custom_pk/tests.py
index 1e3ca8e58c..b473dcab59 100644
--- a/tests/modeltests/custom_pk/tests.py
+++ b/tests/modeltests/custom_pk/tests.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from django.db import transaction, IntegrityError
from django.test import TestCase, skipIfDBFeature
@@ -140,7 +140,7 @@ class CustomPKTests(TestCase):
def test_unicode_pk(self):
# Primary key may be unicode string
- bus = Business.objects.create(name=u'jaźń')
+ bus = Business.objects.create(name='jaźń')
def test_unique_pk(self):
# The primary key must also obviously be unique, so trying to create a
diff --git a/tests/modeltests/distinct_on_fields/models.py b/tests/modeltests/distinct_on_fields/models.py
index be0b591107..33665e9624 100644
--- a/tests/modeltests/distinct_on_fields/models.py
+++ b/tests/modeltests/distinct_on_fields/models.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.db import models
class Tag(models.Model):
@@ -36,4 +38,4 @@ class StaffTag(models.Model):
tag = models.ForeignKey(Tag)
def __unicode__(self):
- return u"%s -> %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 4d827d15b6..f62a32e58d 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 dd504999ff..018a0cf795 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 8f4f5461a5..c4e2707109 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 4d809ba6f8..b9987c0fab 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 837723a049..3e256f787f 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 a415fdf6a7..17538ed7e8 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 f3e216edf5..f2dcf7db24 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 0ac552cf77..d3de71d917 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(), ["<TaggedItem: salty>"])
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"""<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag">Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" maxlength="50" /></p>
+ self.assertHTMLEqual(''.join(form.as_p() for form in formset.forms), """<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag">Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" maxlength="50" /></p>
<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">Delete:</label> <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE" /><input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id" id="id_generic_relations-taggeditem-content_type-object_id-0-id" /></p>""")
formset = GenericFormSet(instance=Animal())
- self.assertHTMLEqual(u''.join(form.as_p() for form in formset.forms), u"""<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag">Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" maxlength="50" /></p>
+ self.assertHTMLEqual(''.join(form.as_p() for form in formset.forms), """<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag">Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" maxlength="50" /></p>
<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">Delete:</label> <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE" /><input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id" id="id_generic_relations-taggeditem-content_type-object_id-0-id" /></p>""")
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"""<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag">Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" value="shiny" maxlength="50" /></p>
+ self.assertHTMLEqual(''.join(form.as_p() for form in formset.forms), """<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag">Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" value="shiny" maxlength="50" /></p>
<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">Delete:</label> <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE" /><input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id" value="%s" id="id_generic_relations-taggeditem-content_type-object_id-0-id" /></p><p><label for="id_generic_relations-taggeditem-content_type-object_id-1-tag">Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-1-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-1-tag" maxlength="50" /></p>
<p><label for="id_generic_relations-taggeditem-content_type-object_id-1-DELETE">Delete:</label> <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-1-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-1-DELETE" /><input type="hidden" name="generic_relations-taggeditem-content_type-object_id-1-id" id="id_generic_relations-taggeditem-content_type-object_id-1-id" /></p>""" % 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"""<p><label for="id_x-0-tag">Tag:</label> <input id="id_x-0-tag" type="text" name="x-0-tag" maxlength="50" /></p>
+ self.assertHTMLEqual(''.join(form.as_p() for form in formset.forms), """<p><label for="id_x-0-tag">Tag:</label> <input id="id_x-0-tag" type="text" name="x-0-tag" maxlength="50" /></p>
<p><label for="id_x-0-DELETE">Delete:</label> <input type="checkbox" name="x-0-DELETE" id="id_x-0-DELETE" /><input type="hidden" name="x-0-id" id="id_x-0-id" /></p>""")
def test_gfk_manager(self):
diff --git a/tests/modeltests/get_or_create/models.py b/tests/modeltests/get_or_create/models.py
index 1de5a6ecec..78b92f09df 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 ed69fb60ee..b2ba253c5d 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 bcdd3d7c68..3e5d61538a 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 502e0d5f2b..98358e3d10 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 9368398f71..6c1f277811 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 ea9b83ea14..85786e8458 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 94be628a42..259dc68a0b 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 1e4afcf22f..0d2688e8a4 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 aed952fe2f..257025583b 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']),
[
"<Article: John's second story>",
"<Article: This is a test>",
@@ -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 35fc9a7bc1..a4ce86f184 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 af8bcbca4e..281316a28e 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):
<option value="3">Live</option>
</select></li>''' % (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(), '''<li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" /></li>
<li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" /></li>
@@ -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):
</select></li>''' % (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']), '''<select name="parent" id="id_parent">
@@ -1471,7 +1471,7 @@ class OldFormForXTests(TestCase):
# to_field_name should also work on ModelMultipleChoiceField ##################
field = forms.ModelMultipleChoiceField(Inventory.objects.all(), to_field_name='barcode')
- self.assertEqual(tuple(field.choices), ((86, u'Apple'), (87, u'Core'), (22, u'Pear')))
+ self.assertEqual(tuple(field.choices), ((86, 'Apple'), (87, 'Core'), (22, 'Pear')))
self.assertEqual(map(lambda o: o.name, field.clean([86])), ['Apple'])
form = SelectInventoryForm({'items': [87, 22]})
diff --git a/tests/modeltests/model_formsets/models.py b/tests/modeltests/model_formsets/models.py
index b915c07eb2..055aa8dff1 100644
--- a/tests/modeltests/model_formsets/models.py
+++ b/tests/modeltests/model_formsets/models.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import datetime
from django.db import models
@@ -34,7 +36,7 @@ class BookWithCustomPK(models.Model):
title = models.CharField(max_length=100)
def __unicode__(self):
- return u'%s: %s' % (self.my_pk, self.title)
+ return '%s: %s' % (self.my_pk, self.title)
class Editor(models.Model):
name = models.CharField(max_length=100)
@@ -57,7 +59,7 @@ class AlternateBook(Book):
notes = models.CharField(max_length=100)
def __unicode__(self):
- return u'%s - %s' % (self.title, self.notes)
+ return '%s - %s' % (self.title, self.notes)
class AuthorMeeting(models.Model):
name = models.CharField(max_length=100)
@@ -119,7 +121,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'),)
@@ -147,7 +149,7 @@ class Revision(models.Model):
unique_together = (("repository", "revision"),)
def __unicode__(self):
- return u"%s (%s)" % (self.revision, unicode(self.repository))
+ return "%s (%s)" % (self.revision, unicode(self.repository))
# models for testing callable defaults (see bug #7975). If you define a model
# with a callable default value, you cannot rely on the initial value in a
diff --git a/tests/modeltests/model_formsets/tests.py b/tests/modeltests/model_formsets/tests.py
index 46941471b1..309dd3aaa2 100644
--- a/tests/modeltests/model_formsets/tests.py
+++ b/tests/modeltests/model_formsets/tests.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import datetime
import re
@@ -23,12 +23,12 @@ class DeletionTests(TestCase):
PoetFormSet = modelformset_factory(Poet, can_delete=True)
poet = Poet.objects.create(name='test')
data = {
- 'form-TOTAL_FORMS': u'1',
- 'form-INITIAL_FORMS': u'1',
- 'form-MAX_NUM_FORMS': u'0',
+ 'form-TOTAL_FORMS': '1',
+ 'form-INITIAL_FORMS': '1',
+ 'form-MAX_NUM_FORMS': '0',
'form-0-id': str(poet.pk),
- 'form-0-name': u'test',
- 'form-0-DELETE': u'on',
+ 'form-0-name': 'test',
+ 'form-0-DELETE': 'on',
}
formset = PoetFormSet(data, queryset=Poet.objects.all())
formset.save()
@@ -42,11 +42,11 @@ class DeletionTests(TestCase):
"""
PoetFormSet = modelformset_factory(Poet, can_delete=True)
data = {
- 'form-TOTAL_FORMS': u'1',
- 'form-INITIAL_FORMS': u'0',
- 'form-MAX_NUM_FORMS': u'0',
- 'form-0-id': u'',
- 'form-0-name': u'x' * 1000,
+ 'form-TOTAL_FORMS': '1',
+ 'form-INITIAL_FORMS': '0',
+ 'form-MAX_NUM_FORMS': '0',
+ 'form-0-id': '',
+ 'form-0-name': 'x' * 1000,
}
formset = PoetFormSet(data, queryset=Poet.objects.all())
# Make sure this form doesn't pass validation.
@@ -69,11 +69,11 @@ class DeletionTests(TestCase):
PoetFormSet = modelformset_factory(Poet, can_delete=True)
poet = Poet.objects.create(name='test')
data = {
- 'form-TOTAL_FORMS': u'1',
- 'form-INITIAL_FORMS': u'1',
- 'form-MAX_NUM_FORMS': u'0',
+ 'form-TOTAL_FORMS': '1',
+ 'form-INITIAL_FORMS': '1',
+ 'form-MAX_NUM_FORMS': '0',
'form-0-id': unicode(poet.id),
- 'form-0-name': u'x' * 1000,
+ 'form-0-name': 'x' * 1000,
}
formset = PoetFormSet(data, queryset=Poet.objects.all())
# Make sure this form doesn't pass validation.
@@ -245,7 +245,7 @@ class ModelFormsetTest(TestCase):
# create an Author instance to add to the meeting.
- author4 = Author.objects.create(name=u'John Steinbeck')
+ author4 = Author.objects.create(name='John Steinbeck')
AuthorMeetingFormSet = modelformset_factory(AuthorMeeting, extra=1, can_delete=True)
data = {
@@ -329,7 +329,7 @@ class ModelFormsetTest(TestCase):
def save(self, commit=True):
# change the name to "Vladimir Mayakovsky" just to be a jerk.
author = super(PoetForm, self).save(commit=False)
- author.name = u"Vladimir Mayakovsky"
+ author.name = "Vladimir Mayakovsky"
if commit:
author.save()
return author
@@ -640,7 +640,7 @@ class ModelFormsetTest(TestCase):
def save(self, commit=True):
# change the name to "Brooklyn Bridge" just to be a jerk.
poem = super(PoemForm, self).save(commit=False)
- poem.name = u"Brooklyn Bridge"
+ poem.name = "Brooklyn Bridge"
if commit:
poem.save()
return poem
@@ -731,7 +731,7 @@ class ModelFormsetTest(TestCase):
# Custom primary keys with ForeignKey, OneToOneField and AutoField ############
- 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, Owner, extra=2, can_delete=False)
formset = FormSet(instance=place)
@@ -746,7 +746,7 @@ class ModelFormsetTest(TestCase):
'owner_set-INITIAL_FORMS': '0',
'owner_set-MAX_NUM_FORMS': '',
'owner_set-0-auto_id': '',
- 'owner_set-0-name': u'Joe Perry',
+ 'owner_set-0-name': 'Joe Perry',
'owner_set-1-auto_id': '',
'owner_set-1-name': '',
}
@@ -773,9 +773,9 @@ class ModelFormsetTest(TestCase):
'owner_set-INITIAL_FORMS': '1',
'owner_set-MAX_NUM_FORMS': '',
'owner_set-0-auto_id': unicode(owner1.auto_id),
- 'owner_set-0-name': u'Joe Perry',
+ 'owner_set-0-name': 'Joe Perry',
'owner_set-1-auto_id': '',
- 'owner_set-1-name': u'Jack Berry',
+ 'owner_set-1-name': 'Jack Berry',
'owner_set-2-auto_id': '',
'owner_set-2-name': '',
}
@@ -800,7 +800,7 @@ class ModelFormsetTest(TestCase):
'<p><label for="id_form-0-age">Age:</label> <input type="text" name="form-0-age" id="id_form-0-age" /></p>'
% (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 a0fed8a5cc..37ca603021 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 429c1d019f..8c6d56a795 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 b7e217ebeb..9ced9edff2 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"<Page 1 of 2>", unicode(p))
+ self.assertEqual("<Page 1 of 2>", unicode(p))
self.assertQuerysetEqual(p.object_list, [
"<Article: Article 1>",
"<Article: Article 2>",
@@ -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"<Page 2 of 2>", unicode(p))
+ self.assertEqual("<Page 2 of 2>", unicode(p))
self.assertQuerysetEqual(p.object_list, [
"<Article: Article 6>",
"<Article: Article 7>",
@@ -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"<Page 1 of 2>", unicode(p))
+ self.assertEqual("<Page 1 of 2>", 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 b21244b6d9..43f195d357 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"<Author: Charlotte>"])
+ self.assertQuerysetEqual(self.book2.authors.all(), ["<Author: Charlotte>"])
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 738e0dbce2..7ec86e9b22 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 515c7f6c91..bae60e4b86 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 ebe2f8c2be..557a5c318a 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 9948afd4e0..3549be1b4f 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 e792c944a1..13cf1e7e17 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 53b8f26606..18ca467655 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 1b0eb0972f..bed9ea719b 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 a533d6a280..399d2906a8 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 bd9c7658f9..aadb8ba842 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 66acb9fc63..7a51b9ac1c 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 c31f4dfaa9..7a1177c1fd 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 1a6fdd7c16..0adc9fec32 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 4aea3d52de..62ca4e95c6 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 8f819b9d9c..038da16494 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 f255498306..4f658203df 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 d82b95e3ad..e58d9fd4a6 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 a1a48bf97c..018be6ae59 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 6197827793..4a6235e7d5 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 deb8ee88c3..371c67061f 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 8c9788b985..72cc5d7ee5 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 f2add00288..d7526d6020 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 2cca67012f..94790af56c 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 b82f150f40..faae834f93 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 055f494dcd..ba2be363ca 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'<img src="%sadmin/img/icon-unknown.gif" alt="None" />' % settings.STATIC_URL
+ expected = '<img src="%sadmin/img/icon-unknown.gif" alt="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 d9607496c3..01a19e6373 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 17533f9f80..5aa775656b 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 f9a9b15114..e220011fdc 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"&lt;p&gt;Middle content&lt;/p&gt;",
- "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"&lt;p&gt;Oldest content&lt;/p&gt;",
- "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"&lt;p&gt;Newest content&lt;/p&gt;",
- "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": "&lt;p&gt;Middle content&lt;/p&gt;",
+ "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": "&lt;p&gt;Oldest content&lt;/p&gt;",
+ "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": "&lt;p&gt;Newest content&lt;/p&gt;",
+ "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"&lt;p&gt;Svært frustrerende med UnicodeDecodeError&lt;/p&gt;",
- "chapter_set-1-id": u"2",
- "chapter_set-1-title": u"Kjærlighet.",
- "chapter_set-1-content": u"&lt;p&gt;La kjærligheten til de lidende seire.&lt;/p&gt;",
- "chapter_set-2-id": u"3",
- "chapter_set-2-title": u"Need a title.",
- "chapter_set-2-content": u"&lt;p&gt;Newest content&lt;/p&gt;",
- "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": "&lt;p&gt;Svært frustrerende med UnicodeDecodeError&lt;/p&gt;",
+ "chapter_set-1-id": "2",
+ "chapter_set-1-title": "Kjærlighet.",
+ "chapter_set-1-content": "&lt;p&gt;La kjærligheten til de lidende seire.&lt;/p&gt;",
+ "chapter_set-2-id": "3",
+ "chapter_set-2-title": "Need a title.",
+ "chapter_set-2-content": "&lt;p&gt;Newest content&lt;/p&gt;",
+ "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, '<li class="info">The paper &quot;Paper_Deferred_author object&quot; was changed successfully.</li>', 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 1973d5069f..81a4ec7aba 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 be1d294051..4b115431c1 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 36a54c0b17..e5f12e5781 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 1a78a87eca..af4952dce8 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 109e1a5bcc..2569a3236f 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 88fe5471cf..264ef74abd 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 5edc58fe2d..429f3b2bf2 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 2d9b4f755f..52fd3ea1c7 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="""
<html><body><h1>\u00a1Unicode!<form method="post"><input type="text" /></form></body></html>
""", 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 fcb5a4be44..c768c12772 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 fb94e831ba..f8f6802041 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 7d0b8d61b6..ffa0a01132 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'<script>and this</script>'),
- 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'<script>and this</script>'),
+ '\\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 &amp; Jill &amp; Jeroboam')
+ self.assertEqual(fix_ampersands_filter('Jack & Jill & Jeroboam'),
+ 'Jack &amp; Jill &amp; 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'<p>one <a href="#">two - three <br>four</a> five</p>', 0), u'')
- self.assertEqual(truncatewords_html(u'<p>one <a href="#">two - '\
- u'three <br>four</a> five</p>', 2),
- u'<p>one <a href="#">two ...</a></p>')
+ '<p>one <a href="#">two - three <br>four</a> five</p>', 0), '')
+ self.assertEqual(truncatewords_html('<p>one <a href="#">two - '\
+ 'three <br>four</a> five</p>', 2),
+ '<p>one <a href="#">two ...</a></p>')
self.assertEqual(truncatewords_html(
- u'<p>one <a href="#">two - three <br>four</a> five</p>', 4),
- u'<p>one <a href="#">two - three <br>four ...</a></p>')
+ '<p>one <a href="#">two - three <br>four</a> five</p>', 4),
+ '<p>one <a href="#">two - three <br>four ...</a></p>')
self.assertEqual(truncatewords_html(
- u'<p>one <a href="#">two - three <br>four</a> five</p>', 5),
- u'<p>one <a href="#">two - three <br>four</a> five</p>')
+ '<p>one <a href="#">two - three <br>four</a> five</p>', 5),
+ '<p>one <a href="#">two - three <br>four</a> five</p>')
self.assertEqual(truncatewords_html(
- u'<p>one <a href="#">two - three <br>four</a> five</p>', 100),
- u'<p>one <a href="#">two - three <br>four</a> five</p>')
+ '<p>one <a href="#">two - three <br>four</a> five</p>', 100),
+ '<p>one <a href="#">two - three <br>four</a> five</p>')
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'<a href='\
- u'"http://short.com/" rel="nofollow">http://short.com/</a>')
+ self.assertEqual(urlizetrunc('http://short.com/', 20), '<a href='\
+ '"http://short.com/" rel="nofollow">http://short.com/</a>')
- self.assertEqual(urlizetrunc(u'http://www.google.co.uk/search?hl=en'\
- u'&q=some+long+url&btnG=Search&meta=', 20), u'<a href="http://'\
- u'www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search&'\
- u'meta=" rel="nofollow">http://www.google...</a>')
+ self.assertEqual(urlizetrunc('http://www.google.co.uk/search?hl=en'\
+ '&q=some+long+url&btnG=Search&meta=', 20), '<a href="http://'\
+ 'www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search&'\
+ 'meta=" rel="nofollow">http://www.google...</a>')
self.assertEqual(urlizetrunc('http://www.google.co.uk/search?hl=en'\
- u'&q=some+long+url&btnG=Search&meta=', 20), u'<a href="http://'\
- u'www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search'\
- u'&meta=" rel="nofollow">http://www.google...</a>')
+ '&q=some+long+url&btnG=Search&meta=', 20), '<a href="http://'\
+ 'www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search'\
+ '&meta=" rel="nofollow">http://www.google...</a>')
# 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'<a href="http://31characteruri.com/test/" rel="nofollow">'\
- u'http://31characteruri.com/test/</a>')
+ '<a href="http://31characteruri.com/test/" rel="nofollow">'\
+ 'http://31characteruri.com/test/</a>')
self.assertEqual(urlizetrunc(uri, 30),
- u'<a href="http://31characteruri.com/test/" rel="nofollow">'\
- u'http://31characteruri.com/t...</a>')
+ '<a href="http://31characteruri.com/test/" rel="nofollow">'\
+ 'http://31characteruri.com/t...</a>')
self.assertEqual(urlizetrunc(uri, 2),
- u'<a href="http://31characteruri.com/test/"'\
- u' rel="nofollow">...</a>')
+ '<a href="http://31characteruri.com/test/"'\
+ ' rel="nofollow">...</a>')
def test_urlize(self):
# Check normal urlize
self.assertEqual(urlize('http://google.com'),
- u'<a href="http://google.com" rel="nofollow">http://google.com</a>')
+ '<a href="http://google.com" rel="nofollow">http://google.com</a>')
self.assertEqual(urlize('http://google.com/'),
- u'<a href="http://google.com/" rel="nofollow">http://google.com/</a>')
+ '<a href="http://google.com/" rel="nofollow">http://google.com/</a>')
self.assertEqual(urlize('www.google.com'),
- u'<a href="http://www.google.com" rel="nofollow">www.google.com</a>')
+ '<a href="http://www.google.com" rel="nofollow">www.google.com</a>')
self.assertEqual(urlize('djangoproject.org'),
- u'<a href="http://djangoproject.org" rel="nofollow">djangoproject.org</a>')
+ '<a href="http://djangoproject.org" rel="nofollow">djangoproject.org</a>')
self.assertEqual(urlize('info@djangoproject.org'),
- u'<a href="mailto:info@djangoproject.org">info@djangoproject.org</a>')
+ '<a href="mailto:info@djangoproject.org">info@djangoproject.org</a>')
# Check urlize with https addresses
self.assertEqual(urlize('https://google.com'),
- u'<a href="https://google.com" rel="nofollow">https://google.com</a>')
+ '<a href="https://google.com" rel="nofollow">https://google.com</a>')
# Check urlize doesn't overquote already quoted urls - see #9655
self.assertEqual(urlize('http://hi.baidu.com/%D6%D8%D0%C2%BF'),
- u'<a href="http://hi.baidu.com/%D6%D8%D0%C2%BF" rel="nofollow">'
- u'http://hi.baidu.com/%D6%D8%D0%C2%BF</a>')
+ '<a href="http://hi.baidu.com/%D6%D8%D0%C2%BF" rel="nofollow">'
+ 'http://hi.baidu.com/%D6%D8%D0%C2%BF</a>')
self.assertEqual(urlize('www.mystore.com/30%OffCoupons!'),
- u'<a href="http://www.mystore.com/30%25OffCoupons!" rel="nofollow">'
- u'www.mystore.com/30%OffCoupons!</a>')
+ '<a href="http://www.mystore.com/30%25OffCoupons!" rel="nofollow">'
+ 'www.mystore.com/30%OffCoupons!</a>')
self.assertEqual(urlize('http://en.wikipedia.org/wiki/Caf%C3%A9'),
- u'<a href="http://en.wikipedia.org/wiki/Caf%C3%A9" rel="nofollow">'
- u'http://en.wikipedia.org/wiki/Caf%C3%A9</a>')
+ '<a href="http://en.wikipedia.org/wiki/Caf%C3%A9" rel="nofollow">'
+ 'http://en.wikipedia.org/wiki/Caf%C3%A9</a>')
self.assertEqual(urlize('http://en.wikipedia.org/wiki/Café'),
- u'<a href="http://en.wikipedia.org/wiki/Caf%C3%A9" rel="nofollow">'
- u'http://en.wikipedia.org/wiki/Café</a>')
+ '<a href="http://en.wikipedia.org/wiki/Caf%C3%A9" rel="nofollow">'
+ 'http://en.wikipedia.org/wiki/Café</a>')
# Check urlize keeps balanced parentheses - see #11911
self.assertEqual(urlize('http://en.wikipedia.org/wiki/Django_(web_framework)'),
- u'<a href="http://en.wikipedia.org/wiki/Django_(web_framework)" rel="nofollow">'
- u'http://en.wikipedia.org/wiki/Django_(web_framework)</a>')
+ '<a href="http://en.wikipedia.org/wiki/Django_(web_framework)" rel="nofollow">'
+ 'http://en.wikipedia.org/wiki/Django_(web_framework)</a>')
self.assertEqual(urlize('(see http://en.wikipedia.org/wiki/Django_(web_framework))'),
- u'(see <a href="http://en.wikipedia.org/wiki/Django_(web_framework)" rel="nofollow">'
- u'http://en.wikipedia.org/wiki/Django_(web_framework)</a>)')
+ '(see <a href="http://en.wikipedia.org/wiki/Django_(web_framework)" rel="nofollow">'
+ 'http://en.wikipedia.org/wiki/Django_(web_framework)</a>)')
# Check urlize adds nofollow properly - see #12183
self.assertEqual(urlize('foo@bar.com or www.bar.com'),
- u'<a href="mailto:foo@bar.com">foo@bar.com</a> or '
- u'<a href="http://www.bar.com" rel="nofollow">www.bar.com</a>')
+ '<a href="mailto:foo@bar.com">foo@bar.com</a> or '
+ '<a href="http://www.bar.com" rel="nofollow">www.bar.com</a>')
# Check urlize handles IDN correctly - see #13704
self.assertEqual(urlize('http://c✶.ws'),
- u'<a href="http://xn--c-lgq.ws" rel="nofollow">http://c✶.ws</a>')
+ '<a href="http://xn--c-lgq.ws" rel="nofollow">http://c✶.ws</a>')
self.assertEqual(urlize('www.c✶.ws'),
- u'<a href="http://www.xn--c-lgq.ws" rel="nofollow">www.c✶.ws</a>')
+ '<a href="http://www.xn--c-lgq.ws" rel="nofollow">www.c✶.ws</a>')
self.assertEqual(urlize('c✶.org'),
- u'<a href="http://xn--c-lgq.org" rel="nofollow">c✶.org</a>')
+ '<a href="http://xn--c-lgq.org" rel="nofollow">c✶.org</a>')
self.assertEqual(urlize('info@c✶.org'),
- u'<a href="mailto:info@xn--c-lgq.org">info@c✶.org</a>')
+ '<a href="mailto:info@xn--c-lgq.org">info@c✶.org</a>')
# 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'<a href="http://usa.gov" rel="nofollow">usa.gov</a>')
+ '<a href="http://usa.gov" rel="nofollow">usa.gov</a>')
# 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'<a href="https://github.com/" rel="nofollow">HTTPS://github.com/</a>')
+ '<a href="https://github.com/" rel="nofollow">HTTPS://github.com/</a>')
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'<some html & special characters > here')
+ escaped = force_escape('<some html & special characters > here')
self.assertEqual(
- escaped, u'&lt;some html &amp; special characters &gt; here')
+ escaped, '&lt;some html &amp; special characters &gt; here')
self.assertTrue(isinstance(escaped, SafeData))
self.assertEqual(
- force_escape(u'<some html & special characters > here ĐÅ€£'),
- u'&lt;some html &amp; special characters &gt; here'\
- u' \u0110\xc5\u20ac\xa3')
+ force_escape('<some html & special characters > here ĐÅ€£'),
+ '&lt;some html &amp; special characters &gt; here'\
+ ' \u0110\xc5\u20ac\xa3')
def test_linebreaks(self):
- self.assertEqual(linebreaks_filter(u'line 1'), u'<p>line 1</p>')
- self.assertEqual(linebreaks_filter(u'line 1\nline 2'),
- u'<p>line 1<br />line 2</p>')
- self.assertEqual(linebreaks_filter(u'line 1\rline 2'),
- u'<p>line 1<br />line 2</p>')
- self.assertEqual(linebreaks_filter(u'line 1\r\nline 2'),
- u'<p>line 1<br />line 2</p>')
+ self.assertEqual(linebreaks_filter('line 1'), '<p>line 1</p>')
+ self.assertEqual(linebreaks_filter('line 1\nline 2'),
+ '<p>line 1<br />line 2</p>')
+ self.assertEqual(linebreaks_filter('line 1\rline 2'),
+ '<p>line 1<br />line 2</p>')
+ self.assertEqual(linebreaks_filter('line 1\r\nline 2'),
+ '<p>line 1<br />line 2</p>')
def test_linebreaksbr(self):
- self.assertEqual(linebreaksbr(u'line 1\nline 2'),
- u'line 1<br />line 2')
- self.assertEqual(linebreaksbr(u'line 1\rline 2'),
- u'line 1<br />line 2')
- self.assertEqual(linebreaksbr(u'line 1\r\nline 2'),
- u'line 1<br />line 2')
+ self.assertEqual(linebreaksbr('line 1\nline 2'),
+ 'line 1<br />line 2')
+ self.assertEqual(linebreaksbr('line 1\rline 2'),
+ 'line 1<br />line 2')
+ self.assertEqual(linebreaksbr('line 1\r\nline 2'),
+ 'line 1<br />line 2')
def test_removetags(self):
- self.assertEqual(removetags(u'some <b>html</b> with <script>alert'\
- u'("You smell")</script> disallowed <img /> tags', 'script img'),
- u'some <b>html</b> with alert("You smell") disallowed tags')
- self.assertEqual(striptags(u'some <b>html</b> with <script>alert'\
- u'("You smell")</script> disallowed <img /> tags'),
- u'some html with alert("You smell") disallowed tags')
+ self.assertEqual(removetags('some <b>html</b> with <script>alert'\
+ '("You smell")</script> disallowed <img /> tags', 'script img'),
+ 'some <b>html</b> with alert("You smell") disallowed tags')
+ self.assertEqual(striptags('some <b>html</b> with <script>alert'\
+ '("You smell")</script> disallowed <img /> 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<li>item 1</li>\n\t<li>item 2</li>')
- self.assertEqual(unordered_list([u'item 1', [u'item 1.1']]),
- u'\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t</ul>\n\t</li>')
+ self.assertEqual(unordered_list(['item 1', 'item 2']),
+ '\t<li>item 1</li>\n\t<li>item 2</li>')
+ self.assertEqual(unordered_list(['item 1', ['item 1.1']]),
+ '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t</ul>\n\t</li>')
self.assertEqual(
- unordered_list([u'item 1', [u'item 1.1', u'item1.2'], u'item 2']),
- u'\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t\t<li>item1.2'\
- u'</li>\n\t</ul>\n\t</li>\n\t<li>item 2</li>')
+ unordered_list(['item 1', ['item 1.1', 'item1.2'], 'item 2']),
+ '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t\t<li>item1.2'\
+ '</li>\n\t</ul>\n\t</li>\n\t<li>item 2</li>')
self.assertEqual(
- unordered_list([u'item 1', [u'item 1.1', [u'item 1.1.1',
- [u'item 1.1.1.1']]]]),
- u'\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1\n\t\t<ul>\n\t\t\t<li>'\
- u'item 1.1.1\n\t\t\t<ul>\n\t\t\t\t<li>item 1.1.1.1</li>\n\t\t\t'\
- u'</ul>\n\t\t\t</li>\n\t\t</ul>\n\t\t</li>\n\t</ul>\n\t</li>')
+ unordered_list(['item 1', ['item 1.1', ['item 1.1.1',
+ ['item 1.1.1.1']]]]),
+ '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1\n\t\t<ul>\n\t\t\t<li>'\
+ 'item 1.1.1\n\t\t\t<ul>\n\t\t\t\t<li>item 1.1.1.1</li>\n\t\t\t'\
+ '</ul>\n\t\t\t</li>\n\t\t</ul>\n\t\t</li>\n\t</ul>\n\t</li>')
self.assertEqual(unordered_list(
['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]),
- u'\t<li>States\n\t<ul>\n\t\t<li>Kansas\n\t\t<ul>\n\t\t\t<li>'\
- u'Lawrence</li>\n\t\t\t<li>Topeka</li>\n\t\t</ul>\n\t\t</li>'\
- u'\n\t\t<li>Illinois</li>\n\t</ul>\n\t</li>')
+ '\t<li>States\n\t<ul>\n\t\t<li>Kansas\n\t\t<ul>\n\t\t\t<li>'\
+ 'Lawrence</li>\n\t\t\t<li>Topeka</li>\n\t\t</ul>\n\t\t</li>'\
+ '\n\t\t<li>Illinois</li>\n\t</ul>\n\t</li>')
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<li>ulitem-a</li>\n\t<li>ulitem-b</li>')
+ '\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>')
# Old format for unordered lists should still work
- self.assertEqual(unordered_list([u'item 1', []]), u'\t<li>item 1</li>')
+ self.assertEqual(unordered_list(['item 1', []]), '\t<li>item 1</li>')
- self.assertEqual(unordered_list([u'item 1', [[u'item 1.1', []]]]),
- u'\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t</ul>\n\t</li>')
+ self.assertEqual(unordered_list(['item 1', [['item 1.1', []]]]),
+ '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t</ul>\n\t</li>')
- self.assertEqual(unordered_list([u'item 1', [[u'item 1.1', []],
- [u'item 1.2', []]]]), u'\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1'\
- u'</li>\n\t\t<li>item 1.2</li>\n\t</ul>\n\t</li>')
+ self.assertEqual(unordered_list(['item 1', [['item 1.1', []],
+ ['item 1.2', []]]]), '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1'\
+ '</li>\n\t\t<li>item 1.2</li>\n\t</ul>\n\t</li>')
self.assertEqual(unordered_list(['States', [['Kansas', [['Lawrence',
- []], ['Topeka', []]]], ['Illinois', []]]]), u'\t<li>States\n\t'\
- u'<ul>\n\t\t<li>Kansas\n\t\t<ul>\n\t\t\t<li>Lawrence</li>'\
- u'\n\t\t\t<li>Topeka</li>\n\t\t</ul>\n\t\t</li>\n\t\t<li>'\
- u'Illinois</li>\n\t</ul>\n\t</li>')
+ []], ['Topeka', []]]], ['Illinois', []]]]), '\t<li>States\n\t'\
+ '<ul>\n\t\t<li>Kansas\n\t\t<ul>\n\t\t\t<li>Lawrence</li>'\
+ '\n\t\t\t<li>Topeka</li>\n\t\t</ul>\n\t\t</li>\n\t\t<li>'\
+ 'Illinois</li>\n\t</ul>\n\t</li>')
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'<p>123</p>')
- 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), '<p>123</p>')
+ 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 0ebccb5084..f3b6999377 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 868331e508..7d2a6fab34 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 3fcafef5de..f591900afe 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 87035d96d7..51b2207867 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 c8de8035f9..a7424639b4 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 ae6842d0a7..73b09cbcff 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 5a16f175a1..5d23a21dcd 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 c0b811bea2..405c566826 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 939055785a..18e6ddce6d 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 7153a3b0a6..f69b419483 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'<div class="error">%s</div>' % ''.join([u'<p>%s</p>' % e for e in self]))
+ if not self: return ''
+ return mark_safe('<div class="error">%s</div>' % ''.join(['<p>%s</p>' % 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 c873af7a8c..25b21123c4 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'), """<input type="text" name="name_0" value="some text" />
@@ -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):
</select>
<input type="text" name="field1_2_0" value="2007-04-25" id="id_field1_2_0" /><input type="text" name="field1_2_1" value="06:24:00" id="id_field1_2_1" /></td></tr>""")
- 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'<div class="errorlist">%s</div>' % ''.join([u'<div class="error">%s</div>' % force_unicode(e) for e in self])
+ if not self: return ''
+ return '<div class="errorlist">%s</div>' % ''.join(['<div class="error">%s</div>' % 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 4d442de382..ebeb19c8fc 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 16cf46fc29..7e1c8384a0 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']), '<input type="text" name="first_name" value="John" id="id_first_name" />')
self.assertHTMLEqual(str(p['last_name']), '<input type="text" name="last_name" value="Lennon" id="id_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), """<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" value="John" id="id_first_name" /></td></tr>
<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" value="Lennon" id="id_last_name" /></td></tr>
@@ -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'<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" value="John" id="id_first_name" /></td></tr>\n<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></td></tr>\n<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></td></tr>')
- self.assertHTMLEqual(p.as_ul(), u'<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" value="John" id="id_first_name" /></li>\n<li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></li>\n<li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></li>')
- self.assertHTMLEqual(p.as_p(), u'<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" value="John" id="id_first_name" /></p>\n<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></p>\n<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></p>')
+ p = Person({'first_name': 'John', 'last_name': '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111', 'birthday': '1940-10-9'})
+ self.assertHTMLEqual(p.as_table(), '<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" value="John" id="id_first_name" /></td></tr>\n<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></td></tr>\n<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></td></tr>')
+ self.assertHTMLEqual(p.as_ul(), '<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" value="John" id="id_first_name" /></li>\n<li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></li>\n<li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></li>')
+ self.assertHTMLEqual(p.as_p(), '<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" value="John" id="id_first_name" /></p>\n<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></p>\n<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></p>')
- 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'<ul class="errorlist"><li>first_name<ul class="errorlist"><li>This field is required.</li></ul></li><li>birthday<ul class="errorlist"><li>This field is required.</li></ul></li></ul>')
+ self.assertHTMLEqual(p.errors.as_ul(), '<ul class="errorlist"><li>first_name<ul class="errorlist"><li>This field is required.</li></ul></li><li>birthday<ul class="errorlist"><li>This field is required.</li></ul></li></ul>')
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'<ul class="errorlist"><li>This field is required.</li></ul>')
- 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(), '<ul class="errorlist"><li>This field is required.</li></ul>')
+ self.assertEqual(p['first_name'].errors.as_text(), '* This field is required.')
p = Person()
self.assertHTMLEqual(str(p['first_name']), '<input type="text" name="first_name" id="id_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'<textarea name="subject" rows="10" cols="40"></textarea>')
- self.assertHTMLEqual(f['message'].as_text(), u'<input type="text" name="message" />')
- self.assertHTMLEqual(f['message'].as_hidden(), u'<input type="hidden" name="message" />')
+ self.assertHTMLEqual(f['subject'].as_textarea(), '<textarea name="subject" rows="10" cols="40"></textarea>')
+ self.assertHTMLEqual(f['message'].as_text(), '<input type="text" name="message" />')
+ self.assertHTMLEqual(f['message'].as_hidden(), '<input type="hidden" name="message" />')
# 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'<input type="text" name="message" />')
+ self.assertHTMLEqual(f['message'].as_text(), '<input type="text" name="message" />')
f = ContactForm({'subject': 'Hello', 'message': 'I love you.'}, auto_id=False)
- self.assertHTMLEqual(f['subject'].as_textarea(), u'<textarea rows="10" cols="40" name="subject">Hello</textarea>')
- self.assertHTMLEqual(f['message'].as_text(), u'<input type="text" name="message" value="I love you." />')
- self.assertHTMLEqual(f['message'].as_hidden(), u'<input type="hidden" name="message" value="I love you." />')
+ self.assertHTMLEqual(f['subject'].as_textarea(), '<textarea rows="10" cols="40" name="subject">Hello</textarea>')
+ self.assertHTMLEqual(f['message'].as_text(), '<input type="text" name="message" value="I love you." />')
+ self.assertHTMLEqual(f['message'].as_hidden(), '<input type="hidden" name="message" value="I love you." />')
def test_forms_with_choices(self):
# For a form with a <select>, use ChoiceField:
@@ -454,7 +457,7 @@ class FormsTestCase(TestCase):
name = CharField()
f = BeatleForm(auto_id=False)
- self.assertHTMLEqual('\n'.join([str(bf) for bf in f['name']]), u'<input type="text" name="name" />')
+ self.assertHTMLEqual('\n'.join([str(bf) for bf in f['name']]), '<input type="text" name="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(), """<tr><th>Username:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="username" maxlength="10" /></td></tr>
<tr><th>Password1:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="password" name="password1" /></td></tr>
<tr><th>Password2:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="password" name="password2" /></td></tr>""")
- 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(), """<tr><td colspan="2"><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></td></tr>
<tr><th>Username:</th><td><input type="text" name="username" value="adrian" maxlength="10" /></td></tr>
<tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr>
@@ -686,9 +689,9 @@ class FormsTestCase(TestCase):
<li>Password2: <input type="password" name="password2" /></li>""")
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'<li>\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111: <input type="text" name="username" maxlength="10" /></li>\n<li>\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111: <input type="password" name="password" /></li>')
+ self.assertHTMLEqual(p.as_ul(), '<li>\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111: <input type="text" name="username" maxlength="10" /></li>\n<li>\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111: <input type="password" name="password" /></li>')
# 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(), """<li>Favorite color? <input type="text" name="color" /></li>
<li>Favorite animal <input type="text" name="animal" /></li>""")
- f = FavoriteForm(auto_id=False, label_suffix=u'\u2192')
- self.assertHTMLEqual(f.as_ul(), u'<li>Favorite color? <input type="text" name="color" /></li>\n<li>Favorite animal\u2192 <input type="text" name="animal" /></li>')
+ f = FavoriteForm(auto_id=False, label_suffix='\u2192')
+ self.assertHTMLEqual(f.as_ul(), '<li>Favorite color? <input type="text" name="color" /></li>\n<li>Favorite animal\u2192 <input type="text" name="animal" /></li>')
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(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
- p = UserRegistration({'username': u''}, auto_id=False)
+ p = UserRegistration({'username': ''}, auto_id=False)
self.assertHTMLEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
- p = UserRegistration({'username': u'foo'}, auto_id=False)
+ p = UserRegistration({'username': 'foo'}, auto_id=False)
self.assertHTMLEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
@@ -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(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
- p = UserRegistration({'username': u''}, initial={'username': 'django'}, auto_id=False)
+ p = UserRegistration({'username': ''}, initial={'username': 'django'}, auto_id=False)
self.assertHTMLEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
- 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(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
@@ -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):
<option value="b">bar</option>
<option value="w">whiz</option>
</select></li>""")
- 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(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>Options: <select multiple="multiple" name="options">
@@ -1164,7 +1167,7 @@ class FormsTestCase(TestCase):
<option value="b">bar</option>
<option value="w">whiz</option>
</select></li>""")
- 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(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>
<li>Options: <select multiple="multiple" name="options">
@@ -1177,7 +1180,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': initial_django, 'options': initial_options})
- 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(),
@@ -1234,7 +1237,7 @@ class FormsTestCase(TestCase):
<tr><th>Password:</th><td><input type="password" name="password" /><br /><span class="helptext">Choose wisely.</span></td></tr>""")
# 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(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /> <span class="helptext">Choose wisely.</span></li>""")
@@ -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'<li>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111</span></li>')
+ self.assertHTMLEqual(p.as_ul(), '<li>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111</span></li>')
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(), """<li><label for="id_person1-first_name">First name:</label> <input type="text" name="person1-first_name" value="John" id="id_person1-first_name" /></li>
@@ -1325,22 +1328,22 @@ class FormsTestCase(TestCase):
self.assertHTMLEqual(str(p['birthday']), '<input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-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):
<li><label for="id_foo-prefix-last_name">Last name:</label> <input type="text" name="foo-prefix-last_name" id="id_foo-prefix-last_name" /></li>
<li><label for="id_foo-prefix-birthday">Birthday:</label> <input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday" /></li>""")
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']), """<select name="is_cool">
<option value="1" selected="selected">Unknown</option>
<option value="2">Yes</option>
<option value="3">No</option>
</select>""")
- 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']), """<select name="is_cool">
<option value="1" selected="selected">Unknown</option>
<option value="2">Yes</option>
<option value="3">No</option>
</select>""")
- 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']), """<select name="is_cool">
<option value="1">Unknown</option>
<option value="2" selected="selected">Yes</option>
<option value="3">No</option>
</select>""")
- 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']), """<select name="is_cool">
<option value="1">Unknown</option>
<option value="2">Yes</option>
<option value="3" selected="selected">No</option>
</select>""")
- 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']), """<select name="is_cool">
<option value="1">Unknown</option>
<option value="2" selected="selected">Yes</option>
<option value="3">No</option>
</select>""")
- 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']), """<select name="is_cool">
<option value="1">Unknown</option>
<option value="2">Yes</option>
@@ -1473,7 +1476,7 @@ class FormsTestCase(TestCase):
self.assertHTMLEqual(f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>')
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(), '<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>')
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):
<input type="submit" />
</form>""")
# 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):
<p>Password2: <input type="password" name="password2" /></p>
<input type="submit" />
</form>""")
- 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 <label> tag.
@@ -1674,7 +1677,7 @@ class FormsTestCase(TestCase):
data = {'artist': '', 'song': ''}
form = SongForm(data, empty_permitted=False)
self.assertFalse(form.is_valid())
- self.assertEqual(form.errors, {'name': [u'This field is required.'], 'artist': [u'This field is required.']})
+ self.assertEqual(form.errors, {'name': ['This field is required.'], 'artist': ['This field is required.']})
try:
form.cleaned_data
self.fail('Attempts to access cleaned_data when validation fails should fail.')
@@ -1692,7 +1695,7 @@ class FormsTestCase(TestCase):
data = {'artist': 'The Doors', 'song': ''}
form = SongForm(data, empty_permitted=False)
self.assertFalse(form.is_valid())
- self.assertEqual(form.errors, {'name': [u'This field is required.']})
+ self.assertEqual(form.errors, {'name': ['This field is required.']})
try:
form.cleaned_data
self.fail('Attempts to access cleaned_data when validation fails should fail.')
@@ -1777,7 +1780,7 @@ class FormsTestCase(TestCase):
happened_at = SplitDateTimeField(widget=widgets.SplitHiddenDateTimeWidget)
form = EventForm()
- self.assertHTMLEqual(form.as_ul(), u'<input type="hidden" name="happened_at_0" id="id_happened_at_0" /><input type="hidden" name="happened_at_1" id="id_happened_at_1" />')
+ self.assertHTMLEqual(form.as_ul(), '<input type="hidden" name="happened_at_0" id="id_happened_at_0" /><input type="hidden" name="happened_at_1" id="id_happened_at_1" />')
def test_multivalue_field_validation(self):
def bad_names(value):
@@ -1799,11 +1802,11 @@ class FormsTestCase(TestCase):
form = NameForm(data={'name' : ['bad', 'value']})
form.full_clean()
self.assertFalse(form.is_valid())
- self.assertEqual(form.errors, {'name': [u'bad value not allowed']})
+ self.assertEqual(form.errors, {'name': ['bad value not allowed']})
form = NameForm(data={'name' : ['should be overly', 'long for the field names']})
self.assertFalse(form.is_valid())
- self.assertEqual(form.errors, {'name': [u'Ensure this value has at most 10 characters (it has 16).',
- u'Ensure this value has at most 10 characters (it has 24).']})
+ self.assertEqual(form.errors, {'name': ['Ensure this value has at most 10 characters (it has 16).',
+ 'Ensure this value has at most 10 characters (it has 24).']})
form = NameForm(data={'name' : ['fname', 'lname']})
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data, {'name' : 'fname lname'})
diff --git a/tests/regressiontests/forms/tests/formsets.py b/tests/regressiontests/forms/tests/formsets.py
index 05ef978c45..3decd1f085 100644
--- a/tests/regressiontests/forms/tests/formsets.py
+++ b/tests/regressiontests/forms/tests/formsets.py
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
from django.forms import Form, CharField, IntegerField, ValidationError, DateField
from django.forms.formsets import formset_factory, BaseFormSet
from django.test import TestCase
@@ -71,7 +73,7 @@ class FormsFormsetTestCase(TestCase):
formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
self.assertTrue(formset.is_valid())
- self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'choice': u'Calexico'}])
+ self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'choice': 'Calexico'}])
# If a FormSet was not passed any data, its is_valid and has_changed
# methods should return False.
@@ -93,7 +95,7 @@ class FormsFormsetTestCase(TestCase):
formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
self.assertFalse(formset.is_valid())
- self.assertEqual(formset.errors, [{'votes': [u'This field is required.']}])
+ self.assertEqual(formset.errors, [{'votes': ['This field is required.']}])
def test_formset_has_changed(self):
# FormSet instances has_changed method will be True if any data is
@@ -125,7 +127,7 @@ class FormsFormsetTestCase(TestCase):
# argument to the constructor. ``initial`` should be a list of dicts. By default,
# an extra blank form is included.
- initial = [{'choice': u'Calexico', 'votes': 100}]
+ initial = [{'choice': 'Calexico', 'votes': 100}]
formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')
form_output = []
@@ -151,7 +153,7 @@ class FormsFormsetTestCase(TestCase):
formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
self.assertTrue(formset.is_valid())
- self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'choice': u'Calexico'}, {}])
+ self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'choice': 'Calexico'}, {}])
def test_second_form_partially_filled(self):
# But the second form was blank! Shouldn't we get some errors? No. If we display
@@ -172,7 +174,7 @@ class FormsFormsetTestCase(TestCase):
formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
self.assertFalse(formset.is_valid())
- self.assertEqual(formset.errors, [{}, {'votes': [u'This field is required.']}])
+ self.assertEqual(formset.errors, [{}, {'votes': ['This field is required.']}])
def test_delete_prefilled_data(self):
# If we delete data that was pre-filled, we should get an error. Simply removing
@@ -191,7 +193,7 @@ class FormsFormsetTestCase(TestCase):
formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
self.assertFalse(formset.is_valid())
- self.assertEqual(formset.errors, [{'votes': [u'This field is required.'], 'choice': [u'This field is required.']}, {}])
+ self.assertEqual(formset.errors, [{'votes': ['This field is required.'], 'choice': ['This field is required.']}, {}])
def test_displaying_more_than_one_blank_form(self):
# Displaying more than 1 blank form ###########################################
@@ -250,7 +252,7 @@ class FormsFormsetTestCase(TestCase):
ChoiceFormSet = formset_factory(Choice, extra=3)
formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
self.assertTrue(formset.is_valid())
- self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'choice': u'Calexico'}, {}, {}])
+ self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'choice': 'Calexico'}, {}, {}])
def test_second_form_partially_filled_2(self):
# And once again, if we try to partially complete a form, validation will fail.
@@ -270,7 +272,7 @@ class FormsFormsetTestCase(TestCase):
ChoiceFormSet = formset_factory(Choice, extra=3)
formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
self.assertFalse(formset.is_valid())
- self.assertEqual(formset.errors, [{}, {'votes': [u'This field is required.']}, {}])
+ self.assertEqual(formset.errors, [{}, {'votes': ['This field is required.']}, {}])
def test_more_initial_data(self):
# The extra argument also works when the formset is pre-filled with initial
@@ -288,7 +290,7 @@ class FormsFormsetTestCase(TestCase):
'choices-2-votes': '',
}
- initial = [{'choice': u'Calexico', 'votes': 100}]
+ initial = [{'choice': 'Calexico', 'votes': 100}]
ChoiceFormSet = formset_factory(Choice, extra=3)
formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')
form_output = []
@@ -319,7 +321,7 @@ class FormsFormsetTestCase(TestCase):
ChoiceFormSet = formset_factory(Choice, can_delete=True)
- initial = [{'choice': u'Calexico', 'votes': 100}, {'choice': u'Fergie', 'votes': 900}]
+ initial = [{'choice': 'Calexico', 'votes': 100}, {'choice': 'Fergie', 'votes': 900}]
formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')
form_output = []
@@ -356,8 +358,8 @@ class FormsFormsetTestCase(TestCase):
formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
self.assertTrue(formset.is_valid())
- self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'DELETE': False, 'choice': u'Calexico'}, {'votes': 900, 'DELETE': True, 'choice': u'Fergie'}, {}])
- self.assertEqual([form.cleaned_data for form in formset.deleted_forms], [{'votes': 900, 'DELETE': True, 'choice': u'Fergie'}])
+ self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'DELETE': False, 'choice': 'Calexico'}, {'votes': 900, 'DELETE': True, 'choice': 'Fergie'}, {}])
+ self.assertEqual([form.cleaned_data for form in formset.deleted_forms], [{'votes': 900, 'DELETE': True, 'choice': 'Fergie'}])
# If we fill a form with something and then we check the can_delete checkbox for
# that form, that form's errors should not make the entire formset invalid since
@@ -397,7 +399,7 @@ class FormsFormsetTestCase(TestCase):
can_delete=True)
p = PeopleForm(
- {'form-0-name': u'', 'form-0-DELETE': u'on', # no name!
+ {'form-0-name': '', 'form-0-DELETE': 'on', # no name!
'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1,
'form-MAX_NUM_FORMS': 1})
@@ -416,7 +418,7 @@ class FormsFormsetTestCase(TestCase):
ChoiceFormSet = formset_factory(Choice, can_order=True)
- initial = [{'choice': u'Calexico', 'votes': 100}, {'choice': u'Fergie', 'votes': 900}]
+ initial = [{'choice': 'Calexico', 'votes': 100}, {'choice': 'Fergie', 'votes': 900}]
formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')
form_output = []
@@ -456,9 +458,9 @@ class FormsFormsetTestCase(TestCase):
form_output.append(form.cleaned_data)
self.assertEqual(form_output, [
- {'votes': 500, 'ORDER': 0, 'choice': u'The Decemberists'},
- {'votes': 100, 'ORDER': 1, 'choice': u'Calexico'},
- {'votes': 900, 'ORDER': 2, 'choice': u'Fergie'},
+ {'votes': 500, 'ORDER': 0, 'choice': 'The Decemberists'},
+ {'votes': 100, 'ORDER': 1, 'choice': 'Calexico'},
+ {'votes': 900, 'ORDER': 2, 'choice': 'Fergie'},
])
def test_empty_ordered_fields(self):
@@ -492,10 +494,10 @@ class FormsFormsetTestCase(TestCase):
form_output.append(form.cleaned_data)
self.assertEqual(form_output, [
- {'votes': 100, 'ORDER': 1, 'choice': u'Calexico'},
- {'votes': 900, 'ORDER': 2, 'choice': u'Fergie'},
- {'votes': 500, 'ORDER': None, 'choice': u'The Decemberists'},
- {'votes': 50, 'ORDER': None, 'choice': u'Basia Bulat'},
+ {'votes': 100, 'ORDER': 1, 'choice': 'Calexico'},
+ {'votes': 900, 'ORDER': 2, 'choice': 'Fergie'},
+ {'votes': 500, 'ORDER': None, 'choice': 'The Decemberists'},
+ {'votes': 50, 'ORDER': None, 'choice': 'Basia Bulat'},
])
def test_ordering_blank_fieldsets(self):
@@ -524,9 +526,9 @@ class FormsFormsetTestCase(TestCase):
ChoiceFormSet = formset_factory(Choice, can_order=True, can_delete=True)
initial = [
- {'choice': u'Calexico', 'votes': 100},
- {'choice': u'Fergie', 'votes': 900},
- {'choice': u'The Decemberists', 'votes': 500},
+ {'choice': 'Calexico', 'votes': 100},
+ {'choice': 'Fergie', 'votes': 900},
+ {'choice': 'The Decemberists', 'votes': 500},
]
formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')
form_output = []
@@ -583,10 +585,10 @@ class FormsFormsetTestCase(TestCase):
form_output.append(form.cleaned_data)
self.assertEqual(form_output, [
- {'votes': 500, 'DELETE': False, 'ORDER': 0, 'choice': u'The Decemberists'},
- {'votes': 100, 'DELETE': False, 'ORDER': 1, 'choice': u'Calexico'},
+ {'votes': 500, 'DELETE': False, 'ORDER': 0, 'choice': 'The Decemberists'},
+ {'votes': 100, 'DELETE': False, 'ORDER': 1, 'choice': 'Calexico'},
])
- self.assertEqual([form.cleaned_data for form in formset.deleted_forms], [{'votes': 900, 'DELETE': True, 'ORDER': 2, 'choice': u'Fergie'}])
+ self.assertEqual([form.cleaned_data for form in formset.deleted_forms], [{'votes': 900, 'DELETE': True, 'ORDER': 2, 'choice': 'Fergie'}])
def test_invalid_deleted_form_with_ordering(self):
# Should be able to get ordered forms from a valid formset even if a
@@ -598,8 +600,8 @@ class FormsFormsetTestCase(TestCase):
PeopleForm = formset_factory(form=Person, can_delete=True, can_order=True)
p = PeopleForm({
- 'form-0-name': u'',
- 'form-0-DELETE': u'on', # no name!
+ 'form-0-name': '',
+ 'form-0-DELETE': 'on', # no name!
'form-TOTAL_FORMS': 1,
'form-INITIAL_FORMS': 1,
'form-MAX_NUM_FORMS': 1
@@ -797,7 +799,7 @@ class FormsFormsetTestCase(TestCase):
formset = FavoriteDrinksFormSet(data, prefix='drinks')
self.assertFalse(formset.is_valid())
- self.assertEqual(formset.non_form_errors(), [u'You may only specify a drink once.'])
+ self.assertEqual(formset.non_form_errors(), ['You may only specify a drink once.'])
def test_formset_iteration(self):
# Regression tests for #16455 -- formset instances are iterable
@@ -892,8 +894,8 @@ class TestIsBoundBehavior(TestCase):
def test_with_management_data_attrs_work_fine(self):
data = {
- 'form-TOTAL_FORMS': u'1',
- 'form-INITIAL_FORMS': u'0',
+ 'form-TOTAL_FORMS': '1',
+ 'form-INITIAL_FORMS': '0',
}
formset = ArticleFormSet(data)
self.assertEqual(0, formset.initial_form_count())
@@ -907,23 +909,23 @@ class TestIsBoundBehavior(TestCase):
def test_form_errors_are_cought_by_formset(self):
data = {
- 'form-TOTAL_FORMS': u'2',
- 'form-INITIAL_FORMS': u'0',
- 'form-0-title': u'Test',
- 'form-0-pub_date': u'1904-06-16',
- 'form-1-title': u'Test',
- 'form-1-pub_date': u'', # <-- this date is missing but required
+ 'form-TOTAL_FORMS': '2',
+ 'form-INITIAL_FORMS': '0',
+ 'form-0-title': 'Test',
+ 'form-0-pub_date': '1904-06-16',
+ 'form-1-title': 'Test',
+ 'form-1-pub_date': '', # <-- this date is missing but required
}
formset = ArticleFormSet(data)
self.assertFalse(formset.is_valid())
- self.assertEqual([{}, {'pub_date': [u'This field is required.']}], formset.errors)
+ self.assertEqual([{}, {'pub_date': ['This field is required.']}], formset.errors)
def test_empty_forms_are_unbound(self):
data = {
- 'form-TOTAL_FORMS': u'1',
- 'form-INITIAL_FORMS': u'0',
- 'form-0-title': u'Test',
- 'form-0-pub_date': u'1904-06-16',
+ 'form-TOTAL_FORMS': '1',
+ 'form-INITIAL_FORMS': '0',
+ 'form-0-title': 'Test',
+ 'form-0-pub_date': '1904-06-16',
}
unbound_formset = ArticleFormSet()
bound_formset = ArticleFormSet(data)
diff --git a/tests/regressiontests/forms/tests/models.py b/tests/regressiontests/forms/tests/models.py
index 7f569651c7..5bea49b840 100644
--- a/tests/regressiontests/forms/tests/models.py
+++ b/tests/regressiontests/forms/tests/models.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import datetime
@@ -106,11 +106,11 @@ class ModelFormCallableModelDefault(TestCase):
class FormsModelTestCase(TestCase):
def test_unicode_filename(self):
# FileModel with unicode filename and data #########################
- 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.assertTrue(f.is_valid())
self.assertTrue('file1' in f.cleaned_data)
m = FileModel.objects.create(file=f.cleaned_data['file1'])
- self.assertEqual(m.file.name, u'tests/\u6211\u96bb\u6c23\u588a\u8239\u88dd\u6eff\u6652\u9c54.txt')
+ self.assertEqual(m.file.name, 'tests/\u6211\u96bb\u6c23\u588a\u8239\u88dd\u6eff\u6652\u9c54.txt')
m.delete()
def test_boundary_conditions(self):
@@ -134,7 +134,7 @@ class FormsModelTestCase(TestCase):
class Meta:
model = Defaults
- self.assertEqual(DefaultsForm().fields['name'].initial, u'class default value')
+ self.assertEqual(DefaultsForm().fields['name'].initial, 'class default value')
self.assertEqual(DefaultsForm().fields['def_date'].initial, datetime.date(1980, 1, 1))
self.assertEqual(DefaultsForm().fields['value'].initial, 42)
r1 = DefaultsForm()['callable_default'].as_widget()
@@ -143,9 +143,9 @@ class FormsModelTestCase(TestCase):
# In a ModelForm that is passed an instance, the initial values come from the
# instance's values, not the model's defaults.
- foo_instance = Defaults(name=u'instance value', def_date=datetime.date(1969, 4, 4), value=12)
+ foo_instance = Defaults(name='instance value', def_date=datetime.date(1969, 4, 4), value=12)
instance_form = DefaultsForm(instance=foo_instance)
- self.assertEqual(instance_form.initial['name'], u'instance value')
+ self.assertEqual(instance_form.initial['name'], 'instance value')
self.assertEqual(instance_form.initial['def_date'], datetime.date(1969, 4, 4))
self.assertEqual(instance_form.initial['value'], 12)
@@ -158,11 +158,11 @@ class FormsModelTestCase(TestCase):
model = Defaults
exclude = ['name', 'callable_default']
- f = ExcludingForm({'name': u'Hello', 'value': 99, 'def_date': datetime.date(1999, 3, 2)})
+ f = ExcludingForm({'name': 'Hello', 'value': 99, 'def_date': datetime.date(1999, 3, 2)})
self.assertTrue(f.is_valid())
- self.assertEqual(f.cleaned_data['name'], u'Hello')
+ self.assertEqual(f.cleaned_data['name'], 'Hello')
obj = f.save()
- self.assertEqual(obj.name, u'class default value')
+ self.assertEqual(obj.name, 'class default value')
self.assertEqual(obj.value, 99)
self.assertEqual(obj.def_date, datetime.date(1999, 3, 2))
diff --git a/tests/regressiontests/forms/tests/regressions.py b/tests/regressiontests/forms/tests/regressions.py
index 20c11f99a8..45f51eef2f 100644
--- a/tests/regressiontests/forms/tests/regressions.py
+++ b/tests/regressiontests/forms/tests/regressions.py
@@ -1,4 +1,8 @@
# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from warnings import catch_warnings
+
from django.forms import *
from django.test import TestCase
from django.utils.translation import ugettext_lazy, override
@@ -15,7 +19,7 @@ class FormsRegressionsTestCase(TestCase):
f1 = CharField(max_length=10, widget=TextInput(attrs=extra_attrs))
f2 = CharField(widget=TextInput(attrs=extra_attrs))
- self.assertHTMLEqual(TestForm(auto_id=False).as_p(), u'<p>F1: <input type="text" class="special" name="f1" maxlength="10" /></p>\n<p>F2: <input type="text" class="special" name="f2" /></p>')
+ self.assertHTMLEqual(TestForm(auto_id=False).as_p(), '<p>F1: <input type="text" class="special" name="f1" maxlength="10" /></p>\n<p>F2: <input type="text" class="special" name="f2" /></p>')
def test_regression_3600(self):
# Tests for form i18n #
@@ -31,7 +35,7 @@ class FormsRegressionsTestCase(TestCase):
with override('de'):
self.assertHTMLEqual(f.as_p(), '<p><label for="id_username">Benutzername:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>')
with override('pl', deactivate=True):
- self.assertHTMLEqual(f.as_p(), u'<p><label for="id_username">Nazwa u\u017cytkownika:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>')
+ self.assertHTMLEqual(f.as_p(), '<p><label for="id_username">Nazwa u\u017cytkownika:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>')
def test_regression_5216(self):
# There was some problems with form translations in #5216
@@ -44,26 +48,28 @@ class FormsRegressionsTestCase(TestCase):
self.assertHTMLEqual(f['field_2'].label_tag(), '<label for="field_2_id">field_2</label>')
# Unicode decoding problems...
- GENDERS = ((u'\xc5', u'En tied\xe4'), (u'\xf8', u'Mies'), (u'\xdf', u'Nainen'))
+ GENDERS = (('\xc5', 'En tied\xe4'), ('\xf8', 'Mies'), ('\xdf', 'Nainen'))
class SomeForm(Form):
- somechoice = ChoiceField(choices=GENDERS, widget=RadioSelect(), label=u'\xc5\xf8\xdf')
+ somechoice = ChoiceField(choices=GENDERS, widget=RadioSelect(), label='\xc5\xf8\xdf')
f = SomeForm()
- self.assertHTMLEqual(f.as_p(), u'<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label> <ul>\n<li><label for="id_somechoice_0"><input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> En tied\xe4</label></li>\n<li><label for="id_somechoice_1"><input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> Mies</label></li>\n<li><label for="id_somechoice_2"><input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> Nainen</label></li>\n</ul></p>')
+ self.assertHTMLEqual(f.as_p(), '<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label> <ul>\n<li><label for="id_somechoice_0"><input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> En tied\xe4</label></li>\n<li><label for="id_somechoice_1"><input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> Mies</label></li>\n<li><label for="id_somechoice_2"><input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> Nainen</label></li>\n</ul></p>')
# Testing choice validation with UTF-8 bytestrings as input (these are the
# Russian abbreviations "мес." and "шт.".
UNITS = ((b'\xd0\xbc\xd0\xb5\xd1\x81.', b'\xd0\xbc\xd0\xb5\xd1\x81.'),
(b'\xd1\x88\xd1\x82.', b'\xd1\x88\xd1\x82.'))
f = ChoiceField(choices=UNITS)
- self.assertEqual(f.clean(u'\u0448\u0442.'), u'\u0448\u0442.')
- self.assertEqual(f.clean(b'\xd1\x88\xd1\x82.'), u'\u0448\u0442.')
+ self.assertEqual(f.clean('\u0448\u0442.'), '\u0448\u0442.')
+ with catch_warnings(record=True):
+ # Ignore UnicodeWarning
+ self.assertEqual(f.clean(b'\xd1\x88\xd1\x82.'), '\u0448\u0442.')
# Translated error messages used to be buggy.
with override('ru'):
f = SomeForm({})
- self.assertHTMLEqual(f.as_p(), u'<ul class="errorlist"><li>\u041e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0435 \u043f\u043e\u043b\u0435.</li></ul>\n<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label> <ul>\n<li><label for="id_somechoice_0"><input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> En tied\xe4</label></li>\n<li><label for="id_somechoice_1"><input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> Mies</label></li>\n<li><label for="id_somechoice_2"><input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> Nainen</label></li>\n</ul></p>')
+ self.assertHTMLEqual(f.as_p(), '<ul class="errorlist"><li>\u041e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0435 \u043f\u043e\u043b\u0435.</li></ul>\n<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label> <ul>\n<li><label for="id_somechoice_0"><input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> En tied\xe4</label></li>\n<li><label for="id_somechoice_1"><input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> Mies</label></li>\n<li><label for="id_somechoice_2"><input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> Nainen</label></li>\n</ul></p>')
# Deep copying translated text shouldn't raise an error)
from django.utils.translation import gettext_lazy
@@ -81,15 +87,15 @@ class FormsRegressionsTestCase(TestCase):
f = DataForm({'data': 'xyzzy'})
self.assertTrue(f.is_valid())
- self.assertEqual(f.cleaned_data, {'data': u'xyzzy'})
+ self.assertEqual(f.cleaned_data, {'data': 'xyzzy'})
# A form with *only* hidden fields that has errors is going to be very unusual.
class HiddenForm(Form):
data = IntegerField(widget=HiddenInput)
f = HiddenForm({})
- self.assertHTMLEqual(f.as_p(), u'<ul class="errorlist"><li>(Hidden field data) This field is required.</li></ul>\n<p> <input type="hidden" name="data" id="id_data" /></p>')
- self.assertHTMLEqual(f.as_table(), u'<tr><td colspan="2"><ul class="errorlist"><li>(Hidden field data) This field is required.</li></ul><input type="hidden" name="data" id="id_data" /></td></tr>')
+ self.assertHTMLEqual(f.as_p(), '<ul class="errorlist"><li>(Hidden field data) This field is required.</li></ul>\n<p> <input type="hidden" name="data" id="id_data" /></p>')
+ self.assertHTMLEqual(f.as_table(), '<tr><td colspan="2"><ul class="errorlist"><li>(Hidden field data) This field is required.</li></ul><input type="hidden" name="data" id="id_data" /></td></tr>')
def test_xss_error_messages(self):
###################################################
@@ -107,13 +113,13 @@ class FormsRegressionsTestCase(TestCase):
field = ChoiceField(choices=[('one', 'One')])
f = SomeForm({'field': '<script>'})
- self.assertHTMLEqual(t.render(Context({'form': f})), u'<ul class="errorlist"><li>field<ul class="errorlist"><li>Select a valid choice. &lt;script&gt; is not one of the available choices.</li></ul></li></ul>')
+ self.assertHTMLEqual(t.render(Context({'form': f})), '<ul class="errorlist"><li>field<ul class="errorlist"><li>Select a valid choice. &lt;script&gt; is not one of the available choices.</li></ul></li></ul>')
class SomeForm(Form):
field = MultipleChoiceField(choices=[('one', 'One')])
f = SomeForm({'field': ['<script>']})
- self.assertHTMLEqual(t.render(Context({'form': f})), u'<ul class="errorlist"><li>field<ul class="errorlist"><li>Select a valid choice. &lt;script&gt; is not one of the available choices.</li></ul></li></ul>')
+ self.assertHTMLEqual(t.render(Context({'form': f})), '<ul class="errorlist"><li>field<ul class="errorlist"><li>Select a valid choice. &lt;script&gt; is not one of the available choices.</li></ul></li></ul>')
from regressiontests.forms.models import ChoiceModel
@@ -121,7 +127,7 @@ class FormsRegressionsTestCase(TestCase):
field = ModelMultipleChoiceField(ChoiceModel.objects.all())
f = SomeForm({'field': ['<script>']})
- self.assertHTMLEqual(t.render(Context({'form': f})), u'<ul class="errorlist"><li>field<ul class="errorlist"><li>&quot;&lt;script&gt;&quot; is not a valid value for a primary key.</li></ul></li></ul>')
+ self.assertHTMLEqual(t.render(Context({'form': f})), '<ul class="errorlist"><li>field<ul class="errorlist"><li>&quot;&lt;script&gt;&quot; is not a valid value for a primary key.</li></ul></li></ul>')
def test_regression_14234(self):
"""
diff --git a/tests/regressiontests/forms/tests/util.py b/tests/regressiontests/forms/tests/util.py
index dddb8c7e56..280049c97b 100644
--- a/tests/regressiontests/forms/tests/util.py
+++ b/tests/regressiontests/forms/tests/util.py
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
from django.core.exceptions import ValidationError
from django.forms.util import flatatt, ErrorDict, ErrorList
from django.test import TestCase
@@ -14,9 +16,9 @@ class FormsUtilTestCase(TestCase):
# flatatt #
###########
- self.assertEqual(flatatt({'id': "header"}), u' id="header"')
- self.assertEqual(flatatt({'class': "news", 'title': "Read this"}), u' class="news" title="Read this"')
- self.assertEqual(flatatt({}), u'')
+ self.assertEqual(flatatt({'id': "header"}), ' id="header"')
+ self.assertEqual(flatatt({'class': "news", 'title': "Read this"}), ' class="news" title="Read this"')
+ self.assertEqual(flatatt({}), '')
def test_validation_error(self):
###################
@@ -28,8 +30,8 @@ class FormsUtilTestCase(TestCase):
'<ul class="errorlist"><li>There was an error.</li></ul>')
# Can take a unicode string.
- self.assertHTMLEqual(unicode(ErrorList(ValidationError(u"Not \u03C0.").messages)),
- u'<ul class="errorlist"><li>Not π.</li></ul>')
+ self.assertHTMLEqual(unicode(ErrorList(ValidationError("Not \u03C0.").messages)),
+ '<ul class="errorlist"><li>Not π.</li></ul>')
# Can take a lazy string.
self.assertHTMLEqual(str(ErrorList(ValidationError(ugettext_lazy("Error.")).messages)),
@@ -40,11 +42,11 @@ class FormsUtilTestCase(TestCase):
'<ul class="errorlist"><li>Error one.</li><li>Error two.</li></ul>')
# Can take a mixture in a list.
- self.assertHTMLEqual(str(ErrorList(ValidationError(["First error.", u"Not \u03C0.", ugettext_lazy("Error.")]).messages)),
+ self.assertHTMLEqual(str(ErrorList(ValidationError(["First error.", "Not \u03C0.", ugettext_lazy("Error.")]).messages)),
'<ul class="errorlist"><li>First error.</li><li>Not π.</li><li>Error.</li></ul>')
class VeryBadError:
- def __unicode__(self): return u"A very bad error."
+ def __unicode__(self): return "A very bad error."
# Can take a non-string.
self.assertHTMLEqual(str(ErrorList(ValidationError(VeryBadError()).messages)),
diff --git a/tests/regressiontests/forms/tests/widgets.py b/tests/regressiontests/forms/tests/widgets.py
index 8630b45666..d5f6334fe9 100644
--- a/tests/regressiontests/forms/tests/widgets.py
+++ b/tests/regressiontests/forms/tests/widgets.py
@@ -1,4 +1,5 @@
# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
import copy
import datetime
@@ -19,127 +20,127 @@ class FormsWidgetTestCase(TestCase):
# validation.
def test_textinput(self):
w = TextInput()
- self.assertHTMLEqual(w.render('email', ''), u'<input type="text" name="email" />')
- self.assertHTMLEqual(w.render('email', None), u'<input type="text" name="email" />')
- self.assertHTMLEqual(w.render('email', 'test@example.com'), u'<input type="text" name="email" value="test@example.com" />')
- self.assertHTMLEqual(w.render('email', 'some "quoted" & ampersanded value'), u'<input type="text" name="email" value="some &quot;quoted&quot; &amp; ampersanded value" />')
- self.assertHTMLEqual(w.render('email', 'test@example.com', attrs={'class': 'fun'}), u'<input type="text" name="email" value="test@example.com" class="fun" />')
+ self.assertHTMLEqual(w.render('email', ''), '<input type="text" name="email" />')
+ self.assertHTMLEqual(w.render('email', None), '<input type="text" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'test@example.com'), '<input type="text" name="email" value="test@example.com" />')
+ self.assertHTMLEqual(w.render('email', 'some "quoted" & ampersanded value'), '<input type="text" name="email" value="some &quot;quoted&quot; &amp; ampersanded value" />')
+ self.assertHTMLEqual(w.render('email', 'test@example.com', attrs={'class': 'fun'}), '<input type="text" name="email" value="test@example.com" class="fun" />')
- self.assertHTMLEqual(w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), u'<input type="text" name="email" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" class="fun" />')
+ self.assertHTMLEqual(w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), '<input type="text" name="email" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" class="fun" />')
# You can also pass 'attrs' to the constructor:
w = TextInput(attrs={'class': 'fun'})
- self.assertHTMLEqual(w.render('email', ''), u'<input type="text" class="fun" name="email" />')
- self.assertHTMLEqual(w.render('email', 'foo@example.com'), u'<input type="text" class="fun" value="foo@example.com" name="email" />')
+ self.assertHTMLEqual(w.render('email', ''), '<input type="text" class="fun" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'foo@example.com'), '<input type="text" class="fun" value="foo@example.com" name="email" />')
# 'attrs' passed to render() get precedence over those passed to the constructor:
w = TextInput(attrs={'class': 'pretty'})
- self.assertHTMLEqual(w.render('email', '', attrs={'class': 'special'}), u'<input type="text" class="special" name="email" />')
+ self.assertHTMLEqual(w.render('email', '', attrs={'class': 'special'}), '<input type="text" class="special" name="email" />')
# 'attrs' can be safe-strings if needed)
w = TextInput(attrs={'onBlur': mark_safe("function('foo')")})
- self.assertHTMLEqual(w.render('email', ''), u'<input onBlur="function(\'foo\')" type="text" name="email" />')
+ self.assertHTMLEqual(w.render('email', ''), '<input onBlur="function(\'foo\')" type="text" name="email" />')
def test_passwordinput(self):
w = PasswordInput()
- self.assertHTMLEqual(w.render('email', ''), u'<input type="password" name="email" />')
- self.assertHTMLEqual(w.render('email', None), u'<input type="password" name="email" />')
- self.assertHTMLEqual(w.render('email', 'secret'), u'<input type="password" name="email" />')
+ self.assertHTMLEqual(w.render('email', ''), '<input type="password" name="email" />')
+ self.assertHTMLEqual(w.render('email', None), '<input type="password" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'secret'), '<input type="password" name="email" />')
# The render_value argument lets you specify whether the widget should render
# its value. For security reasons, this is off by default.
w = PasswordInput(render_value=True)
- self.assertHTMLEqual(w.render('email', ''), u'<input type="password" name="email" />')
- self.assertHTMLEqual(w.render('email', None), u'<input type="password" name="email" />')
- self.assertHTMLEqual(w.render('email', 'test@example.com'), u'<input type="password" name="email" value="test@example.com" />')
- self.assertHTMLEqual(w.render('email', 'some "quoted" & ampersanded value'), u'<input type="password" name="email" value="some &quot;quoted&quot; &amp; ampersanded value" />')
- self.assertHTMLEqual(w.render('email', 'test@example.com', attrs={'class': 'fun'}), u'<input type="password" name="email" value="test@example.com" class="fun" />')
+ self.assertHTMLEqual(w.render('email', ''), '<input type="password" name="email" />')
+ self.assertHTMLEqual(w.render('email', None), '<input type="password" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'test@example.com'), '<input type="password" name="email" value="test@example.com" />')
+ self.assertHTMLEqual(w.render('email', 'some "quoted" & ampersanded value'), '<input type="password" name="email" value="some &quot;quoted&quot; &amp; ampersanded value" />')
+ self.assertHTMLEqual(w.render('email', 'test@example.com', attrs={'class': 'fun'}), '<input type="password" name="email" value="test@example.com" class="fun" />')
# You can also pass 'attrs' to the constructor:
w = PasswordInput(attrs={'class': 'fun'}, render_value=True)
- self.assertHTMLEqual(w.render('email', ''), u'<input type="password" class="fun" name="email" />')
- self.assertHTMLEqual(w.render('email', 'foo@example.com'), u'<input type="password" class="fun" value="foo@example.com" name="email" />')
+ self.assertHTMLEqual(w.render('email', ''), '<input type="password" class="fun" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'foo@example.com'), '<input type="password" class="fun" value="foo@example.com" name="email" />')
# 'attrs' passed to render() get precedence over those passed to the constructor:
w = PasswordInput(attrs={'class': 'pretty'}, render_value=True)
- self.assertHTMLEqual(w.render('email', '', attrs={'class': 'special'}), u'<input type="password" class="special" name="email" />')
+ self.assertHTMLEqual(w.render('email', '', attrs={'class': 'special'}), '<input type="password" class="special" name="email" />')
- self.assertHTMLEqual(w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), u'<input type="password" class="fun" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), '<input type="password" class="fun" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" name="email" />')
def test_hiddeninput(self):
w = HiddenInput()
- self.assertHTMLEqual(w.render('email', ''), u'<input type="hidden" name="email" />')
- self.assertHTMLEqual(w.render('email', None), u'<input type="hidden" name="email" />')
- self.assertHTMLEqual(w.render('email', 'test@example.com'), u'<input type="hidden" name="email" value="test@example.com" />')
- self.assertHTMLEqual(w.render('email', 'some "quoted" & ampersanded value'), u'<input type="hidden" name="email" value="some &quot;quoted&quot; &amp; ampersanded value" />')
- self.assertHTMLEqual(w.render('email', 'test@example.com', attrs={'class': 'fun'}), u'<input type="hidden" name="email" value="test@example.com" class="fun" />')
+ self.assertHTMLEqual(w.render('email', ''), '<input type="hidden" name="email" />')
+ self.assertHTMLEqual(w.render('email', None), '<input type="hidden" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'test@example.com'), '<input type="hidden" name="email" value="test@example.com" />')
+ self.assertHTMLEqual(w.render('email', 'some "quoted" & ampersanded value'), '<input type="hidden" name="email" value="some &quot;quoted&quot; &amp; ampersanded value" />')
+ self.assertHTMLEqual(w.render('email', 'test@example.com', attrs={'class': 'fun'}), '<input type="hidden" name="email" value="test@example.com" class="fun" />')
# You can also pass 'attrs' to the constructor:
w = HiddenInput(attrs={'class': 'fun'})
- self.assertHTMLEqual(w.render('email', ''), u'<input type="hidden" class="fun" name="email" />')
- self.assertHTMLEqual(w.render('email', 'foo@example.com'), u'<input type="hidden" class="fun" value="foo@example.com" name="email" />')
+ self.assertHTMLEqual(w.render('email', ''), '<input type="hidden" class="fun" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'foo@example.com'), '<input type="hidden" class="fun" value="foo@example.com" name="email" />')
# 'attrs' passed to render() get precedence over those passed to the constructor:
w = HiddenInput(attrs={'class': 'pretty'})
- self.assertHTMLEqual(w.render('email', '', attrs={'class': 'special'}), u'<input type="hidden" class="special" name="email" />')
+ self.assertHTMLEqual(w.render('email', '', attrs={'class': 'special'}), '<input type="hidden" class="special" name="email" />')
- self.assertHTMLEqual(w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), u'<input type="hidden" class="fun" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), '<input type="hidden" class="fun" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" name="email" />')
# 'attrs' passed to render() get precedence over those passed to the constructor:
w = HiddenInput(attrs={'class': 'pretty'})
- self.assertHTMLEqual(w.render('email', '', attrs={'class': 'special'}), u'<input type="hidden" class="special" name="email" />')
+ self.assertHTMLEqual(w.render('email', '', attrs={'class': 'special'}), '<input type="hidden" class="special" name="email" />')
# Boolean values are rendered to their string forms ("True" and "False").
w = HiddenInput()
- self.assertHTMLEqual(w.render('get_spam', False), u'<input type="hidden" name="get_spam" value="False" />')
- self.assertHTMLEqual(w.render('get_spam', True), u'<input type="hidden" name="get_spam" value="True" />')
+ self.assertHTMLEqual(w.render('get_spam', False), '<input type="hidden" name="get_spam" value="False" />')
+ self.assertHTMLEqual(w.render('get_spam', True), '<input type="hidden" name="get_spam" value="True" />')
def test_multiplehiddeninput(self):
w = MultipleHiddenInput()
- self.assertHTMLEqual(w.render('email', []), u'')
- self.assertHTMLEqual(w.render('email', None), u'')
- self.assertHTMLEqual(w.render('email', ['test@example.com']), u'<input type="hidden" name="email" value="test@example.com" />')
- self.assertHTMLEqual(w.render('email', ['some "quoted" & ampersanded value']), u'<input type="hidden" name="email" value="some &quot;quoted&quot; &amp; ampersanded value" />')
- self.assertHTMLEqual(w.render('email', ['test@example.com', 'foo@example.com']), u'<input type="hidden" name="email" value="test@example.com" />\n<input type="hidden" name="email" value="foo@example.com" />')
- self.assertHTMLEqual(w.render('email', ['test@example.com'], attrs={'class': 'fun'}), u'<input type="hidden" name="email" value="test@example.com" class="fun" />')
- self.assertHTMLEqual(w.render('email', ['test@example.com', 'foo@example.com'], attrs={'class': 'fun'}), u'<input type="hidden" name="email" value="test@example.com" class="fun" />\n<input type="hidden" name="email" value="foo@example.com" class="fun" />')
+ self.assertHTMLEqual(w.render('email', []), '')
+ self.assertHTMLEqual(w.render('email', None), '')
+ self.assertHTMLEqual(w.render('email', ['test@example.com']), '<input type="hidden" name="email" value="test@example.com" />')
+ self.assertHTMLEqual(w.render('email', ['some "quoted" & ampersanded value']), '<input type="hidden" name="email" value="some &quot;quoted&quot; &amp; ampersanded value" />')
+ self.assertHTMLEqual(w.render('email', ['test@example.com', 'foo@example.com']), '<input type="hidden" name="email" value="test@example.com" />\n<input type="hidden" name="email" value="foo@example.com" />')
+ self.assertHTMLEqual(w.render('email', ['test@example.com'], attrs={'class': 'fun'}), '<input type="hidden" name="email" value="test@example.com" class="fun" />')
+ self.assertHTMLEqual(w.render('email', ['test@example.com', 'foo@example.com'], attrs={'class': 'fun'}), '<input type="hidden" name="email" value="test@example.com" class="fun" />\n<input type="hidden" name="email" value="foo@example.com" class="fun" />')
# You can also pass 'attrs' to the constructor:
w = MultipleHiddenInput(attrs={'class': 'fun'})
- self.assertHTMLEqual(w.render('email', []), u'')
- self.assertHTMLEqual(w.render('email', ['foo@example.com']), u'<input type="hidden" class="fun" value="foo@example.com" name="email" />')
- self.assertHTMLEqual(w.render('email', ['foo@example.com', 'test@example.com']), u'<input type="hidden" class="fun" value="foo@example.com" name="email" />\n<input type="hidden" class="fun" value="test@example.com" name="email" />')
+ self.assertHTMLEqual(w.render('email', []), '')
+ self.assertHTMLEqual(w.render('email', ['foo@example.com']), '<input type="hidden" class="fun" value="foo@example.com" name="email" />')
+ self.assertHTMLEqual(w.render('email', ['foo@example.com', 'test@example.com']), '<input type="hidden" class="fun" value="foo@example.com" name="email" />\n<input type="hidden" class="fun" value="test@example.com" name="email" />')
# 'attrs' passed to render() get precedence over those passed to the constructor:
w = MultipleHiddenInput(attrs={'class': 'pretty'})
- self.assertHTMLEqual(w.render('email', ['foo@example.com'], attrs={'class': 'special'}), u'<input type="hidden" class="special" value="foo@example.com" name="email" />')
+ self.assertHTMLEqual(w.render('email', ['foo@example.com'], attrs={'class': 'special'}), '<input type="hidden" class="special" value="foo@example.com" name="email" />')
- self.assertHTMLEqual(w.render('email', ['ŠĐĆŽćžšđ'], attrs={'class': 'fun'}), u'<input type="hidden" class="fun" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" name="email" />')
+ self.assertHTMLEqual(w.render('email', ['ŠĐĆŽćžšđ'], attrs={'class': 'fun'}), '<input type="hidden" class="fun" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" name="email" />')
# 'attrs' passed to render() get precedence over those passed to the constructor:
w = MultipleHiddenInput(attrs={'class': 'pretty'})
- self.assertHTMLEqual(w.render('email', ['foo@example.com'], attrs={'class': 'special'}), u'<input type="hidden" class="special" value="foo@example.com" name="email" />')
+ self.assertHTMLEqual(w.render('email', ['foo@example.com'], attrs={'class': 'special'}), '<input type="hidden" class="special" value="foo@example.com" name="email" />')
# Each input gets a separate ID.
w = MultipleHiddenInput()
- self.assertHTMLEqual(w.render('letters', list('abc'), attrs={'id': 'hideme'}), u'<input type="hidden" name="letters" value="a" id="hideme_0" />\n<input type="hidden" name="letters" value="b" id="hideme_1" />\n<input type="hidden" name="letters" value="c" id="hideme_2" />')
+ self.assertHTMLEqual(w.render('letters', list('abc'), attrs={'id': 'hideme'}), '<input type="hidden" name="letters" value="a" id="hideme_0" />\n<input type="hidden" name="letters" value="b" id="hideme_1" />\n<input type="hidden" name="letters" value="c" id="hideme_2" />')
def test_fileinput(self):
# FileInput widgets don't ever show the value, because the old value is of no use
# if you are updating the form or if the provided file generated an error.
w = FileInput()
- self.assertHTMLEqual(w.render('email', ''), u'<input type="file" name="email" />')
- self.assertHTMLEqual(w.render('email', None), u'<input type="file" name="email" />')
- self.assertHTMLEqual(w.render('email', 'test@example.com'), u'<input type="file" name="email" />')
- self.assertHTMLEqual(w.render('email', 'some "quoted" & ampersanded value'), u'<input type="file" name="email" />')
- self.assertHTMLEqual(w.render('email', 'test@example.com', attrs={'class': 'fun'}), u'<input type="file" name="email" class="fun" />')
+ self.assertHTMLEqual(w.render('email', ''), '<input type="file" name="email" />')
+ self.assertHTMLEqual(w.render('email', None), '<input type="file" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'test@example.com'), '<input type="file" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'some "quoted" & ampersanded value'), '<input type="file" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'test@example.com', attrs={'class': 'fun'}), '<input type="file" name="email" class="fun" />')
# You can also pass 'attrs' to the constructor:
w = FileInput(attrs={'class': 'fun'})
- self.assertHTMLEqual(w.render('email', ''), u'<input type="file" class="fun" name="email" />')
- self.assertHTMLEqual(w.render('email', 'foo@example.com'), u'<input type="file" class="fun" name="email" />')
+ self.assertHTMLEqual(w.render('email', ''), '<input type="file" class="fun" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'foo@example.com'), '<input type="file" class="fun" name="email" />')
- self.assertHTMLEqual(w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), u'<input type="file" class="fun" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), '<input type="file" class="fun" name="email" />')
# Test for the behavior of _has_changed for FileInput. The value of data will
# more than likely come from request.FILES. The value of initial data will
@@ -148,13 +149,13 @@ class FormsWidgetTestCase(TestCase):
w = FileInput()
# No file was uploaded and no initial data.
- self.assertFalse(w._has_changed(u'', None))
+ self.assertFalse(w._has_changed('', None))
# A file was uploaded and no initial data.
- self.assertTrue(w._has_changed(u'', {'filename': 'resume.txt', 'content': 'My resume'}))
+ self.assertTrue(w._has_changed('', {'filename': 'resume.txt', 'content': 'My resume'}))
# A file was not uploaded, but there is initial data
- self.assertFalse(w._has_changed(u'resume.txt', None))
+ self.assertFalse(w._has_changed('resume.txt', None))
# A file was uploaded and there is initial data (file identity is not dealt
# with here)
@@ -162,64 +163,64 @@ class FormsWidgetTestCase(TestCase):
def test_textarea(self):
w = Textarea()
- self.assertHTMLEqual(w.render('msg', ''), u'<textarea rows="10" cols="40" name="msg"></textarea>')
- self.assertHTMLEqual(w.render('msg', None), u'<textarea rows="10" cols="40" name="msg"></textarea>')
- self.assertHTMLEqual(w.render('msg', 'value'), u'<textarea rows="10" cols="40" name="msg">value</textarea>')
- self.assertHTMLEqual(w.render('msg', 'some "quoted" & ampersanded value'), u'<textarea rows="10" cols="40" name="msg">some &quot;quoted&quot; &amp; ampersanded value</textarea>')
- self.assertHTMLEqual(w.render('msg', mark_safe('pre &quot;quoted&quot; value')), u'<textarea rows="10" cols="40" name="msg">pre &quot;quoted&quot; value</textarea>')
- self.assertHTMLEqual(w.render('msg', 'value', attrs={'class': 'pretty', 'rows': 20}), u'<textarea class="pretty" rows="20" cols="40" name="msg">value</textarea>')
+ self.assertHTMLEqual(w.render('msg', ''), '<textarea rows="10" cols="40" name="msg"></textarea>')
+ self.assertHTMLEqual(w.render('msg', None), '<textarea rows="10" cols="40" name="msg"></textarea>')
+ self.assertHTMLEqual(w.render('msg', 'value'), '<textarea rows="10" cols="40" name="msg">value</textarea>')
+ self.assertHTMLEqual(w.render('msg', 'some "quoted" & ampersanded value'), '<textarea rows="10" cols="40" name="msg">some &quot;quoted&quot; &amp; ampersanded value</textarea>')
+ self.assertHTMLEqual(w.render('msg', mark_safe('pre &quot;quoted&quot; value')), '<textarea rows="10" cols="40" name="msg">pre &quot;quoted&quot; value</textarea>')
+ self.assertHTMLEqual(w.render('msg', 'value', attrs={'class': 'pretty', 'rows': 20}), '<textarea class="pretty" rows="20" cols="40" name="msg">value</textarea>')
# You can also pass 'attrs' to the constructor:
w = Textarea(attrs={'class': 'pretty'})
- self.assertHTMLEqual(w.render('msg', ''), u'<textarea rows="10" cols="40" name="msg" class="pretty"></textarea>')
- self.assertHTMLEqual(w.render('msg', 'example'), u'<textarea rows="10" cols="40" name="msg" class="pretty">example</textarea>')
+ self.assertHTMLEqual(w.render('msg', ''), '<textarea rows="10" cols="40" name="msg" class="pretty"></textarea>')
+ self.assertHTMLEqual(w.render('msg', 'example'), '<textarea rows="10" cols="40" name="msg" class="pretty">example</textarea>')
# 'attrs' passed to render() get precedence over those passed to the constructor:
w = Textarea(attrs={'class': 'pretty'})
- self.assertHTMLEqual(w.render('msg', '', attrs={'class': 'special'}), u'<textarea rows="10" cols="40" name="msg" class="special"></textarea>')
+ self.assertHTMLEqual(w.render('msg', '', attrs={'class': 'special'}), '<textarea rows="10" cols="40" name="msg" class="special"></textarea>')
- self.assertHTMLEqual(w.render('msg', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), u'<textarea rows="10" cols="40" name="msg" class="fun">\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111</textarea>')
+ self.assertHTMLEqual(w.render('msg', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), '<textarea rows="10" cols="40" name="msg" class="fun">\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111</textarea>')
def test_checkboxinput(self):
w = CheckboxInput()
- self.assertHTMLEqual(w.render('is_cool', ''), u'<input type="checkbox" name="is_cool" />')
- self.assertHTMLEqual(w.render('is_cool', None), u'<input type="checkbox" name="is_cool" />')
- self.assertHTMLEqual(w.render('is_cool', False), u'<input type="checkbox" name="is_cool" />')
- self.assertHTMLEqual(w.render('is_cool', True), u'<input checked="checked" type="checkbox" name="is_cool" />')
+ self.assertHTMLEqual(w.render('is_cool', ''), '<input type="checkbox" name="is_cool" />')
+ self.assertHTMLEqual(w.render('is_cool', None), '<input type="checkbox" name="is_cool" />')
+ self.assertHTMLEqual(w.render('is_cool', False), '<input type="checkbox" name="is_cool" />')
+ self.assertHTMLEqual(w.render('is_cool', True), '<input checked="checked" type="checkbox" name="is_cool" />')
# Using any value that's not in ('', None, False, True) will check the checkbox
# and set the 'value' attribute.
- self.assertHTMLEqual(w.render('is_cool', 'foo'), u'<input checked="checked" type="checkbox" name="is_cool" value="foo" />')
+ self.assertHTMLEqual(w.render('is_cool', 'foo'), '<input checked="checked" type="checkbox" name="is_cool" value="foo" />')
- self.assertHTMLEqual(w.render('is_cool', False, attrs={'class': 'pretty'}), u'<input type="checkbox" name="is_cool" class="pretty" />')
+ self.assertHTMLEqual(w.render('is_cool', False, attrs={'class': 'pretty'}), '<input type="checkbox" name="is_cool" class="pretty" />')
# regression for #17114
- self.assertHTMLEqual(w.render('is_cool', 0), u'<input checked="checked" type="checkbox" name="is_cool" value="0" />')
- self.assertHTMLEqual(w.render('is_cool', 1), u'<input checked="checked" type="checkbox" name="is_cool" value="1" />')
+ self.assertHTMLEqual(w.render('is_cool', 0), '<input checked="checked" type="checkbox" name="is_cool" value="0" />')
+ self.assertHTMLEqual(w.render('is_cool', 1), '<input checked="checked" type="checkbox" name="is_cool" value="1" />')
# You can also pass 'attrs' to the constructor:
w = CheckboxInput(attrs={'class': 'pretty'})
- self.assertHTMLEqual(w.render('is_cool', ''), u'<input type="checkbox" class="pretty" name="is_cool" />')
+ self.assertHTMLEqual(w.render('is_cool', ''), '<input type="checkbox" class="pretty" name="is_cool" />')
# 'attrs' passed to render() get precedence over those passed to the constructor:
w = CheckboxInput(attrs={'class': 'pretty'})
- self.assertHTMLEqual(w.render('is_cool', '', attrs={'class': 'special'}), u'<input type="checkbox" class="special" name="is_cool" />')
+ self.assertHTMLEqual(w.render('is_cool', '', attrs={'class': 'special'}), '<input type="checkbox" class="special" name="is_cool" />')
# You can pass 'check_test' to the constructor. This is a callable that takes the
# value and returns True if the box should be checked.
w = CheckboxInput(check_test=lambda value: value.startswith('hello'))
- self.assertHTMLEqual(w.render('greeting', ''), u'<input type="checkbox" name="greeting" />')
- self.assertHTMLEqual(w.render('greeting', 'hello'), u'<input checked="checked" type="checkbox" name="greeting" value="hello" />')
- self.assertHTMLEqual(w.render('greeting', 'hello there'), u'<input checked="checked" type="checkbox" name="greeting" value="hello there" />')
- self.assertHTMLEqual(w.render('greeting', 'hello & goodbye'), u'<input checked="checked" type="checkbox" name="greeting" value="hello &amp; goodbye" />')
+ self.assertHTMLEqual(w.render('greeting', ''), '<input type="checkbox" name="greeting" />')
+ self.assertHTMLEqual(w.render('greeting', 'hello'), '<input checked="checked" type="checkbox" name="greeting" value="hello" />')
+ self.assertHTMLEqual(w.render('greeting', 'hello there'), '<input checked="checked" type="checkbox" name="greeting" value="hello there" />')
+ self.assertHTMLEqual(w.render('greeting', 'hello & goodbye'), '<input checked="checked" type="checkbox" name="greeting" value="hello &amp; goodbye" />')
# A subtlety: If the 'check_test' argument cannot handle a value and raises any
# exception during its __call__, then the exception will be swallowed and the box
# will not be checked. In this example, the 'check_test' assumes the value has a
# startswith() method, which fails for the values True, False and None.
- self.assertHTMLEqual(w.render('greeting', True), u'<input type="checkbox" name="greeting" />')
- self.assertHTMLEqual(w.render('greeting', False), u'<input type="checkbox" name="greeting" />')
- self.assertHTMLEqual(w.render('greeting', None), u'<input type="checkbox" name="greeting" />')
+ self.assertHTMLEqual(w.render('greeting', True), '<input type="checkbox" name="greeting" />')
+ self.assertHTMLEqual(w.render('greeting', False), '<input type="checkbox" name="greeting" />')
+ self.assertHTMLEqual(w.render('greeting', None), '<input type="checkbox" name="greeting" />')
# The CheckboxInput widget will return False if the key is not found in the data
# dictionary (because HTML form submission doesn't send any result for unchecked
@@ -227,12 +228,12 @@ class FormsWidgetTestCase(TestCase):
self.assertFalse(w.value_from_datadict({}, {}, 'testing'))
self.assertFalse(w._has_changed(None, None))
- self.assertFalse(w._has_changed(None, u''))
- self.assertFalse(w._has_changed(u'', None))
- self.assertFalse(w._has_changed(u'', u''))
- self.assertTrue(w._has_changed(False, u'on'))
- self.assertFalse(w._has_changed(True, u'on'))
- self.assertTrue(w._has_changed(True, u''))
+ self.assertFalse(w._has_changed(None, ''))
+ self.assertFalse(w._has_changed('', None))
+ self.assertFalse(w._has_changed('', ''))
+ self.assertTrue(w._has_changed(False, 'on'))
+ self.assertFalse(w._has_changed(True, 'on'))
+ self.assertTrue(w._has_changed(True, ''))
def test_select(self):
w = Select()
@@ -301,10 +302,10 @@ class FormsWidgetTestCase(TestCase):
class SomeForm(Form):
somechoice = ChoiceField(choices=chain((('', '-'*9),), [(thing['id'], thing['name']) for thing in things]))
f = SomeForm()
- self.assertHTMLEqual(f.as_table(), u'<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="" selected="selected">---------</option>\n<option value="1">And Boom</option>\n<option value="2">One More Thing!</option>\n</select></td></tr>')
- self.assertHTMLEqual(f.as_table(), u'<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="" selected="selected">---------</option>\n<option value="1">And Boom</option>\n<option value="2">One More Thing!</option>\n</select></td></tr>')
+ self.assertHTMLEqual(f.as_table(), '<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="" selected="selected">---------</option>\n<option value="1">And Boom</option>\n<option value="2">One More Thing!</option>\n</select></td></tr>')
+ self.assertHTMLEqual(f.as_table(), '<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="" selected="selected">---------</option>\n<option value="1">And Boom</option>\n<option value="2">One More Thing!</option>\n</select></td></tr>')
f = SomeForm({'somechoice': 2})
- self.assertHTMLEqual(f.as_table(), u'<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="">---------</option>\n<option value="1">And Boom</option>\n<option value="2" selected="selected">One More Thing!</option>\n</select></td></tr>')
+ self.assertHTMLEqual(f.as_table(), '<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="">---------</option>\n<option value="1">And Boom</option>\n<option value="2" selected="selected">One More Thing!</option>\n</select></td></tr>')
# You can also pass 'choices' to the constructor:
w = Select(choices=[(1, 1), (2, 2), (3, 3)])
@@ -333,7 +334,7 @@ class FormsWidgetTestCase(TestCase):
</select>""")
# Unicode choices are correctly rendered as HTML
- self.assertHTMLEqual(w.render('email', 'ŠĐĆŽćžšđ', choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]), u'<select name="email">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" selected="selected">\u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</option>\n<option value="\u0107\u017e\u0161\u0111">abc\u0107\u017e\u0161\u0111</option>\n</select>')
+ self.assertHTMLEqual(w.render('email', 'ŠĐĆŽćžšđ', choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]), '<select name="email">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" selected="selected">\u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</option>\n<option value="\u0107\u017e\u0161\u0111">abc\u0107\u017e\u0161\u0111</option>\n</select>')
# If choices is passed to the constructor and is a generator, it can be iterated
# over multiple times without getting consumed:
@@ -524,15 +525,15 @@ class FormsWidgetTestCase(TestCase):
</select>""")
# Unicode choices are correctly rendered as HTML
- self.assertHTMLEqual(w.render('nums', ['ŠĐĆŽćžšđ'], choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]), u'<select multiple="multiple" name="nums">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" selected="selected">\u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</option>\n<option value="\u0107\u017e\u0161\u0111">abc\u0107\u017e\u0161\u0111</option>\n</select>')
+ self.assertHTMLEqual(w.render('nums', ['ŠĐĆŽćžšđ'], choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]), '<select multiple="multiple" name="nums">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" selected="selected">\u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</option>\n<option value="\u0107\u017e\u0161\u0111">abc\u0107\u017e\u0161\u0111</option>\n</select>')
# Test the usage of _has_changed
self.assertFalse(w._has_changed(None, None))
self.assertFalse(w._has_changed([], None))
- self.assertTrue(w._has_changed(None, [u'1']))
- self.assertFalse(w._has_changed([1, 2], [u'1', u'2']))
- self.assertTrue(w._has_changed([1, 2], [u'1']))
- self.assertTrue(w._has_changed([1, 2], [u'1', u'3']))
+ self.assertTrue(w._has_changed(None, ['1']))
+ self.assertFalse(w._has_changed([1, 2], ['1', '2']))
+ self.assertTrue(w._has_changed([1, 2], ['1']))
+ self.assertTrue(w._has_changed([1, 2], ['1', '3']))
# Choices can be nested one level in order to create HTML optgroups:
w.choices = (('outer1', 'Outer 1'), ('Group "1"', (('inner1', 'Inner 1'), ('inner2', 'Inner 2'))))
@@ -675,7 +676,7 @@ beatle J R Ringo False""")
# You can create your own custom renderers for RadioSelect to use.
class MyRenderer(RadioFieldRenderer):
def render(self):
- return u'<br />\n'.join([unicode(choice) for choice in self])
+ return '<br />\n'.join([unicode(choice) for choice in self])
w = RadioSelect(renderer=MyRenderer)
self.assertHTMLEqual(w.render('beatle', 'G', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<label><input type="radio" name="beatle" value="J" /> John</label><br />
<label><input type="radio" name="beatle" value="P" /> Paul</label><br />
@@ -698,7 +699,7 @@ beatle J R Ringo False""")
self.assertHTMLEqual(str(r[0]), '<label><input checked="checked" type="radio" name="beatle" value="J" /> John</label>')
self.assertTrue(r[0].is_checked())
self.assertFalse(r[1].is_checked())
- self.assertEqual((r[1].name, r[1].value, r[1].choice_value, r[1].choice_label), ('beatle', u'J', u'P', u'Paul'))
+ self.assertEqual((r[1].name, r[1].value, r[1].choice_value, r[1].choice_label), ('beatle', 'J', 'P', 'Paul'))
try:
r[10]
@@ -715,7 +716,7 @@ beatle J R Ringo False""")
# Unicode choices are correctly rendered as HTML
w = RadioSelect()
- self.assertHTMLEqual(unicode(w.render('email', 'ŠĐĆŽćžšđ', choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')])), u'<ul>\n<li><label><input checked="checked" type="radio" name="email" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" /> \u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</label></li>\n<li><label><input type="radio" name="email" value="\u0107\u017e\u0161\u0111" /> abc\u0107\u017e\u0161\u0111</label></li>\n</ul>')
+ self.assertHTMLEqual(unicode(w.render('email', 'ŠĐĆŽćžšđ', choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')])), '<ul>\n<li><label><input checked="checked" type="radio" name="email" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" /> \u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</label></li>\n<li><label><input type="radio" name="email" value="\u0107\u017e\u0161\u0111" /> abc\u0107\u017e\u0161\u0111</label></li>\n</ul>')
# Attributes provided at instantiation are passed to the constituent inputs
w = RadioSelect(attrs={'id':'foo'})
@@ -838,14 +839,14 @@ beatle J R Ringo False""")
# Test the usage of _has_changed
self.assertFalse(w._has_changed(None, None))
self.assertFalse(w._has_changed([], None))
- self.assertTrue(w._has_changed(None, [u'1']))
- self.assertFalse(w._has_changed([1, 2], [u'1', u'2']))
- self.assertTrue(w._has_changed([1, 2], [u'1']))
- self.assertTrue(w._has_changed([1, 2], [u'1', u'3']))
- self.assertFalse(w._has_changed([2, 1], [u'1', u'2']))
+ self.assertTrue(w._has_changed(None, ['1']))
+ self.assertFalse(w._has_changed([1, 2], ['1', '2']))
+ self.assertTrue(w._has_changed([1, 2], ['1']))
+ self.assertTrue(w._has_changed([1, 2], ['1', '3']))
+ self.assertFalse(w._has_changed([2, 1], ['1', '2']))
# Unicode choices are correctly rendered as HTML
- self.assertHTMLEqual(w.render('nums', ['ŠĐĆŽćžšđ'], choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]), u'<ul>\n<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li>\n<li><label><input type="checkbox" name="nums" value="2" /> 2</label></li>\n<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li>\n<li><label><input checked="checked" type="checkbox" name="nums" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" /> \u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</label></li>\n<li><label><input type="checkbox" name="nums" value="\u0107\u017e\u0161\u0111" /> abc\u0107\u017e\u0161\u0111</label></li>\n</ul>')
+ self.assertHTMLEqual(w.render('nums', ['ŠĐĆŽćžšđ'], choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]), '<ul>\n<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li>\n<li><label><input type="checkbox" name="nums" value="2" /> 2</label></li>\n<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li>\n<li><label><input checked="checked" type="checkbox" name="nums" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" /> \u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</label></li>\n<li><label><input type="checkbox" name="nums" value="\u0107\u017e\u0161\u0111" /> abc\u0107\u017e\u0161\u0111</label></li>\n</ul>')
# Each input gets a separate ID
self.assertHTMLEqual(CheckboxSelectMultiple().render('letters', list('ac'), choices=zip(list('abc'), list('ABC')), attrs={'id': 'abc'}), """<ul>
@@ -861,63 +862,63 @@ beatle J R Ringo False""")
return value.split('__')
return ['', '']
def format_output(self, rendered_widgets):
- return u'<br />'.join(rendered_widgets)
+ return '<br />'.join(rendered_widgets)
w = MyMultiWidget(widgets=(TextInput(attrs={'class': 'big'}), TextInput(attrs={'class': 'small'})))
- self.assertHTMLEqual(w.render('name', ['john', 'lennon']), u'<input type="text" class="big" value="john" name="name_0" /><br /><input type="text" class="small" value="lennon" name="name_1" />')
- self.assertHTMLEqual(w.render('name', 'john__lennon'), u'<input type="text" class="big" value="john" name="name_0" /><br /><input type="text" class="small" value="lennon" name="name_1" />')
- self.assertHTMLEqual(w.render('name', 'john__lennon', attrs={'id':'foo'}), u'<input id="foo_0" type="text" class="big" value="john" name="name_0" /><br /><input id="foo_1" type="text" class="small" value="lennon" name="name_1" />')
+ self.assertHTMLEqual(w.render('name', ['john', 'lennon']), '<input type="text" class="big" value="john" name="name_0" /><br /><input type="text" class="small" value="lennon" name="name_1" />')
+ self.assertHTMLEqual(w.render('name', 'john__lennon'), '<input type="text" class="big" value="john" name="name_0" /><br /><input type="text" class="small" value="lennon" name="name_1" />')
+ self.assertHTMLEqual(w.render('name', 'john__lennon', attrs={'id':'foo'}), '<input id="foo_0" type="text" class="big" value="john" name="name_0" /><br /><input id="foo_1" type="text" class="small" value="lennon" name="name_1" />')
w = MyMultiWidget(widgets=(TextInput(attrs={'class': 'big'}), TextInput(attrs={'class': 'small'})), attrs={'id': 'bar'})
- self.assertHTMLEqual(w.render('name', ['john', 'lennon']), u'<input id="bar_0" type="text" class="big" value="john" name="name_0" /><br /><input id="bar_1" type="text" class="small" value="lennon" name="name_1" />')
+ self.assertHTMLEqual(w.render('name', ['john', 'lennon']), '<input id="bar_0" type="text" class="big" value="john" name="name_0" /><br /><input id="bar_1" type="text" class="small" value="lennon" name="name_1" />')
w = MyMultiWidget(widgets=(TextInput(), TextInput()))
# test with no initial data
- self.assertTrue(w._has_changed(None, [u'john', u'lennon']))
+ self.assertTrue(w._has_changed(None, ['john', 'lennon']))
# test when the data is the same as initial
- self.assertFalse(w._has_changed(u'john__lennon', [u'john', u'lennon']))
+ self.assertFalse(w._has_changed('john__lennon', ['john', 'lennon']))
# test when the first widget's data has changed
- self.assertTrue(w._has_changed(u'john__lennon', [u'alfred', u'lennon']))
+ self.assertTrue(w._has_changed('john__lennon', ['alfred', 'lennon']))
# test when the last widget's data has changed. this ensures that it is not
# short circuiting while testing the widgets.
- self.assertTrue(w._has_changed(u'john__lennon', [u'john', u'denver']))
+ self.assertTrue(w._has_changed('john__lennon', ['john', 'denver']))
def test_splitdatetime(self):
w = SplitDateTimeWidget()
- self.assertHTMLEqual(w.render('date', ''), u'<input type="text" name="date_0" /><input type="text" name="date_1" />')
- self.assertHTMLEqual(w.render('date', None), u'<input type="text" name="date_0" /><input type="text" name="date_1" />')
- self.assertHTMLEqual(w.render('date', datetime.datetime(2006, 1, 10, 7, 30)), u'<input type="text" name="date_0" value="2006-01-10" /><input type="text" name="date_1" value="07:30:00" />')
- self.assertHTMLEqual(w.render('date', [datetime.date(2006, 1, 10), datetime.time(7, 30)]), u'<input type="text" name="date_0" value="2006-01-10" /><input type="text" name="date_1" value="07:30:00" />')
+ self.assertHTMLEqual(w.render('date', ''), '<input type="text" name="date_0" /><input type="text" name="date_1" />')
+ self.assertHTMLEqual(w.render('date', None), '<input type="text" name="date_0" /><input type="text" name="date_1" />')
+ self.assertHTMLEqual(w.render('date', datetime.datetime(2006, 1, 10, 7, 30)), '<input type="text" name="date_0" value="2006-01-10" /><input type="text" name="date_1" value="07:30:00" />')
+ self.assertHTMLEqual(w.render('date', [datetime.date(2006, 1, 10), datetime.time(7, 30)]), '<input type="text" name="date_0" value="2006-01-10" /><input type="text" name="date_1" value="07:30:00" />')
# You can also pass 'attrs' to the constructor. In this case, the attrs will be
w = SplitDateTimeWidget(attrs={'class': 'pretty'})
- self.assertHTMLEqual(w.render('date', datetime.datetime(2006, 1, 10, 7, 30)), u'<input type="text" class="pretty" value="2006-01-10" name="date_0" /><input type="text" class="pretty" value="07:30:00" name="date_1" />')
+ self.assertHTMLEqual(w.render('date', datetime.datetime(2006, 1, 10, 7, 30)), '<input type="text" class="pretty" value="2006-01-10" name="date_0" /><input type="text" class="pretty" value="07:30:00" name="date_1" />')
# Use 'date_format' and 'time_format' to change the way a value is displayed.
w = SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M')
- self.assertHTMLEqual(w.render('date', datetime.datetime(2006, 1, 10, 7, 30)), u'<input type="text" name="date_0" value="10/01/2006" /><input type="text" name="date_1" value="07:30" />')
+ self.assertHTMLEqual(w.render('date', datetime.datetime(2006, 1, 10, 7, 30)), '<input type="text" name="date_0" value="10/01/2006" /><input type="text" name="date_1" value="07:30" />')
- self.assertTrue(w._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), [u'2008-05-06', u'12:40:00']))
- self.assertFalse(w._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), [u'06/05/2008', u'12:40']))
- self.assertTrue(w._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), [u'06/05/2008', u'12:41']))
+ self.assertTrue(w._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), ['2008-05-06', '12:40:00']))
+ self.assertFalse(w._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), ['06/05/2008', '12:40']))
+ self.assertTrue(w._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), ['06/05/2008', '12:41']))
def test_datetimeinput(self):
w = DateTimeInput()
- self.assertHTMLEqual(w.render('date', None), u'<input type="text" name="date" />')
+ self.assertHTMLEqual(w.render('date', None), '<input type="text" name="date" />')
d = datetime.datetime(2007, 9, 17, 12, 51, 34, 482548)
self.assertEqual(str(d), '2007-09-17 12:51:34.482548')
# The microseconds are trimmed on display, by default.
- self.assertHTMLEqual(w.render('date', d), u'<input type="text" name="date" value="2007-09-17 12:51:34" />')
- self.assertHTMLEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51, 34)), u'<input type="text" name="date" value="2007-09-17 12:51:34" />')
- self.assertHTMLEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51)), u'<input type="text" name="date" value="2007-09-17 12:51:00" />')
+ self.assertHTMLEqual(w.render('date', d), '<input type="text" name="date" value="2007-09-17 12:51:34" />')
+ self.assertHTMLEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51, 34)), '<input type="text" name="date" value="2007-09-17 12:51:34" />')
+ self.assertHTMLEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51)), '<input type="text" name="date" value="2007-09-17 12:51:00" />')
# Use 'format' to change the way a value is displayed.
w = DateTimeInput(format='%d/%m/%Y %H:%M')
- self.assertHTMLEqual(w.render('date', d), u'<input type="text" name="date" value="17/09/2007 12:51" />')
+ self.assertHTMLEqual(w.render('date', d), '<input type="text" name="date" value="17/09/2007 12:51" />')
self.assertFalse(w._has_changed(d, '17/09/2007 12:51'))
# Make sure a custom format works with _has_changed. The hidden input will use
@@ -928,19 +929,19 @@ beatle J R Ringo False""")
def test_dateinput(self):
w = DateInput()
- self.assertHTMLEqual(w.render('date', None), u'<input type="text" name="date" />')
+ self.assertHTMLEqual(w.render('date', None), '<input type="text" name="date" />')
d = datetime.date(2007, 9, 17)
self.assertEqual(str(d), '2007-09-17')
- self.assertHTMLEqual(w.render('date', d), u'<input type="text" name="date" value="2007-09-17" />')
- self.assertHTMLEqual(w.render('date', datetime.date(2007, 9, 17)), u'<input type="text" name="date" value="2007-09-17" />')
+ self.assertHTMLEqual(w.render('date', d), '<input type="text" name="date" value="2007-09-17" />')
+ self.assertHTMLEqual(w.render('date', datetime.date(2007, 9, 17)), '<input type="text" name="date" value="2007-09-17" />')
# We should be able to initialize from a unicode value.
- self.assertHTMLEqual(w.render('date', u'2007-09-17'), u'<input type="text" name="date" value="2007-09-17" />')
+ self.assertHTMLEqual(w.render('date', '2007-09-17'), '<input type="text" name="date" value="2007-09-17" />')
# Use 'format' to change the way a value is displayed.
w = DateInput(format='%d/%m/%Y')
- self.assertHTMLEqual(w.render('date', d), u'<input type="text" name="date" value="17/09/2007" />')
+ self.assertHTMLEqual(w.render('date', d), '<input type="text" name="date" value="17/09/2007" />')
self.assertFalse(w._has_changed(d, '17/09/2007'))
# Make sure a custom format works with _has_changed. The hidden input will use
@@ -951,21 +952,21 @@ beatle J R Ringo False""")
def test_timeinput(self):
w = TimeInput()
- self.assertHTMLEqual(w.render('time', None), u'<input type="text" name="time" />')
+ self.assertHTMLEqual(w.render('time', None), '<input type="text" name="time" />')
t = datetime.time(12, 51, 34, 482548)
self.assertEqual(str(t), '12:51:34.482548')
# The microseconds are trimmed on display, by default.
- self.assertHTMLEqual(w.render('time', t), u'<input type="text" name="time" value="12:51:34" />')
- self.assertHTMLEqual(w.render('time', datetime.time(12, 51, 34)), u'<input type="text" name="time" value="12:51:34" />')
- self.assertHTMLEqual(w.render('time', datetime.time(12, 51)), u'<input type="text" name="time" value="12:51:00" />')
+ self.assertHTMLEqual(w.render('time', t), '<input type="text" name="time" value="12:51:34" />')
+ self.assertHTMLEqual(w.render('time', datetime.time(12, 51, 34)), '<input type="text" name="time" value="12:51:34" />')
+ self.assertHTMLEqual(w.render('time', datetime.time(12, 51)), '<input type="text" name="time" value="12:51:00" />')
# We should be able to initialize from a unicode value.
- self.assertHTMLEqual(w.render('time', u'13:12:11'), u'<input type="text" name="time" value="13:12:11" />')
+ self.assertHTMLEqual(w.render('time', '13:12:11'), '<input type="text" name="time" value="13:12:11" />')
# Use 'format' to change the way a value is displayed.
w = TimeInput(format='%H:%M')
- self.assertHTMLEqual(w.render('time', t), u'<input type="text" name="time" value="12:51" />')
+ self.assertHTMLEqual(w.render('time', t), '<input type="text" name="time" value="12:51" />')
self.assertFalse(w._has_changed(t, '12:51'))
# Make sure a custom format works with _has_changed. The hidden input will use
@@ -978,12 +979,12 @@ beatle J R Ringo False""")
from django.forms.widgets import SplitHiddenDateTimeWidget
w = SplitHiddenDateTimeWidget()
- self.assertHTMLEqual(w.render('date', ''), u'<input type="hidden" name="date_0" /><input type="hidden" name="date_1" />')
+ self.assertHTMLEqual(w.render('date', ''), '<input type="hidden" name="date_0" /><input type="hidden" name="date_1" />')
d = datetime.datetime(2007, 9, 17, 12, 51, 34, 482548)
self.assertHTMLEqual(str(d), '2007-09-17 12:51:34.482548')
- self.assertHTMLEqual(w.render('date', d), u'<input type="hidden" name="date_0" value="2007-09-17" /><input type="hidden" name="date_1" value="12:51:34" />')
- self.assertHTMLEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51, 34)), u'<input type="hidden" name="date_0" value="2007-09-17" /><input type="hidden" name="date_1" value="12:51:34" />')
- self.assertHTMLEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51)), u'<input type="hidden" name="date_0" value="2007-09-17" /><input type="hidden" name="date_1" value="12:51:00" />')
+ self.assertHTMLEqual(w.render('date', d), '<input type="hidden" name="date_0" value="2007-09-17" /><input type="hidden" name="date_1" value="12:51:34" />')
+ self.assertHTMLEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51, 34)), '<input type="hidden" name="date_0" value="2007-09-17" /><input type="hidden" name="date_1" value="12:51:34" />')
+ self.assertHTMLEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51)), '<input type="hidden" name="date_0" value="2007-09-17" /><input type="hidden" name="date_1" value="12:51:00" />')
class NullBooleanSelectLazyForm(Form):
@@ -1004,32 +1005,32 @@ class FormsI18NWidgetsTestCase(TestCase):
def test_splitdatetime(self):
w = SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M')
- self.assertTrue(w._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), [u'06.05.2008', u'12:41']))
+ self.assertTrue(w._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), ['06.05.2008', '12:41']))
def test_datetimeinput(self):
w = DateTimeInput()
d = datetime.datetime(2007, 9, 17, 12, 51, 34, 482548)
w.is_localized = True
- self.assertHTMLEqual(w.render('date', d), u'<input type="text" name="date" value="17.09.2007 12:51:34" />')
+ self.assertHTMLEqual(w.render('date', d), '<input type="text" name="date" value="17.09.2007 12:51:34" />')
def test_dateinput(self):
w = DateInput()
d = datetime.date(2007, 9, 17)
w.is_localized = True
- self.assertHTMLEqual(w.render('date', d), u'<input type="text" name="date" value="17.09.2007" />')
+ self.assertHTMLEqual(w.render('date', d), '<input type="text" name="date" value="17.09.2007" />')
def test_timeinput(self):
w = TimeInput()
t = datetime.time(12, 51, 34, 482548)
w.is_localized = True
- self.assertHTMLEqual(w.render('time', t), u'<input type="text" name="time" value="12:51:34" />')
+ self.assertHTMLEqual(w.render('time', t), '<input type="text" name="time" value="12:51:34" />')
def test_splithiddendatetime(self):
from django.forms.widgets import SplitHiddenDateTimeWidget
w = SplitHiddenDateTimeWidget()
w.is_localized = True
- self.assertHTMLEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51)), u'<input type="hidden" name="date_0" value="17.09.2007" /><input type="hidden" name="date_1" value="12:51:00" />')
+ self.assertHTMLEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51)), '<input type="hidden" name="date_0" value="17.09.2007" /><input type="hidden" name="date_1" value="12:51:00" />')
def test_nullbooleanselect(self):
"""
@@ -1038,7 +1039,7 @@ class FormsI18NWidgetsTestCase(TestCase):
Refs #17190
"""
f = NullBooleanSelectLazyForm()
- self.assertHTMLEqual(f.fields['bool'].widget.render('id_bool', True), u'<select name="id_bool">\n<option value="1">Unbekannt</option>\n<option value="2" selected="selected">Ja</option>\n<option value="3">Nein</option>\n</select>')
+ self.assertHTMLEqual(f.fields['bool'].widget.render('id_bool', True), '<select name="id_bool">\n<option value="1">Unbekannt</option>\n<option value="2" selected="selected">Ja</option>\n<option value="3">Nein</option>\n</select>')
class SelectAndTextWidget(MultiWidget):
@@ -1115,7 +1116,7 @@ class ClearableFileInputTests(TestCase):
widget = ClearableFileInput()
widget.is_required = False
self.assertHTMLEqual(widget.render('myfile', FakeFieldFile()),
- u'Currently: <a href="something">something</a> <input type="checkbox" name="myfile-clear" id="myfile-clear_id" /> <label for="myfile-clear_id">Clear</label><br />Change: <input type="file" name="myfile" />')
+ 'Currently: <a href="something">something</a> <input type="checkbox" name="myfile-clear" id="myfile-clear_id" /> <label for="myfile-clear_id">Clear</label><br />Change: <input type="file" name="myfile" />')
def test_html_escaped(self):
"""
@@ -1127,17 +1128,17 @@ class ClearableFileInputTests(TestCase):
url = "something?chapter=1&sect=2&copy=3&lang=en"
def __unicode__(self):
- return u'''something<div onclick="alert('oops')">.jpg'''
+ return '''something<div onclick="alert('oops')">.jpg'''
widget = ClearableFileInput()
field = StrangeFieldFile()
output = widget.render('my<div>file', field)
self.assertFalse(field.url in output)
- self.assertTrue(u'href="something?chapter=1&amp;sect=2&amp;copy=3&amp;lang=en"' in output)
+ self.assertTrue('href="something?chapter=1&amp;sect=2&amp;copy=3&amp;lang=en"' in output)
self.assertFalse(unicode(field) in output)
- self.assertTrue(u'something&lt;div onclick=&quot;alert(&#39;oops&#39;)&quot;&gt;.jpg' in output)
- self.assertTrue(u'my&lt;div&gt;file' in output)
- self.assertFalse(u'my<div>file' in output)
+ self.assertTrue('something&lt;div onclick=&quot;alert(&#39;oops&#39;)&quot;&gt;.jpg' in output)
+ self.assertTrue('my&lt;div&gt;file' in output)
+ self.assertFalse('my<div>file' in output)
def test_clear_input_renders_only_if_not_required(self):
"""
@@ -1148,7 +1149,7 @@ class ClearableFileInputTests(TestCase):
widget = ClearableFileInput()
widget.is_required = True
self.assertHTMLEqual(widget.render('myfile', FakeFieldFile()),
- u'Currently: <a href="something">something</a> <br />Change: <input type="file" name="myfile" />')
+ 'Currently: <a href="something">something</a> <br />Change: <input type="file" name="myfile" />')
def test_clear_input_renders_only_if_initial(self):
"""
@@ -1159,7 +1160,7 @@ class ClearableFileInputTests(TestCase):
widget = ClearableFileInput()
widget.is_required = False
self.assertHTMLEqual(widget.render('myfile', None),
- u'<input type="file" name="myfile" />')
+ '<input type="file" name="myfile" />')
def test_clear_input_checked_returns_false(self):
"""
diff --git a/tests/regressiontests/generic_inline_admin/tests.py b/tests/regressiontests/generic_inline_admin/tests.py
index c6c1eeac5a..c97f4c4f03 100644
--- a/tests/regressiontests/generic_inline_admin/tests.py
+++ b/tests/regressiontests/generic_inline_admin/tests.py
@@ -1,6 +1,5 @@
-# coding: utf-8
-
-from __future__ import absolute_import
+# -*- coding: utf-8 -*-
+from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.contrib import admin
@@ -66,11 +65,11 @@ class GenericAdminViewTest(TestCase):
A smoke test to ensure POST on add_view works.
"""
post_data = {
- "name": u"This Week in Django",
+ "name": "This Week in Django",
# inline data
- "generic_inline_admin-media-content_type-object_id-TOTAL_FORMS": u"1",
- "generic_inline_admin-media-content_type-object_id-INITIAL_FORMS": u"0",
- "generic_inline_admin-media-content_type-object_id-MAX_NUM_FORMS": u"0",
+ "generic_inline_admin-media-content_type-object_id-TOTAL_FORMS": "1",
+ "generic_inline_admin-media-content_type-object_id-INITIAL_FORMS": "0",
+ "generic_inline_admin-media-content_type-object_id-MAX_NUM_FORMS": "0",
}
response = self.client.post('/generic_inline_admin/admin/generic_inline_admin/episode/add/', post_data)
self.assertEqual(response.status_code, 302) # redirect somewhere
@@ -80,17 +79,17 @@ class GenericAdminViewTest(TestCase):
A smoke test to ensure POST on edit_view works.
"""
post_data = {
- "name": u"This Week in Django",
+ "name": "This Week in Django",
# inline data
- "generic_inline_admin-media-content_type-object_id-TOTAL_FORMS": u"3",
- "generic_inline_admin-media-content_type-object_id-INITIAL_FORMS": u"2",
- "generic_inline_admin-media-content_type-object_id-MAX_NUM_FORMS": u"0",
- "generic_inline_admin-media-content_type-object_id-0-id": u"%d" % self.mp3_media_pk,
- "generic_inline_admin-media-content_type-object_id-0-url": u"http://example.com/podcast.mp3",
- "generic_inline_admin-media-content_type-object_id-1-id": u"%d" % self.png_media_pk,
- "generic_inline_admin-media-content_type-object_id-1-url": u"http://example.com/logo.png",
- "generic_inline_admin-media-content_type-object_id-2-id": u"",
- "generic_inline_admin-media-content_type-object_id-2-url": u"",
+ "generic_inline_admin-media-content_type-object_id-TOTAL_FORMS": "3",
+ "generic_inline_admin-media-content_type-object_id-INITIAL_FORMS": "2",
+ "generic_inline_admin-media-content_type-object_id-MAX_NUM_FORMS": "0",
+ "generic_inline_admin-media-content_type-object_id-0-id": "%d" % self.mp3_media_pk,
+ "generic_inline_admin-media-content_type-object_id-0-url": "http://example.com/podcast.mp3",
+ "generic_inline_admin-media-content_type-object_id-1-id": "%d" % self.png_media_pk,
+ "generic_inline_admin-media-content_type-object_id-1-url": "http://example.com/logo.png",
+ "generic_inline_admin-media-content_type-object_id-2-id": "",
+ "generic_inline_admin-media-content_type-object_id-2-url": "",
}
url = '/generic_inline_admin/admin/generic_inline_admin/episode/%d/' % self.episode_pk
response = self.client.post(url, post_data)
@@ -198,11 +197,11 @@ class GenericInlineAdminWithUniqueTogetherTest(TestCase):
def testAdd(self):
category_id = Category.objects.create(name='male').pk
post_data = {
- "name": u"John Doe",
+ "name": "John Doe",
# inline data
- "generic_inline_admin-phonenumber-content_type-object_id-TOTAL_FORMS": u"1",
- "generic_inline_admin-phonenumber-content_type-object_id-INITIAL_FORMS": u"0",
- "generic_inline_admin-phonenumber-content_type-object_id-MAX_NUM_FORMS": u"0",
+ "generic_inline_admin-phonenumber-content_type-object_id-TOTAL_FORMS": "1",
+ "generic_inline_admin-phonenumber-content_type-object_id-INITIAL_FORMS": "0",
+ "generic_inline_admin-phonenumber-content_type-object_id-MAX_NUM_FORMS": "0",
"generic_inline_admin-phonenumber-content_type-object_id-0-id": "",
"generic_inline_admin-phonenumber-content_type-object_id-0-phone_number": "555-555-5555",
"generic_inline_admin-phonenumber-content_type-object_id-0-category": "%s" % category_id,
diff --git a/tests/regressiontests/httpwrappers/tests.py b/tests/regressiontests/httpwrappers/tests.py
index 218c5b5b3b..870324bffb 100644
--- a/tests/regressiontests/httpwrappers/tests.py
+++ b/tests/regressiontests/httpwrappers/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import copy
import pickle
@@ -59,8 +61,8 @@ class QueryDictTests(unittest.TestCase):
self.assertFalse(q.has_key('bar'))
self.assertFalse('bar' in q)
- self.assertEqual(q.items(), [(u'foo', u'bar')])
- self.assertEqual(q.lists(), [(u'foo', [u'bar'])])
+ self.assertEqual(q.items(), [('foo', 'bar')])
+ self.assertEqual(q.lists(), [('foo', ['bar'])])
self.assertEqual(q.keys(), ['foo'])
self.assertEqual(q.values(), ['bar'])
self.assertEqual(len(q), 1)
@@ -79,7 +81,7 @@ class QueryDictTests(unittest.TestCase):
self.assertEqual(q.urlencode(), 'next=%2Fa%26b%2F')
self.assertEqual(q.urlencode(safe='/'), 'next=/a%26b/')
q = QueryDict('', mutable=True)
- q['next'] = u'/t\xebst&key/'
+ q['next'] = '/t\xebst&key/'
self.assertEqual(q.urlencode(), 'next=%2Ft%C3%ABst%26key%2F')
self.assertEqual(q.urlencode(safe='/'), 'next=/t%C3%ABst%26key/')
@@ -114,17 +116,17 @@ class QueryDictTests(unittest.TestCase):
self.assertTrue(q.has_key('foo'))
self.assertTrue('foo' in q)
- self.assertEqual(q.items(), [(u'foo', u'another'), (u'name', u'john')])
- self.assertEqual(q.lists(), [(u'foo', [u'bar', u'baz', u'another']), (u'name', [u'john'])])
- self.assertEqual(q.keys(), [u'foo', u'name'])
- self.assertEqual(q.values(), [u'another', u'john'])
+ self.assertEqual(q.items(), [('foo', 'another'), ('name', 'john')])
+ self.assertEqual(q.lists(), [('foo', ['bar', 'baz', 'another']), ('name', ['john'])])
+ self.assertEqual(q.keys(), ['foo', 'name'])
+ self.assertEqual(q.values(), ['another', 'john'])
self.assertEqual(len(q), 2)
q.update({'foo': 'hello'})
self.assertEqual(q['foo'], 'hello')
self.assertEqual(q.get('foo', 'not available'), 'hello')
- self.assertEqual(q.getlist('foo'), [u'bar', u'baz', u'another', u'hello'])
- self.assertEqual(q.pop('foo'), [u'bar', u'baz', u'another', u'hello'])
+ self.assertEqual(q.getlist('foo'), ['bar', 'baz', 'another', 'hello'])
+ self.assertEqual(q.pop('foo'), ['bar', 'baz', 'another', 'hello'])
self.assertEqual(q.pop('foo', 'not there'), 'not there')
self.assertEqual(q.get('foo', 'not there'), 'not there')
self.assertEqual(q.setdefault('foo', 'bar'), 'bar')
@@ -140,12 +142,12 @@ class QueryDictTests(unittest.TestCase):
q = QueryDict('vote=yes&vote=no')
- self.assertEqual(q['vote'], u'no')
+ self.assertEqual(q['vote'], 'no')
self.assertRaises(AttributeError, q.__setitem__, 'something', 'bar')
- self.assertEqual(q.get('vote', 'default'), u'no')
+ self.assertEqual(q.get('vote', 'default'), 'no')
self.assertEqual(q.get('foo', 'default'), 'default')
- self.assertEqual(q.getlist('vote'), [u'yes', u'no'])
+ self.assertEqual(q.getlist('vote'), ['yes', 'no'])
self.assertEqual(q.getlist('foo'), [])
self.assertRaises(AttributeError, q.setlist, 'foo', ['bar', 'baz'])
@@ -156,10 +158,10 @@ class QueryDictTests(unittest.TestCase):
self.assertEqual('vote' in q, True)
self.assertEqual(q.has_key('foo'), False)
self.assertEqual('foo' in q, False)
- self.assertEqual(q.items(), [(u'vote', u'no')])
- self.assertEqual(q.lists(), [(u'vote', [u'yes', u'no'])])
- self.assertEqual(q.keys(), [u'vote'])
- self.assertEqual(q.values(), [u'no'])
+ self.assertEqual(q.items(), [('vote', 'no')])
+ self.assertEqual(q.lists(), [('vote', ['yes', 'no'])])
+ self.assertEqual(q.keys(), ['vote'])
+ self.assertEqual(q.values(), ['no'])
self.assertEqual(len(q), 1)
self.assertRaises(AttributeError, q.update, {'foo': 'bar'})
@@ -175,8 +177,8 @@ class QueryDictTests(unittest.TestCase):
case, bad UTF-8 encoding).
"""
q = QueryDict(b'foo=bar&foo=\xff')
- self.assertEqual(q['foo'], u'\ufffd')
- self.assertEqual(q.getlist('foo'), [u'bar', u'\ufffd'])
+ self.assertEqual(q['foo'], '\ufffd')
+ self.assertEqual(q.getlist('foo'), ['bar', '\ufffd'])
def test_pickle(self):
q = QueryDict('')
@@ -194,17 +196,17 @@ class QueryDictTests(unittest.TestCase):
x = QueryDict("a=1&a=2", mutable=True)
y = QueryDict("a=3&a=4")
x.update(y)
- self.assertEqual(x.getlist('a'), [u'1', u'2', u'3', u'4'])
+ self.assertEqual(x.getlist('a'), ['1', '2', '3', '4'])
def test_non_default_encoding(self):
"""#13572 - QueryDict with a non-default encoding"""
q = QueryDict(b'sbb=one', encoding='rot_13')
self.assertEqual(q.encoding , 'rot_13' )
- self.assertEqual(q.items() , [(u'foo', u'bar')] )
+ self.assertEqual(q.items() , [('foo', 'bar')] )
self.assertEqual(q.urlencode() , 'sbb=one' )
q = q.copy()
self.assertEqual(q.encoding , 'rot_13' )
- self.assertEqual(q.items() , [(u'foo', u'bar')] )
+ self.assertEqual(q.items() , [('foo', 'bar')] )
self.assertEqual(q.urlencode() , 'sbb=one' )
self.assertEqual(copy.copy(q).encoding , 'rot_13' )
self.assertEqual(copy.deepcopy(q).encoding , 'rot_13')
@@ -214,29 +216,29 @@ class HttpResponseTests(unittest.TestCase):
r = HttpResponse()
# If we insert a unicode value it will be converted to an ascii
- r['value'] = u'test value'
+ r['value'] = 'test value'
self.assertTrue(isinstance(r['value'], str))
# An error is raised when a unicode object with non-ascii is assigned.
- self.assertRaises(UnicodeEncodeError, r.__setitem__, 'value', u't\xebst value')
+ self.assertRaises(UnicodeEncodeError, r.__setitem__, 'value', 't\xebst value')
# An error is raised when a unicode object with non-ASCII format is
# passed as initial mimetype or content_type.
self.assertRaises(UnicodeEncodeError, HttpResponse,
- content_type=u't\xebst value')
+ content_type='t\xebst value')
# HttpResponse headers must be convertible to ASCII.
self.assertRaises(UnicodeEncodeError, HttpResponse,
- content_type=u't\xebst value')
+ content_type='t\xebst value')
# The response also converts unicode keys to strings.)
- r[u'test'] = 'testing key'
+ r['test'] = 'testing key'
l = list(r.items())
l.sort()
self.assertEqual(l[1], ('test', 'testing key'))
# It will also raise errors for keys with non-ascii data.
- self.assertRaises(UnicodeEncodeError, r.__setitem__, u't\xebst key', 'value')
+ self.assertRaises(UnicodeEncodeError, r.__setitem__, 't\xebst key', 'value')
def test_newlines_in_headers(self):
# Bug #10188: Do not allow newlines in headers (CR or LF)
@@ -276,7 +278,7 @@ class HttpResponseTests(unittest.TestCase):
#test retrieval explicitly using iter and odd inputs
r = HttpResponse()
- r.content = ['1', u'2', 3, unichr(1950)]
+ r.content = ['1', '2', 3, unichr(1950)]
result = []
my_iter = r.__iter__()
while True:
diff --git a/tests/regressiontests/i18n/contenttypes/tests.py b/tests/regressiontests/i18n/contenttypes/tests.py
index baaa6ada42..bed94da8b8 100644
--- a/tests/regressiontests/i18n/contenttypes/tests.py
+++ b/tests/regressiontests/i18n/contenttypes/tests.py
@@ -1,4 +1,5 @@
# coding: utf-8
+from __future__ import unicode_literals
import os
@@ -23,9 +24,9 @@ class ContentTypeTests(TestCase):
def test_verbose_name(self):
company_type = ContentType.objects.get(app_label='i18n', model='company')
with translation.override('en'):
- self.assertEqual(unicode(company_type), u'Company')
+ self.assertEqual(unicode(company_type), 'Company')
with translation.override('fr'):
- self.assertEqual(unicode(company_type), u'Société')
+ self.assertEqual(unicode(company_type), 'Société')
def test_field_override(self):
company_type = ContentType.objects.get(app_label='i18n', model='company')
diff --git a/tests/regressiontests/i18n/patterns/tests.py b/tests/regressiontests/i18n/patterns/tests.py
index 8ef7377ecc..73c9f56711 100644
--- a/tests/regressiontests/i18n/patterns/tests.py
+++ b/tests/regressiontests/i18n/patterns/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import os
from django.core.exceptions import ImproperlyConfigured
@@ -247,7 +249,7 @@ class URLTagTests(URLTestCaseBase):
{% language 'nl' %}{% url 'no-prefix-translated' %}{% endlanguage %}
{% language 'pt-br' %}{% url 'no-prefix-translated' %}{% endlanguage %}""")
self.assertEqual(t.render(Context({})).strip().split(),
- [u'/vertaald/', u'/traduzidos/'])
+ ['/vertaald/', '/traduzidos/'])
def test_context(self):
ctx = Context({'lang1':'nl', 'lang2':'pt-br'})
@@ -255,18 +257,18 @@ class URLTagTests(URLTestCaseBase):
{% language lang1 %}{% url 'no-prefix-translated' %}{% endlanguage %}
{% language lang2 %}{% url 'no-prefix-translated' %}{% endlanguage %}""")
self.assertEqual(tpl.render(ctx).strip().split(),
- [u'/vertaald/', u'/traduzidos/'])
+ ['/vertaald/', '/traduzidos/'])
def test_args(self):
tpl = Template("""{% load i18n %}
{% language 'nl' %}{% url 'no-prefix-translated-slug' 'apo' %}{% endlanguage %}
{% language 'pt-br' %}{% url 'no-prefix-translated-slug' 'apo' %}{% endlanguage %}""")
self.assertEqual(tpl.render(Context({})).strip().split(),
- [u'/vertaald/apo/', u'/traduzidos/apo/'])
+ ['/vertaald/apo/', '/traduzidos/apo/'])
def test_kwargs(self):
tpl = Template("""{% load i18n %}
{% language 'nl' %}{% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %}
{% language 'pt-br' %}{% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %}""")
self.assertEqual(tpl.render(Context({})).strip().split(),
- [u'/vertaald/apo/', u'/traduzidos/apo/'])
+ ['/vertaald/apo/', '/traduzidos/apo/'])
diff --git a/tests/regressiontests/i18n/tests.py b/tests/regressiontests/i18n/tests.py
index 78e41321af..f91d7c042b 100644
--- a/tests/regressiontests/i18n/tests.py
+++ b/tests/regressiontests/i18n/tests.py
@@ -1,5 +1,5 @@
# -*- encoding: utf-8 -*-
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import datetime
import decimal
@@ -62,11 +62,11 @@ class TranslationTests(TestCase):
"""
s = ugettext_lazy('Add %(name)s')
d = {'name': 'Ringo'}
- self.assertEqual(u'Add Ringo', s % d)
+ self.assertEqual('Add Ringo', s % d)
with translation.override('de', deactivate=True):
- self.assertEqual(u'Ringo hinzuf\xfcgen', s % d)
+ self.assertEqual('Ringo hinzuf\xfcgen', s % d)
with translation.override('pl'):
- self.assertEqual(u'Dodaj Ringo', s % d)
+ self.assertEqual('Dodaj Ringo', s % d)
# It should be possible to compare *_lazy objects.
s1 = ugettext_lazy('Add %(name)s')
@@ -94,10 +94,10 @@ class TranslationTests(TestCase):
trans_real._active = local()
trans_real._translations = {}
with translation.override('de'):
- self.assertEqual(pgettext("unexisting", "May"), u"May")
- self.assertEqual(pgettext("month name", "May"), u"Mai")
- self.assertEqual(pgettext("verb", "May"), u"Kann")
- self.assertEqual(npgettext("search", "%d result", "%d results", 4) % 4, u"4 Resultate")
+ self.assertEqual(pgettext("unexisting", "May"), "May")
+ self.assertEqual(pgettext("month name", "May"), "Mai")
+ self.assertEqual(pgettext("verb", "May"), "Kann")
+ self.assertEqual(npgettext("search", "%d result", "%d results", 4) % 4, "4 Resultate")
def test_template_tags_pgettext(self):
"""
@@ -224,7 +224,7 @@ class TranslationTests(TestCase):
unicode(string_concat(...)) should not raise a TypeError - #4796
"""
import django.utils.translation
- self.assertEqual(u'django', unicode(django.utils.translation.string_concat("dja", "ngo")))
+ self.assertEqual('django', unicode(django.utils.translation.string_concat("dja", "ngo")))
def test_safe_status(self):
"""
@@ -247,11 +247,11 @@ class TranslationTests(TestCase):
"""
from django.utils.translation.trans_real import translation as Trans
ca_translation = Trans('ca')
- ca_translation._catalog[u'Mac\nEOF\n'] = u'Catalan Mac\nEOF\n'
- ca_translation._catalog[u'Win\nEOF\n'] = u'Catalan Win\nEOF\n'
+ ca_translation._catalog['Mac\nEOF\n'] = 'Catalan Mac\nEOF\n'
+ ca_translation._catalog['Win\nEOF\n'] = 'Catalan Win\nEOF\n'
with translation.override('ca', deactivate=True):
- self.assertEqual(u'Catalan Mac\nEOF\n', ugettext(u'Mac\rEOF\r'))
- self.assertEqual(u'Catalan Win\nEOF\n', ugettext(u'Win\r\nEOF\r\n'))
+ self.assertEqual('Catalan Mac\nEOF\n', ugettext('Mac\rEOF\r'))
+ self.assertEqual('Catalan Win\nEOF\n', ugettext('Win\r\nEOF\r\n'))
def test_to_locale(self):
"""
@@ -332,22 +332,22 @@ class FormattingTests(TestCase):
Localization of numbers
"""
with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=False):
- self.assertEqual(u'66666.66', nformat(self.n, decimal_sep='.', decimal_pos=2, grouping=3, thousand_sep=','))
- self.assertEqual(u'66666A6', nformat(self.n, decimal_sep='A', decimal_pos=1, grouping=1, thousand_sep='B'))
- self.assertEqual(u'66666', nformat(self.n, decimal_sep='X', decimal_pos=0, grouping=1, thousand_sep='Y'))
+ self.assertEqual('66666.66', nformat(self.n, decimal_sep='.', decimal_pos=2, grouping=3, thousand_sep=','))
+ self.assertEqual('66666A6', nformat(self.n, decimal_sep='A', decimal_pos=1, grouping=1, thousand_sep='B'))
+ self.assertEqual('66666', nformat(self.n, decimal_sep='X', decimal_pos=0, grouping=1, thousand_sep='Y'))
with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True):
- self.assertEqual(u'66,666.66', nformat(self.n, decimal_sep='.', decimal_pos=2, grouping=3, thousand_sep=','))
- self.assertEqual(u'6B6B6B6B6A6', nformat(self.n, decimal_sep='A', decimal_pos=1, grouping=1, thousand_sep='B'))
- self.assertEqual(u'-66666.6', nformat(-66666.666, decimal_sep='.', decimal_pos=1))
- self.assertEqual(u'-66666.0', nformat(int('-66666'), decimal_sep='.', decimal_pos=1))
- self.assertEqual(u'10000.0', nformat(self.l, decimal_sep='.', decimal_pos=1))
+ self.assertEqual('66,666.66', nformat(self.n, decimal_sep='.', decimal_pos=2, grouping=3, thousand_sep=','))
+ self.assertEqual('6B6B6B6B6A6', nformat(self.n, decimal_sep='A', decimal_pos=1, grouping=1, thousand_sep='B'))
+ self.assertEqual('-66666.6', nformat(-66666.666, decimal_sep='.', decimal_pos=1))
+ self.assertEqual('-66666.0', nformat(int('-66666'), decimal_sep='.', decimal_pos=1))
+ self.assertEqual('10000.0', nformat(self.l, decimal_sep='.', decimal_pos=1))
# This unusual grouping/force_grouping combination may be triggered by the intcomma filter (#17414)
- self.assertEqual(u'10000', nformat(self.l, decimal_sep='.', decimal_pos=0, grouping=0, force_grouping=True))
+ self.assertEqual('10000', nformat(self.l, decimal_sep='.', decimal_pos=0, grouping=0, force_grouping=True))
# date filter
- self.assertEqual(u'31.12.2009 в 20:50', Template('{{ dt|date:"d.m.Y в H:i" }}').render(self.ctxt))
- self.assertEqual(u'⌚ 10:15', Template('{{ t|time:"⌚ H:i" }}').render(self.ctxt))
+ self.assertEqual('31.12.2009 в 20:50', Template('{{ dt|date:"d.m.Y в H:i" }}').render(self.ctxt))
+ self.assertEqual('⌚ 10:15', Template('{{ t|time:"⌚ H:i" }}').render(self.ctxt))
def test_l10n_disabled(self):
"""
@@ -356,53 +356,53 @@ class FormattingTests(TestCase):
"""
settings.USE_L10N = False
with translation.override('ca', deactivate=True):
- self.assertEqual(u'N j, Y', get_format('DATE_FORMAT'))
+ self.assertEqual('N j, Y', get_format('DATE_FORMAT'))
self.assertEqual(0, get_format('FIRST_DAY_OF_WEEK'))
- self.assertEqual(u'.', get_format('DECIMAL_SEPARATOR'))
- self.assertEqual(u'10:15 a.m.', time_format(self.t))
- self.assertEqual(u'des. 31, 2009', date_format(self.d))
- self.assertEqual(u'desembre 2009', date_format(self.d, 'YEAR_MONTH_FORMAT'))
- self.assertEqual(u'12/31/2009 8:50 p.m.', date_format(self.dt, 'SHORT_DATETIME_FORMAT'))
- self.assertEqual(u'No localizable', localize('No localizable'))
- self.assertEqual(u'66666.666', localize(self.n))
- self.assertEqual(u'99999.999', localize(self.f))
- self.assertEqual(u'10000', localize(self.l))
- self.assertEqual(u'des. 31, 2009', localize(self.d))
- self.assertEqual(u'des. 31, 2009, 8:50 p.m.', localize(self.dt))
- self.assertEqual(u'66666.666', Template('{{ n }}').render(self.ctxt))
- self.assertEqual(u'99999.999', Template('{{ f }}').render(self.ctxt))
- self.assertEqual(u'des. 31, 2009', Template('{{ d }}').render(self.ctxt))
- self.assertEqual(u'des. 31, 2009, 8:50 p.m.', Template('{{ dt }}').render(self.ctxt))
- self.assertEqual(u'66666.67', Template('{{ n|floatformat:2 }}').render(self.ctxt))
- self.assertEqual(u'100000.0', Template('{{ f|floatformat }}').render(self.ctxt))
- self.assertEqual(u'10:15 a.m.', Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt))
- self.assertEqual(u'12/31/2009', Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt))
- self.assertEqual(u'12/31/2009 8:50 p.m.', Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt))
+ self.assertEqual('.', get_format('DECIMAL_SEPARATOR'))
+ self.assertEqual('10:15 a.m.', time_format(self.t))
+ self.assertEqual('des. 31, 2009', date_format(self.d))
+ self.assertEqual('desembre 2009', date_format(self.d, 'YEAR_MONTH_FORMAT'))
+ self.assertEqual('12/31/2009 8:50 p.m.', date_format(self.dt, 'SHORT_DATETIME_FORMAT'))
+ self.assertEqual('No localizable', localize('No localizable'))
+ self.assertEqual('66666.666', localize(self.n))
+ self.assertEqual('99999.999', localize(self.f))
+ self.assertEqual('10000', localize(self.l))
+ self.assertEqual('des. 31, 2009', localize(self.d))
+ self.assertEqual('des. 31, 2009, 8:50 p.m.', localize(self.dt))
+ self.assertEqual('66666.666', Template('{{ n }}').render(self.ctxt))
+ self.assertEqual('99999.999', Template('{{ f }}').render(self.ctxt))
+ self.assertEqual('des. 31, 2009', Template('{{ d }}').render(self.ctxt))
+ self.assertEqual('des. 31, 2009, 8:50 p.m.', Template('{{ dt }}').render(self.ctxt))
+ self.assertEqual('66666.67', Template('{{ n|floatformat:2 }}').render(self.ctxt))
+ self.assertEqual('100000.0', Template('{{ f|floatformat }}').render(self.ctxt))
+ self.assertEqual('10:15 a.m.', Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt))
+ self.assertEqual('12/31/2009', Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt))
+ self.assertEqual('12/31/2009 8:50 p.m.', Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt))
form = I18nForm({
- 'decimal_field': u'66666,666',
- 'float_field': u'99999,999',
- 'date_field': u'31/12/2009',
- 'datetime_field': u'31/12/2009 20:50',
- 'time_field': u'20:50',
- 'integer_field': u'1.234',
+ 'decimal_field': '66666,666',
+ 'float_field': '99999,999',
+ 'date_field': '31/12/2009',
+ 'datetime_field': '31/12/2009 20:50',
+ 'time_field': '20:50',
+ 'integer_field': '1.234',
})
self.assertEqual(False, form.is_valid())
- self.assertEqual([u'Introdu\xefu un n\xfamero.'], form.errors['float_field'])
- self.assertEqual([u'Introdu\xefu un n\xfamero.'], form.errors['decimal_field'])
- self.assertEqual([u'Introdu\xefu una data v\xe0lida.'], form.errors['date_field'])
- self.assertEqual([u'Introdu\xefu una data/hora v\xe0lides.'], form.errors['datetime_field'])
- self.assertEqual([u'Introdu\xefu un n\xfamero sencer.'], form.errors['integer_field'])
+ self.assertEqual(['Introdu\xefu un n\xfamero.'], form.errors['float_field'])
+ self.assertEqual(['Introdu\xefu un n\xfamero.'], form.errors['decimal_field'])
+ self.assertEqual(['Introdu\xefu una data v\xe0lida.'], form.errors['date_field'])
+ self.assertEqual(['Introdu\xefu una data/hora v\xe0lides.'], form.errors['datetime_field'])
+ self.assertEqual(['Introdu\xefu un n\xfamero sencer.'], form.errors['integer_field'])
form2 = SelectDateForm({
- 'date_field_month': u'12',
- 'date_field_day': u'31',
- 'date_field_year': u'2009'
+ 'date_field_month': '12',
+ 'date_field_day': '31',
+ 'date_field_year': '2009'
})
self.assertEqual(True, form2.is_valid())
self.assertEqual(datetime.date(2009, 12, 31), form2.cleaned_data['date_field'])
self.assertHTMLEqual(
- u'<select name="mydate_month" id="id_mydate_month">\n<option value="1">gener</option>\n<option value="2">febrer</option>\n<option value="3">mar\xe7</option>\n<option value="4">abril</option>\n<option value="5">maig</option>\n<option value="6">juny</option>\n<option value="7">juliol</option>\n<option value="8">agost</option>\n<option value="9">setembre</option>\n<option value="10">octubre</option>\n<option value="11">novembre</option>\n<option value="12" selected="selected">desembre</option>\n</select>\n<select name="mydate_day" id="id_mydate_day">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31" selected="selected">31</option>\n</select>\n<select name="mydate_year" id="id_mydate_year">\n<option value="2009" selected="selected">2009</option>\n<option value="2010">2010</option>\n<option value="2011">2011</option>\n<option value="2012">2012</option>\n<option value="2013">2013</option>\n<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n</select>',
+ '<select name="mydate_month" id="id_mydate_month">\n<option value="1">gener</option>\n<option value="2">febrer</option>\n<option value="3">mar\xe7</option>\n<option value="4">abril</option>\n<option value="5">maig</option>\n<option value="6">juny</option>\n<option value="7">juliol</option>\n<option value="8">agost</option>\n<option value="9">setembre</option>\n<option value="10">octubre</option>\n<option value="11">novembre</option>\n<option value="12" selected="selected">desembre</option>\n</select>\n<select name="mydate_day" id="id_mydate_day">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31" selected="selected">31</option>\n</select>\n<select name="mydate_year" id="id_mydate_year">\n<option value="2009" selected="selected">2009</option>\n<option value="2010">2010</option>\n<option value="2011">2011</option>\n<option value="2012">2012</option>\n<option value="2013">2013</option>\n<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n</select>',
SelectDateWidget(years=range(2009, 2019)).render('mydate', datetime.date(2009, 12, 31))
)
@@ -412,8 +412,8 @@ class FormattingTests(TestCase):
# THOUSAND_SEPARATOR settings are specified
with self.settings(USE_THOUSAND_SEPARATOR=True,
NUMBER_GROUPING=1, THOUSAND_SEPARATOR='!'):
- self.assertEqual(u'66666.67', Template('{{ n|floatformat:2 }}').render(self.ctxt))
- self.assertEqual(u'100000.0', Template('{{ f|floatformat }}').render(self.ctxt))
+ self.assertEqual('66666.67', Template('{{ n|floatformat:2 }}').render(self.ctxt))
+ self.assertEqual('100000.0', Template('{{ f|floatformat }}').render(self.ctxt))
def test_false_like_locale_formats(self):
"""
@@ -455,37 +455,37 @@ class FormattingTests(TestCase):
self.assertEqual('j \d\e F \d\e Y', get_format('DATE_FORMAT'))
self.assertEqual(1, get_format('FIRST_DAY_OF_WEEK'))
self.assertEqual(',', get_format('DECIMAL_SEPARATOR'))
- self.assertEqual(u'10:15:48', time_format(self.t))
- self.assertEqual(u'31 de desembre de 2009', date_format(self.d))
- self.assertEqual(u'desembre del 2009', date_format(self.d, 'YEAR_MONTH_FORMAT'))
- self.assertEqual(u'31/12/2009 20:50', date_format(self.dt, 'SHORT_DATETIME_FORMAT'))
+ self.assertEqual('10:15:48', time_format(self.t))
+ self.assertEqual('31 de desembre de 2009', date_format(self.d))
+ self.assertEqual('desembre del 2009', date_format(self.d, 'YEAR_MONTH_FORMAT'))
+ self.assertEqual('31/12/2009 20:50', date_format(self.dt, 'SHORT_DATETIME_FORMAT'))
self.assertEqual('No localizable', localize('No localizable'))
settings.USE_THOUSAND_SEPARATOR = True
- self.assertEqual(u'66.666,666', localize(self.n))
- self.assertEqual(u'99.999,999', localize(self.f))
- self.assertEqual(u'10.000', localize(self.l))
- self.assertEqual(u'True', localize(True))
+ self.assertEqual('66.666,666', localize(self.n))
+ self.assertEqual('99.999,999', localize(self.f))
+ self.assertEqual('10.000', localize(self.l))
+ self.assertEqual('True', localize(True))
settings.USE_THOUSAND_SEPARATOR = False
- self.assertEqual(u'66666,666', localize(self.n))
- self.assertEqual(u'99999,999', localize(self.f))
- self.assertEqual(u'10000', localize(self.l))
- self.assertEqual(u'31 de desembre de 2009', localize(self.d))
- self.assertEqual(u'31 de desembre de 2009 a les 20:50', localize(self.dt))
+ self.assertEqual('66666,666', localize(self.n))
+ self.assertEqual('99999,999', localize(self.f))
+ self.assertEqual('10000', localize(self.l))
+ self.assertEqual('31 de desembre de 2009', localize(self.d))
+ self.assertEqual('31 de desembre de 2009 a les 20:50', localize(self.dt))
settings.USE_THOUSAND_SEPARATOR = True
- self.assertEqual(u'66.666,666', Template('{{ n }}').render(self.ctxt))
- self.assertEqual(u'99.999,999', Template('{{ f }}').render(self.ctxt))
- self.assertEqual(u'10.000', Template('{{ l }}').render(self.ctxt))
+ self.assertEqual('66.666,666', Template('{{ n }}').render(self.ctxt))
+ self.assertEqual('99.999,999', Template('{{ f }}').render(self.ctxt))
+ self.assertEqual('10.000', Template('{{ l }}').render(self.ctxt))
form3 = I18nForm({
- 'decimal_field': u'66.666,666',
- 'float_field': u'99.999,999',
- 'date_field': u'31/12/2009',
- 'datetime_field': u'31/12/2009 20:50',
- 'time_field': u'20:50',
- 'integer_field': u'1.234',
+ 'decimal_field': '66.666,666',
+ 'float_field': '99.999,999',
+ 'date_field': '31/12/2009',
+ 'datetime_field': '31/12/2009 20:50',
+ 'time_field': '20:50',
+ 'integer_field': '1.234',
})
self.assertEqual(True, form3.is_valid())
self.assertEqual(decimal.Decimal('66666.666'), form3.cleaned_data['decimal_field'])
@@ -496,24 +496,24 @@ class FormattingTests(TestCase):
self.assertEqual(1234, form3.cleaned_data['integer_field'])
settings.USE_THOUSAND_SEPARATOR = False
- self.assertEqual(u'66666,666', Template('{{ n }}').render(self.ctxt))
- self.assertEqual(u'99999,999', Template('{{ f }}').render(self.ctxt))
- self.assertEqual(u'31 de desembre de 2009', Template('{{ d }}').render(self.ctxt))
- self.assertEqual(u'31 de desembre de 2009 a les 20:50', Template('{{ dt }}').render(self.ctxt))
- self.assertEqual(u'66666,67', Template('{{ n|floatformat:2 }}').render(self.ctxt))
- self.assertEqual(u'100000,0', Template('{{ f|floatformat }}').render(self.ctxt))
- self.assertEqual(u'10:15:48', Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt))
- self.assertEqual(u'31/12/2009', Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt))
- self.assertEqual(u'31/12/2009 20:50', Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt))
+ self.assertEqual('66666,666', Template('{{ n }}').render(self.ctxt))
+ self.assertEqual('99999,999', Template('{{ f }}').render(self.ctxt))
+ self.assertEqual('31 de desembre de 2009', Template('{{ d }}').render(self.ctxt))
+ self.assertEqual('31 de desembre de 2009 a les 20:50', Template('{{ dt }}').render(self.ctxt))
+ self.assertEqual('66666,67', Template('{{ n|floatformat:2 }}').render(self.ctxt))
+ self.assertEqual('100000,0', Template('{{ f|floatformat }}').render(self.ctxt))
+ self.assertEqual('10:15:48', Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt))
+ self.assertEqual('31/12/2009', Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt))
+ self.assertEqual('31/12/2009 20:50', Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt))
self.assertEqual(date_format(datetime.datetime.now(), "DATE_FORMAT"), Template('{% now "DATE_FORMAT" %}').render(self.ctxt))
form4 = I18nForm({
- 'decimal_field': u'66666,666',
- 'float_field': u'99999,999',
- 'date_field': u'31/12/2009',
- 'datetime_field': u'31/12/2009 20:50',
- 'time_field': u'20:50',
- 'integer_field': u'1234',
+ 'decimal_field': '66666,666',
+ 'float_field': '99999,999',
+ 'date_field': '31/12/2009',
+ 'datetime_field': '31/12/2009 20:50',
+ 'time_field': '20:50',
+ 'integer_field': '1234',
})
self.assertEqual(True, form4.is_valid())
self.assertEqual(decimal.Decimal('66666.666'), form4.cleaned_data['decimal_field'])
@@ -524,21 +524,21 @@ class FormattingTests(TestCase):
self.assertEqual(1234, form4.cleaned_data['integer_field'])
form5 = SelectDateForm({
- 'date_field_month': u'12',
- 'date_field_day': u'31',
- 'date_field_year': u'2009'
+ 'date_field_month': '12',
+ 'date_field_day': '31',
+ 'date_field_year': '2009'
})
self.assertEqual(True, form5.is_valid())
self.assertEqual(datetime.date(2009, 12, 31), form5.cleaned_data['date_field'])
self.assertHTMLEqual(
- u'<select name="mydate_day" id="id_mydate_day">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31" selected="selected">31</option>\n</select>\n<select name="mydate_month" id="id_mydate_month">\n<option value="1">gener</option>\n<option value="2">febrer</option>\n<option value="3">mar\xe7</option>\n<option value="4">abril</option>\n<option value="5">maig</option>\n<option value="6">juny</option>\n<option value="7">juliol</option>\n<option value="8">agost</option>\n<option value="9">setembre</option>\n<option value="10">octubre</option>\n<option value="11">novembre</option>\n<option value="12" selected="selected">desembre</option>\n</select>\n<select name="mydate_year" id="id_mydate_year">\n<option value="2009" selected="selected">2009</option>\n<option value="2010">2010</option>\n<option value="2011">2011</option>\n<option value="2012">2012</option>\n<option value="2013">2013</option>\n<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n</select>',
+ '<select name="mydate_day" id="id_mydate_day">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31" selected="selected">31</option>\n</select>\n<select name="mydate_month" id="id_mydate_month">\n<option value="1">gener</option>\n<option value="2">febrer</option>\n<option value="3">mar\xe7</option>\n<option value="4">abril</option>\n<option value="5">maig</option>\n<option value="6">juny</option>\n<option value="7">juliol</option>\n<option value="8">agost</option>\n<option value="9">setembre</option>\n<option value="10">octubre</option>\n<option value="11">novembre</option>\n<option value="12" selected="selected">desembre</option>\n</select>\n<select name="mydate_year" id="id_mydate_year">\n<option value="2009" selected="selected">2009</option>\n<option value="2010">2010</option>\n<option value="2011">2011</option>\n<option value="2012">2012</option>\n<option value="2013">2013</option>\n<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n</select>',
SelectDateWidget(years=range(2009, 2019)).render('mydate', datetime.date(2009, 12, 31))
)
# Russian locale (with E as month)
with translation.override('ru', deactivate=True):
self.assertHTMLEqual(
- u'<select name="mydate_day" id="id_mydate_day">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31" selected="selected">31</option>\n</select>\n<select name="mydate_month" id="id_mydate_month">\n<option value="1">\u042f\u043d\u0432\u0430\u0440\u044c</option>\n<option value="2">\u0424\u0435\u0432\u0440\u0430\u043b\u044c</option>\n<option value="3">\u041c\u0430\u0440\u0442</option>\n<option value="4">\u0410\u043f\u0440\u0435\u043b\u044c</option>\n<option value="5">\u041c\u0430\u0439</option>\n<option value="6">\u0418\u044e\u043d\u044c</option>\n<option value="7">\u0418\u044e\u043b\u044c</option>\n<option value="8">\u0410\u0432\u0433\u0443\u0441\u0442</option>\n<option value="9">\u0421\u0435\u043d\u0442\u044f\u0431\u0440\u044c</option>\n<option value="10">\u041e\u043a\u0442\u044f\u0431\u0440\u044c</option>\n<option value="11">\u041d\u043e\u044f\u0431\u0440\u044c</option>\n<option value="12" selected="selected">\u0414\u0435\u043a\u0430\u0431\u0440\u044c</option>\n</select>\n<select name="mydate_year" id="id_mydate_year">\n<option value="2009" selected="selected">2009</option>\n<option value="2010">2010</option>\n<option value="2011">2011</option>\n<option value="2012">2012</option>\n<option value="2013">2013</option>\n<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n</select>',
+ '<select name="mydate_day" id="id_mydate_day">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31" selected="selected">31</option>\n</select>\n<select name="mydate_month" id="id_mydate_month">\n<option value="1">\u042f\u043d\u0432\u0430\u0440\u044c</option>\n<option value="2">\u0424\u0435\u0432\u0440\u0430\u043b\u044c</option>\n<option value="3">\u041c\u0430\u0440\u0442</option>\n<option value="4">\u0410\u043f\u0440\u0435\u043b\u044c</option>\n<option value="5">\u041c\u0430\u0439</option>\n<option value="6">\u0418\u044e\u043d\u044c</option>\n<option value="7">\u0418\u044e\u043b\u044c</option>\n<option value="8">\u0410\u0432\u0433\u0443\u0441\u0442</option>\n<option value="9">\u0421\u0435\u043d\u0442\u044f\u0431\u0440\u044c</option>\n<option value="10">\u041e\u043a\u0442\u044f\u0431\u0440\u044c</option>\n<option value="11">\u041d\u043e\u044f\u0431\u0440\u044c</option>\n<option value="12" selected="selected">\u0414\u0435\u043a\u0430\u0431\u0440\u044c</option>\n</select>\n<select name="mydate_year" id="id_mydate_year">\n<option value="2009" selected="selected">2009</option>\n<option value="2010">2010</option>\n<option value="2011">2011</option>\n<option value="2012">2012</option>\n<option value="2013">2013</option>\n<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n</select>',
SelectDateWidget(years=range(2009, 2019)).render('mydate', datetime.date(2009, 12, 31))
)
@@ -547,45 +547,45 @@ class FormattingTests(TestCase):
self.assertEqual('N j, Y', get_format('DATE_FORMAT'))
self.assertEqual(0, get_format('FIRST_DAY_OF_WEEK'))
self.assertEqual('.', get_format('DECIMAL_SEPARATOR'))
- self.assertEqual(u'Dec. 31, 2009', date_format(self.d))
- self.assertEqual(u'December 2009', date_format(self.d, 'YEAR_MONTH_FORMAT'))
- self.assertEqual(u'12/31/2009 8:50 p.m.', date_format(self.dt, 'SHORT_DATETIME_FORMAT'))
- self.assertEqual(u'No localizable', localize('No localizable'))
+ self.assertEqual('Dec. 31, 2009', date_format(self.d))
+ self.assertEqual('December 2009', date_format(self.d, 'YEAR_MONTH_FORMAT'))
+ self.assertEqual('12/31/2009 8:50 p.m.', date_format(self.dt, 'SHORT_DATETIME_FORMAT'))
+ self.assertEqual('No localizable', localize('No localizable'))
settings.USE_THOUSAND_SEPARATOR = True
- self.assertEqual(u'66,666.666', localize(self.n))
- self.assertEqual(u'99,999.999', localize(self.f))
- self.assertEqual(u'10,000', localize(self.l))
+ self.assertEqual('66,666.666', localize(self.n))
+ self.assertEqual('99,999.999', localize(self.f))
+ self.assertEqual('10,000', localize(self.l))
settings.USE_THOUSAND_SEPARATOR = False
- self.assertEqual(u'66666.666', localize(self.n))
- self.assertEqual(u'99999.999', localize(self.f))
- self.assertEqual(u'10000', localize(self.l))
- self.assertEqual(u'Dec. 31, 2009', localize(self.d))
- self.assertEqual(u'Dec. 31, 2009, 8:50 p.m.', localize(self.dt))
+ self.assertEqual('66666.666', localize(self.n))
+ self.assertEqual('99999.999', localize(self.f))
+ self.assertEqual('10000', localize(self.l))
+ self.assertEqual('Dec. 31, 2009', localize(self.d))
+ self.assertEqual('Dec. 31, 2009, 8:50 p.m.', localize(self.dt))
settings.USE_THOUSAND_SEPARATOR = True
- self.assertEqual(u'66,666.666', Template('{{ n }}').render(self.ctxt))
- self.assertEqual(u'99,999.999', Template('{{ f }}').render(self.ctxt))
- self.assertEqual(u'10,000', Template('{{ l }}').render(self.ctxt))
+ self.assertEqual('66,666.666', Template('{{ n }}').render(self.ctxt))
+ self.assertEqual('99,999.999', Template('{{ f }}').render(self.ctxt))
+ self.assertEqual('10,000', Template('{{ l }}').render(self.ctxt))
settings.USE_THOUSAND_SEPARATOR = False
- self.assertEqual(u'66666.666', Template('{{ n }}').render(self.ctxt))
- self.assertEqual(u'99999.999', Template('{{ f }}').render(self.ctxt))
- self.assertEqual(u'Dec. 31, 2009', Template('{{ d }}').render(self.ctxt))
- self.assertEqual(u'Dec. 31, 2009, 8:50 p.m.', Template('{{ dt }}').render(self.ctxt))
- self.assertEqual(u'66666.67', Template('{{ n|floatformat:2 }}').render(self.ctxt))
- self.assertEqual(u'100000.0', Template('{{ f|floatformat }}').render(self.ctxt))
- self.assertEqual(u'12/31/2009', Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt))
- self.assertEqual(u'12/31/2009 8:50 p.m.', Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt))
+ self.assertEqual('66666.666', Template('{{ n }}').render(self.ctxt))
+ self.assertEqual('99999.999', Template('{{ f }}').render(self.ctxt))
+ self.assertEqual('Dec. 31, 2009', Template('{{ d }}').render(self.ctxt))
+ self.assertEqual('Dec. 31, 2009, 8:50 p.m.', Template('{{ dt }}').render(self.ctxt))
+ self.assertEqual('66666.67', Template('{{ n|floatformat:2 }}').render(self.ctxt))
+ self.assertEqual('100000.0', Template('{{ f|floatformat }}').render(self.ctxt))
+ self.assertEqual('12/31/2009', Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt))
+ self.assertEqual('12/31/2009 8:50 p.m.', Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt))
form5 = I18nForm({
- 'decimal_field': u'66666.666',
- 'float_field': u'99999.999',
- 'date_field': u'12/31/2009',
- 'datetime_field': u'12/31/2009 20:50',
- 'time_field': u'20:50',
- 'integer_field': u'1234',
+ 'decimal_field': '66666.666',
+ 'float_field': '99999.999',
+ 'date_field': '12/31/2009',
+ 'datetime_field': '12/31/2009 20:50',
+ 'time_field': '20:50',
+ 'integer_field': '1234',
})
self.assertEqual(True, form5.is_valid())
self.assertEqual(decimal.Decimal('66666.666'), form5.cleaned_data['decimal_field'])
@@ -596,14 +596,14 @@ class FormattingTests(TestCase):
self.assertEqual(1234, form5.cleaned_data['integer_field'])
form6 = SelectDateForm({
- 'date_field_month': u'12',
- 'date_field_day': u'31',
- 'date_field_year': u'2009'
+ 'date_field_month': '12',
+ 'date_field_day': '31',
+ 'date_field_year': '2009'
})
self.assertEqual(True, form6.is_valid())
self.assertEqual(datetime.date(2009, 12, 31), form6.cleaned_data['date_field'])
self.assertHTMLEqual(
- u'<select name="mydate_month" id="id_mydate_month">\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12" selected="selected">December</option>\n</select>\n<select name="mydate_day" id="id_mydate_day">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31" selected="selected">31</option>\n</select>\n<select name="mydate_year" id="id_mydate_year">\n<option value="2009" selected="selected">2009</option>\n<option value="2010">2010</option>\n<option value="2011">2011</option>\n<option value="2012">2012</option>\n<option value="2013">2013</option>\n<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n</select>',
+ '<select name="mydate_month" id="id_mydate_month">\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12" selected="selected">December</option>\n</select>\n<select name="mydate_day" id="id_mydate_day">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31" selected="selected">31</option>\n</select>\n<select name="mydate_year" id="id_mydate_year">\n<option value="2009" selected="selected">2009</option>\n<option value="2010">2010</option>\n<option value="2011">2011</option>\n<option value="2012">2012</option>\n<option value="2013">2013</option>\n<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n</select>',
SelectDateWidget(years=range(2009, 2019)).render('mydate', datetime.date(2009, 12, 31))
)
@@ -613,9 +613,9 @@ class FormattingTests(TestCase):
"""
with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True):
with translation.override('de-at', deactivate=True):
- self.assertEqual(u'66.666,666', Template('{{ n }}').render(self.ctxt))
+ self.assertEqual('66.666,666', Template('{{ n }}').render(self.ctxt))
with translation.override('es-us', deactivate=True):
- self.assertEqual(u'31 de diciembre de 2009', date_format(self.d))
+ self.assertEqual('31 de diciembre de 2009', date_format(self.d))
def test_localized_input(self):
"""
@@ -624,7 +624,7 @@ class FormattingTests(TestCase):
settings.USE_L10N = True
with translation.override('de-at', deactivate=True):
form6 = CompanyForm({
- 'name': u'acme',
+ 'name': 'acme',
'date_added': datetime.datetime(2009, 12, 31, 6, 0, 0),
'cents_paid': decimal.Decimal('59.47'),
'products_delivered': 12000,
@@ -632,13 +632,13 @@ class FormattingTests(TestCase):
self.assertEqual(True, form6.is_valid())
self.assertHTMLEqual(
form6.as_ul(),
- u'<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" value="acme" maxlength="50" /></li>\n<li><label for="id_date_added">Date added:</label> <input type="text" name="date_added" value="31.12.2009 06:00:00" id="id_date_added" /></li>\n<li><label for="id_cents_paid">Cents paid:</label> <input type="text" name="cents_paid" value="59,47" id="id_cents_paid" /></li>\n<li><label for="id_products_delivered">Products delivered:</label> <input type="text" name="products_delivered" value="12000" id="id_products_delivered" /></li>'
+ '<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" value="acme" maxlength="50" /></li>\n<li><label for="id_date_added">Date added:</label> <input type="text" name="date_added" value="31.12.2009 06:00:00" id="id_date_added" /></li>\n<li><label for="id_cents_paid">Cents paid:</label> <input type="text" name="cents_paid" value="59,47" id="id_cents_paid" /></li>\n<li><label for="id_products_delivered">Products delivered:</label> <input type="text" name="products_delivered" value="12000" id="id_products_delivered" /></li>'
)
self.assertEqual(localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)), '31.12.2009 06:00:00')
self.assertEqual(datetime.datetime(2009, 12, 31, 6, 0, 0), form6.cleaned_data['date_added'])
with self.settings(USE_THOUSAND_SEPARATOR=True):
# Checking for the localized "products_delivered" field
- self.assertTrue(u'<input type="text" name="products_delivered" value="12.000" id="id_products_delivered" />' in form6.as_ul())
+ self.assertTrue('<input type="text" name="products_delivered" value="12.000" id="id_products_delivered" />' in form6.as_ul())
def test_iter_format_modules(self):
"""
@@ -826,9 +826,9 @@ class MiscTests(TestCase):
t_sing = Template("{% load i18n %}{% blocktrans %}The result was {{ percent }}%{% endblocktrans %}")
t_plur = Template("{% load i18n %}{% blocktrans count num as number %}{{ percent }}% represents {{ num }} object{% plural %}{{ percent }}% represents {{ num }} objects{% endblocktrans %}")
with translation.override('de'):
- self.assertEqual(t_sing.render(Context({'percent': 42})), u'Das Ergebnis war 42%')
- self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 1})), u'42% stellt 1 Objekt dar')
- self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 4})), u'42% stellt 4 Objekte dar')
+ self.assertEqual(t_sing.render(Context({'percent': 42})), 'Das Ergebnis war 42%')
+ self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 1})), '42% stellt 1 Objekt dar')
+ self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 4})), '42% stellt 4 Objekte dar')
class ResolutionOrderI18NTests(TestCase):
@@ -895,9 +895,9 @@ class TestModels(TestCase):
def test_safestr(self):
c = Company(cents_paid=12, products_delivered=1)
- c.name = SafeUnicode(u'Iñtërnâtiônàlizætiøn1')
+ c.name = SafeUnicode('Iñtërnâtiônàlizætiøn1')
c.save()
- c.name = SafeString(u'Iñtërnâtiônàlizætiøn1'.encode('utf-8'))
+ c.name = SafeString('Iñtërnâtiônàlizætiøn1'.encode('utf-8'))
c.save()
@@ -905,7 +905,7 @@ class TestLanguageInfo(TestCase):
def test_localized_language_info(self):
li = get_language_info('de')
self.assertEqual(li['code'], 'de')
- self.assertEqual(li['name_local'], u'Deutsch')
+ self.assertEqual(li['name_local'], 'Deutsch')
self.assertEqual(li['name'], 'German')
self.assertEqual(li['bidi'], False)
diff --git a/tests/regressiontests/inline_formsets/tests.py b/tests/regressiontests/inline_formsets/tests.py
index 59187ee6d0..8ad84f221f 100644
--- a/tests/regressiontests/inline_formsets/tests.py
+++ b/tests/regressiontests/inline_formsets/tests.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from django.forms.models import inlineformset_factory
from django.test import TestCase
@@ -13,13 +13,13 @@ class DeletionTests(TestCase):
poet = Poet.objects.create(name='test')
poem = poet.poem_set.create(name='test poem')
data = {
- 'poem_set-TOTAL_FORMS': u'1',
- 'poem_set-INITIAL_FORMS': u'1',
- 'poem_set-MAX_NUM_FORMS': u'0',
+ 'poem_set-TOTAL_FORMS': '1',
+ 'poem_set-INITIAL_FORMS': '1',
+ 'poem_set-MAX_NUM_FORMS': '0',
'poem_set-0-id': str(poem.pk),
'poem_set-0-poet': str(poet.pk),
- 'poem_set-0-name': u'test',
- 'poem_set-0-DELETE': u'on',
+ 'poem_set-0-name': 'test',
+ 'poem_set-0-DELETE': 'on',
}
formset = PoemFormSet(data, instance=poet)
formset.save()
@@ -34,12 +34,12 @@ class DeletionTests(TestCase):
PoemFormSet = inlineformset_factory(Poet, Poem, can_delete=True)
poet = Poet.objects.create(name='test')
data = {
- 'poem_set-TOTAL_FORMS': u'1',
- 'poem_set-INITIAL_FORMS': u'0',
- 'poem_set-MAX_NUM_FORMS': u'0',
- 'poem_set-0-id': u'',
- 'poem_set-0-poem': u'1',
- 'poem_set-0-name': u'x' * 1000,
+ 'poem_set-TOTAL_FORMS': '1',
+ 'poem_set-INITIAL_FORMS': '0',
+ 'poem_set-MAX_NUM_FORMS': '0',
+ 'poem_set-0-id': '',
+ 'poem_set-0-poem': '1',
+ 'poem_set-0-name': 'x' * 1000,
}
formset = PoemFormSet(data, instance=poet)
# Make sure this form doesn't pass validation.
@@ -63,12 +63,12 @@ class DeletionTests(TestCase):
poet = Poet.objects.create(name='test')
poem = poet.poem_set.create(name='test poem')
data = {
- 'poem_set-TOTAL_FORMS': u'1',
- 'poem_set-INITIAL_FORMS': u'1',
- 'poem_set-MAX_NUM_FORMS': u'0',
+ 'poem_set-TOTAL_FORMS': '1',
+ 'poem_set-INITIAL_FORMS': '1',
+ 'poem_set-MAX_NUM_FORMS': '0',
'poem_set-0-id': unicode(poem.id),
'poem_set-0-poem': unicode(poem.id),
- 'poem_set-0-name': u'x' * 1000,
+ 'poem_set-0-name': 'x' * 1000,
}
formset = PoemFormSet(data, instance=poet)
# Make sure this form doesn't pass validation.
@@ -90,14 +90,14 @@ class DeletionTests(TestCase):
"""
# exclude some required field from the forms
ChildFormSet = inlineformset_factory(School, Child, exclude=['father', 'mother'])
- school = School.objects.create(name=u'test')
- mother = Parent.objects.create(name=u'mother')
- father = Parent.objects.create(name=u'father')
+ school = School.objects.create(name='test')
+ mother = Parent.objects.create(name='mother')
+ father = Parent.objects.create(name='father')
data = {
- 'child_set-TOTAL_FORMS': u'1',
- 'child_set-INITIAL_FORMS': u'0',
- 'child_set-MAX_NUM_FORMS': u'0',
- 'child_set-0-name': u'child',
+ 'child_set-TOTAL_FORMS': '1',
+ 'child_set-INITIAL_FORMS': '0',
+ 'child_set-MAX_NUM_FORMS': '0',
+ 'child_set-0-name': 'child',
}
formset = ChildFormSet(data, instance=school)
self.assertEqual(formset.is_valid(), True)
diff --git a/tests/regressiontests/introspection/models.py b/tests/regressiontests/introspection/models.py
index 02a8d71549..3ca80c5aab 100644
--- a/tests/regressiontests/introspection/models.py
+++ b/tests/regressiontests/introspection/models.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.db import models
@@ -11,7 +13,7 @@ class Reporter(models.Model):
unique_together = ('first_name', '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 Article(models.Model):
headline = models.CharField(max_length=100)
diff --git a/tests/regressiontests/introspection/tests.py b/tests/regressiontests/introspection/tests.py
index ca58f04494..06736a68cb 100644
--- a/tests/regressiontests/introspection/tests.py
+++ b/tests/regressiontests/introspection/tests.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import,unicode_literals
from functools import update_wrapper
@@ -125,12 +125,12 @@ class IntrospectionTests(TestCase):
def test_get_key_columns(self):
cursor = connection.cursor()
key_columns = connection.introspection.get_key_columns(cursor, Article._meta.db_table)
- self.assertEqual(key_columns, [(u'reporter_id', Reporter._meta.db_table, u'id')])
+ self.assertEqual(key_columns, [('reporter_id', Reporter._meta.db_table, 'id')])
def test_get_primary_key_column(self):
cursor = connection.cursor()
primary_key_column = connection.introspection.get_primary_key_column(cursor, Article._meta.db_table)
- self.assertEqual(primary_key_column, u'id')
+ self.assertEqual(primary_key_column, 'id')
def test_get_indexes(self):
cursor = connection.cursor()
diff --git a/tests/regressiontests/localflavor/ar/tests.py b/tests/regressiontests/localflavor/ar/tests.py
index b48fb7cff3..0731c3ce9b 100644
--- a/tests/regressiontests/localflavor/ar/tests.py
+++ b/tests/regressiontests/localflavor/ar/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.ar.forms import (ARProvinceSelect,
ARPostalCodeField, ARDNIField, ARCUITField)
@@ -7,7 +9,7 @@ from django.test import SimpleTestCase
class ARLocalFlavorTests(SimpleTestCase):
def test_ARProvinceSelect(self):
f = ARProvinceSelect()
- out = u'''<select name="provincias">
+ out = '''<select name="provincias">
<option value="B">Buenos Aires</option>
<option value="K">Catamarca</option>
<option value="H">Chaco</option>
@@ -36,16 +38,16 @@ class ARLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('provincias', 'A'), out)
def test_ARPostalCodeField(self):
- error_format = [u'Enter a postal code in the format NNNN or ANNNNAAA.']
- error_atmost = [u'Ensure this value has at most 8 characters (it has 9).']
- error_atleast = [u'Ensure this value has at least 4 characters (it has 3).']
+ error_format = ['Enter a postal code in the format NNNN or ANNNNAAA.']
+ error_atmost = ['Ensure this value has at most 8 characters (it has 9).']
+ error_atleast = ['Ensure this value has at least 4 characters (it has 3).']
valid = {
'5000': '5000',
'C1064AAB': 'C1064AAB',
'c1064AAB': 'C1064AAB',
'C1064aab': 'C1064AAB',
'4400': '4400',
- u'C1064AAB': 'C1064AAB',
+ 'C1064AAB': 'C1064AAB',
}
invalid = {
'C1064AABB': error_atmost + error_format,
@@ -58,13 +60,13 @@ class ARLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(ARPostalCodeField, valid, invalid)
def test_ARDNIField(self):
- error_length = [u'This field requires 7 or 8 digits.']
- error_digitsonly = [u'This field requires only numbers.']
+ error_length = ['This field requires 7 or 8 digits.']
+ error_digitsonly = ['This field requires only numbers.']
valid = {
'20123456': '20123456',
'20.123.456': '20123456',
- u'20123456': '20123456',
- u'20.123.456': '20123456',
+ '20123456': '20123456',
+ '20.123.456': '20123456',
'20.123456': '20123456',
'9123456': '9123456',
'9.123.456': '9123456',
@@ -77,11 +79,11 @@ class ARLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(ARDNIField, valid, invalid)
def test_ARCUITField(self):
- error_format = [u'Enter a valid CUIT in XX-XXXXXXXX-X or XXXXXXXXXXXX format.']
- error_invalid = [u'Invalid CUIT.']
+ error_format = ['Enter a valid CUIT in XX-XXXXXXXX-X or XXXXXXXXXXXX format.']
+ error_invalid = ['Invalid CUIT.']
valid = {
'20-10123456-9': '20-10123456-9',
- u'20-10123456-9': '20-10123456-9',
+ '20-10123456-9': '20-10123456-9',
'27-10345678-4': '27-10345678-4',
'20101234569': '20-10123456-9',
'27103456784': '27-10345678-4',
@@ -93,6 +95,6 @@ class ARLocalFlavorTests(SimpleTestCase):
'20-10123456-': error_format,
'20-10123456-5': error_invalid,
'27-10345678-1': error_invalid,
- u'27-10345678-1': error_invalid,
+ '27-10345678-1': error_invalid,
}
self.assertFieldOutput(ARCUITField, valid, invalid)
diff --git a/tests/regressiontests/localflavor/at/tests.py b/tests/regressiontests/localflavor/at/tests.py
index d47e970123..9123ba4e88 100644
--- a/tests/regressiontests/localflavor/at/tests.py
+++ b/tests/regressiontests/localflavor/at/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.at.forms import (ATZipCodeField, ATStateSelect,
ATSocialSecurityNumberField)
@@ -7,7 +9,7 @@ from django.test import SimpleTestCase
class ATLocalFlavorTests(SimpleTestCase):
def test_ATStateSelect(self):
f = ATStateSelect()
- out = u'''<select name="bundesland">
+ out = '''<select name="bundesland">
<option value="BL">Burgenland</option>
<option value="KA">Carinthia</option>
<option value="NO">Lower Austria</option>
@@ -21,7 +23,7 @@ class ATLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('bundesland', 'WI'), out)
def test_ATZipCodeField(self):
- error_format = [u'Enter a zip code in the format XXXX.']
+ error_format = ['Enter a zip code in the format XXXX.']
valid = {
'1150': '1150',
'4020': '4020',
@@ -36,7 +38,7 @@ class ATLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(ATZipCodeField, valid, invalid)
def test_ATSocialSecurityNumberField(self):
- error_format = [u'Enter a valid Austrian Social Security Number in XXXX XXXXXX format.']
+ error_format = ['Enter a valid Austrian Social Security Number in XXXX XXXXXX format.']
valid = {
'1237 010180': '1237 010180',
}
diff --git a/tests/regressiontests/localflavor/au/tests.py b/tests/regressiontests/localflavor/au/tests.py
index 42673a902b..69472f0935 100644
--- a/tests/regressiontests/localflavor/au/tests.py
+++ b/tests/regressiontests/localflavor/au/tests.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import re
@@ -44,9 +44,9 @@ class AULocalflavorTests(SimpleTestCase):
form = AustralianPlaceForm({'state':'NSW', 'name':'Wollongong'})
self.assertFalse(form.is_valid())
self.assertEqual(
- form.errors['state_required'], [u'This field is required.'])
+ form.errors['state_required'], ['This field is required.'])
self.assertEqual(
- form.errors['postcode_required'], [u'This field is required.'])
+ form.errors['postcode_required'], ['This field is required.'])
def test_field_blank_option(self):
""" Test that the empty option is there. """
@@ -66,7 +66,7 @@ class AULocalflavorTests(SimpleTestCase):
def test_AUStateSelect(self):
f = AUStateSelect()
- out = u'''<select name="state">
+ out = '''<select name="state">
<option value="ACT">Australian Capital Territory</option>
<option value="NSW" selected="selected">New South Wales</option>
<option value="NT">Northern Territory</option>
@@ -79,19 +79,19 @@ class AULocalflavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('state', 'NSW'), out)
def test_AUPostCodeField(self):
- error_format = [u'Enter a 4 digit postcode.']
+ error_format = ['Enter a 4 digit postcode.']
valid = {
'1234': '1234',
'2000': '2000',
}
invalid = {
'abcd': error_format,
- '20001': [u'Ensure this value has at most 4 characters (it has 5).'] + error_format,
+ '20001': ['Ensure this value has at most 4 characters (it has 5).'] + error_format,
}
self.assertFieldOutput(AUPostCodeField, valid, invalid)
def test_AUPhoneNumberField(self):
- error_format = [u'Phone numbers must contain 10 digits.']
+ error_format = ['Phone numbers must contain 10 digits.']
valid = {
'1234567890': '1234567890',
'0213456789': '0213456789',
diff --git a/tests/regressiontests/localflavor/be/tests.py b/tests/regressiontests/localflavor/be/tests.py
index 6cfdfb3ffa..69f77eb35f 100644
--- a/tests/regressiontests/localflavor/be/tests.py
+++ b/tests/regressiontests/localflavor/be/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.be.forms import (BEPostalCodeField,
BEPhoneNumberField, BERegionSelect, BEProvinceSelect)
@@ -6,10 +8,10 @@ from django.test import SimpleTestCase
class BELocalFlavorTests(SimpleTestCase):
def test_BEPostalCodeField(self):
- error_format = [u'Enter a valid postal code in the range and format 1XXX - 9XXX.']
+ error_format = ['Enter a valid postal code in the range and format 1XXX - 9XXX.']
valid = {
- u'1451': '1451',
- u'2540': '2540',
+ '1451': '1451',
+ '2540': '2540',
}
invalid = {
'0287': error_format,
@@ -28,17 +30,17 @@ class BELocalFlavorTests(SimpleTestCase):
'0xxxxxxxx or 04xxxxxxxx.')
]
valid = {
- u'01 234 56 78': '01 234 56 78',
- u'01/234.56.78': '01/234.56.78',
- u'01.234.56.78': '01.234.56.78',
- u'012 34 56 78': '012 34 56 78',
- u'012/34.56.78': '012/34.56.78',
- u'012.34.56.78': '012.34.56.78',
- u'0412 34 56 78': '0412 34 56 78',
- u'0412/34.56.78': '0412/34.56.78',
- u'0412.34.56.78': '0412.34.56.78',
- u'012345678': '012345678',
- u'0412345678': '0412345678',
+ '01 234 56 78': '01 234 56 78',
+ '01/234.56.78': '01/234.56.78',
+ '01.234.56.78': '01.234.56.78',
+ '012 34 56 78': '012 34 56 78',
+ '012/34.56.78': '012/34.56.78',
+ '012.34.56.78': '012.34.56.78',
+ '0412 34 56 78': '0412 34 56 78',
+ '0412/34.56.78': '0412/34.56.78',
+ '0412.34.56.78': '0412.34.56.78',
+ '012345678': '012345678',
+ '0412345678': '0412345678',
}
invalid = {
'01234567': error_format,
@@ -54,7 +56,7 @@ class BELocalFlavorTests(SimpleTestCase):
def test_BERegionSelect(self):
f = BERegionSelect()
- out = u'''<select name="regions">
+ out = '''<select name="regions">
<option value="BRU">Brussels Capital Region</option>
<option value="VLG" selected="selected">Flemish Region</option>
<option value="WAL">Wallonia</option>
@@ -63,7 +65,7 @@ class BELocalFlavorTests(SimpleTestCase):
def test_BEProvinceSelect(self):
f = BEProvinceSelect()
- out = u'''<select name="provinces">
+ out = '''<select name="provinces">
<option value="VAN">Antwerp</option>
<option value="BRU">Brussels</option>
<option value="VOV">East Flanders</option>
diff --git a/tests/regressiontests/localflavor/br/tests.py b/tests/regressiontests/localflavor/br/tests.py
index 5777bc3500..abee2d7336 100644
--- a/tests/regressiontests/localflavor/br/tests.py
+++ b/tests/regressiontests/localflavor/br/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.br.forms import (BRZipCodeField,
BRCNPJField, BRCPFField, BRPhoneNumberField, BRStateSelect,
BRStateChoiceField)
@@ -7,7 +9,7 @@ from django.test import SimpleTestCase
class BRLocalFlavorTests(SimpleTestCase):
def test_BRZipCodeField(self):
- error_format = [u'Enter a zip code in the format XXXXX-XXX.']
+ error_format = ['Enter a zip code in the format XXXXX-XXX.']
valid = {
'12345-123': '12345-123',
}
@@ -21,8 +23,8 @@ class BRLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(BRZipCodeField, valid, invalid)
def test_BRCNPJField(self):
- error_format = [u'Invalid CNPJ number.']
- error_numbersonly = [u'This field requires only numbers.']
+ error_format = ['Invalid CNPJ number.']
+ error_numbersonly = ['This field requires only numbers.']
valid = {
'64.132.916/0001-88': '64.132.916/0001-88',
'64-132-916/0001-88': '64-132-916/0001-88',
@@ -37,11 +39,11 @@ class BRLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(BRCNPJField, valid, invalid)
def test_BRCPFField(self):
- error_format = [u'Invalid CPF number.']
- error_numbersonly = [u'This field requires only numbers.']
- error_atmost_chars = [u'Ensure this value has at most 14 characters (it has 15).']
- error_atleast_chars = [u'Ensure this value has at least 11 characters (it has 10).']
- error_atmost = [u'This field requires at most 11 digits or 14 characters.']
+ error_format = ['Invalid CPF number.']
+ error_numbersonly = ['This field requires only numbers.']
+ error_atmost_chars = ['Ensure this value has at most 14 characters (it has 15).']
+ error_atleast_chars = ['Ensure this value has at least 11 characters (it has 10).']
+ error_atmost = ['This field requires at most 11 digits or 14 characters.']
valid = {
'663.256.017-26': '663.256.017-26',
'66325601726': '66325601726',
@@ -62,21 +64,21 @@ class BRLocalFlavorTests(SimpleTestCase):
def test_BRPhoneNumberField(self):
# TODO: this doesn't test for any invalid inputs.
valid = {
- '41-3562-3464': u'41-3562-3464',
- '4135623464': u'41-3562-3464',
- '41 3562-3464': u'41-3562-3464',
- '41 3562 3464': u'41-3562-3464',
- '(41) 3562 3464': u'41-3562-3464',
- '41.3562.3464': u'41-3562-3464',
- '41.3562-3464': u'41-3562-3464',
- ' (41) 3562.3464': u'41-3562-3464',
+ '41-3562-3464': '41-3562-3464',
+ '4135623464': '41-3562-3464',
+ '41 3562-3464': '41-3562-3464',
+ '41 3562 3464': '41-3562-3464',
+ '(41) 3562 3464': '41-3562-3464',
+ '41.3562.3464': '41-3562-3464',
+ '41.3562-3464': '41-3562-3464',
+ ' (41) 3562.3464': '41-3562-3464',
}
invalid = {}
self.assertFieldOutput(BRPhoneNumberField, valid, invalid)
def test_BRStateSelect(self):
f = BRStateSelect()
- out = u'''<select name="states">
+ out = '''<select name="states">
<option value="AC">Acre</option>
<option value="AL">Alagoas</option>
<option value="AP">Amap\xe1</option>
@@ -108,7 +110,7 @@ class BRLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('states', 'PR'), out)
def test_BRStateChoiceField(self):
- error_invalid = [u'Select a valid brazilian state. That state is not one of the available states.']
+ error_invalid = ['Select a valid brazilian state. That state is not one of the available states.']
valid = {
'AC': 'AC',
'AL': 'AL',
diff --git a/tests/regressiontests/localflavor/ca/tests.py b/tests/regressiontests/localflavor/ca/tests.py
index 903321b2cd..8f0eb9c702 100644
--- a/tests/regressiontests/localflavor/ca/tests.py
+++ b/tests/regressiontests/localflavor/ca/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import warnings
from django.contrib.localflavor.ca.forms import (CAPostalCodeField,
@@ -21,7 +23,7 @@ class CALocalFlavorTests(SimpleTestCase):
def test_CAProvinceSelect(self):
f = CAProvinceSelect()
- out = u'''<select name="province">
+ out = '''<select name="province">
<option value="AB" selected="selected">Alberta</option>
<option value="BC">British Columbia</option>
<option value="MB">Manitoba</option>
@@ -39,7 +41,7 @@ class CALocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('province', 'AB'), out)
def test_CAPostalCodeField(self):
- error_format = [u'Enter a postal code in the format XXX XXX.']
+ error_format = ['Enter a postal code in the format XXX XXX.']
valid = {
'T2S 2H7': 'T2S 2H7',
'T2S 2W7': 'T2S 2W7',
@@ -69,7 +71,7 @@ class CALocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(CAPostalCodeField, valid, invalid)
def test_CAPhoneNumberField(self):
- error_format = [u'Phone numbers must be in XXX-XXX-XXXX format.']
+ error_format = ['Phone numbers must be in XXX-XXX-XXXX format.']
valid = {
'403-555-1212': '403-555-1212',
'4035551212': '403-555-1212',
@@ -87,7 +89,7 @@ class CALocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(CAPhoneNumberField, valid, invalid)
def test_CAProvinceField(self):
- error_format = [u'Enter a Canadian province or territory.']
+ error_format = ['Enter a Canadian province or territory.']
valid = {
'ab': 'AB',
'BC': 'BC',
@@ -101,7 +103,7 @@ class CALocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(CAProvinceField, valid, invalid)
def test_CASocialInsuranceField(self):
- error_format = [u'Enter a valid Canadian Social Insurance number in XXX-XXX-XXX format.']
+ error_format = ['Enter a valid Canadian Social Insurance number in XXX-XXX-XXX format.']
valid = {
'046-454-286': '046-454-286',
}
diff --git a/tests/regressiontests/localflavor/ch/tests.py b/tests/regressiontests/localflavor/ch/tests.py
index 17660a46d2..f3491855a2 100644
--- a/tests/regressiontests/localflavor/ch/tests.py
+++ b/tests/regressiontests/localflavor/ch/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.ch.forms import (CHZipCodeField,
CHPhoneNumberField, CHIdentityCardNumberField, CHStateSelect)
@@ -7,7 +9,7 @@ from django.test import SimpleTestCase
class CHLocalFlavorTests(SimpleTestCase):
def test_CHStateSelect(self):
f = CHStateSelect()
- out = u'''<select name="state">
+ out = '''<select name="state">
<option value="AG" selected="selected">Aargau</option>
<option value="AI">Appenzell Innerrhoden</option>
<option value="AR">Appenzell Ausserrhoden</option>
@@ -38,7 +40,7 @@ class CHLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('state', 'AG'), out)
def test_CHZipCodeField(self):
- error_format = [u'Enter a zip code in the format XXXX.']
+ error_format = ['Enter a zip code in the format XXXX.']
valid = {
'1234': '1234',
'0000': '0000',
@@ -50,7 +52,7 @@ class CHLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(CHZipCodeField, valid, invalid)
def test_CHPhoneNumberField(self):
- error_format = [u'Phone numbers must be in 0XX XXX XX XX format.']
+ error_format = ['Phone numbers must be in 0XX XXX XX XX format.']
valid = {
'012 345 67 89': '012 345 67 89',
'0123456789': '012 345 67 89',
@@ -62,7 +64,7 @@ class CHLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(CHPhoneNumberField, valid, invalid)
def test_CHIdentityCardNumberField(self):
- error_format = [u'Enter a valid Swiss identity or passport card number in X1234567<0 or 1234567890 format.']
+ error_format = ['Enter a valid Swiss identity or passport card number in X1234567<0 or 1234567890 format.']
valid = {
'C1234567<0': 'C1234567<0',
'2123456700': '2123456700',
diff --git a/tests/regressiontests/localflavor/cl/tests.py b/tests/regressiontests/localflavor/cl/tests.py
index 250f5645a0..47cae6bd48 100644
--- a/tests/regressiontests/localflavor/cl/tests.py
+++ b/tests/regressiontests/localflavor/cl/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.cl.forms import CLRutField, CLRegionSelect
from django.test import SimpleTestCase
@@ -6,7 +8,7 @@ from django.test import SimpleTestCase
class CLLocalFlavorTests(SimpleTestCase):
def test_CLRegionSelect(self):
f = CLRegionSelect()
- out = u'''<select name="foo">
+ out = '''<select name="foo">
<option value="RM">Regi\xf3n Metropolitana de Santiago</option>
<option value="I">Regi\xf3n de Tarapac\xe1</option>
<option value="II">Regi\xf3n de Antofagasta</option>
@@ -26,8 +28,8 @@ class CLLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('foo', 'bar'), out)
def test_CLRutField(self):
- error_invalid = [u'The Chilean RUT is not valid.']
- error_format = [u'Enter a valid Chilean RUT. The format is XX.XXX.XXX-X.']
+ error_invalid = ['The Chilean RUT is not valid.']
+ error_format = ['Enter a valid Chilean RUT. The format is XX.XXX.XXX-X.']
valid = {
'11-6': '11-6',
'116': '11-6',
diff --git a/tests/regressiontests/localflavor/cn/tests.py b/tests/regressiontests/localflavor/cn/tests.py
index ac4331cca9..24bcc6e392 100644
--- a/tests/regressiontests/localflavor/cn/tests.py
+++ b/tests/regressiontests/localflavor/cn/tests.py
@@ -1,4 +1,5 @@
# Tests for contrib/localflavor/ CN Form Fields
+from __future__ import unicode_literals
from django.contrib.localflavor.cn.forms import (CNProvinceSelect,
CNPostCodeField, CNIDCardField, CNPhoneNumberField, CNCellNumberField)
@@ -7,7 +8,7 @@ from django.test import SimpleTestCase
class CNLocalFlavorTests(SimpleTestCase):
def test_CNProvinceSelect(self):
f = CNProvinceSelect()
- correct_output = u'''<select name="provinces">
+ correct_output = '''<select name="provinces">
<option value="anhui">\u5b89\u5fbd</option>
<option value="beijing">\u5317\u4eac</option>
<option value="chongqing">\u91cd\u5e86</option>
@@ -46,9 +47,9 @@ class CNLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('provinces', 'hubei'), correct_output)
def test_CNPostCodeField(self):
- error_format = [u'Enter a post code in the format XXXXXX.']
+ error_format = ['Enter a post code in the format XXXXXX.']
valid = {
- '091209': u'091209'
+ '091209': '091209'
}
invalid = {
'09120': error_format,
@@ -59,17 +60,17 @@ class CNLocalFlavorTests(SimpleTestCase):
def test_CNIDCardField(self):
valid = {
# A valid 1st generation ID Card Number.
- '110101491001001': u'110101491001001',
+ '110101491001001': '110101491001001',
# A valid 2nd generation ID Card number.
- '11010119491001001X': u'11010119491001001X',
+ '11010119491001001X': '11010119491001001X',
# Another valid 2nd gen ID Number with a case change
- '11010119491001001x': u'11010119491001001X'
+ '11010119491001001x': '11010119491001001X'
}
- wrong_format = [u'ID Card Number consists of 15 or 18 digits.']
- wrong_location = [u'Invalid ID Card Number: Wrong location code']
- wrong_bday = [u'Invalid ID Card Number: Wrong birthdate']
- wrong_checksum = [u'Invalid ID Card Number: Wrong checksum']
+ wrong_format = ['ID Card Number consists of 15 or 18 digits.']
+ wrong_location = ['Invalid ID Card Number: Wrong location code']
+ wrong_bday = ['Invalid ID Card Number: Wrong birthdate']
+ wrong_checksum = ['Invalid ID Card Number: Wrong checksum']
invalid = {
'abcdefghijklmnop': wrong_format,
@@ -83,13 +84,13 @@ class CNLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(CNIDCardField, valid, invalid)
def test_CNPhoneNumberField(self):
- error_format = [u'Enter a valid phone number.']
+ error_format = ['Enter a valid phone number.']
valid = {
- '010-12345678': u'010-12345678',
- '010-1234567': u'010-1234567',
- '0101-12345678': u'0101-12345678',
- '0101-1234567': u'0101-1234567',
- '010-12345678-020':u'010-12345678-020'
+ '010-12345678': '010-12345678',
+ '010-1234567': '010-1234567',
+ '0101-12345678': '0101-12345678',
+ '0101-1234567': '0101-1234567',
+ '010-12345678-020':'010-12345678-020'
}
invalid = {
'01x-12345678': error_format,
@@ -101,9 +102,9 @@ class CNLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(CNPhoneNumberField, valid, invalid)
def test_CNCellNumberField(self):
- error_format = [u'Enter a valid cell number.']
+ error_format = ['Enter a valid cell number.']
valid = {
- '13012345678': u'13012345678',
+ '13012345678': '13012345678',
}
invalid = {
'130123456789': error_format,
diff --git a/tests/regressiontests/localflavor/co/tests.py b/tests/regressiontests/localflavor/co/tests.py
index 4ab1768082..68b20c4308 100644
--- a/tests/regressiontests/localflavor/co/tests.py
+++ b/tests/regressiontests/localflavor/co/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.co.forms import CODepartmentSelect
from django.test import SimpleTestCase
@@ -5,7 +7,7 @@ from django.test import SimpleTestCase
class COLocalFlavorTests(SimpleTestCase):
def test_CODepartmentSelect(self):
d = CODepartmentSelect()
- out = u"""<select name="department">
+ out = """<select name="department">
<option value="AMA">Amazonas</option>
<option value="ANT">Antioquia</option>
<option value="ARA">Arauca</option>
diff --git a/tests/regressiontests/localflavor/cz/tests.py b/tests/regressiontests/localflavor/cz/tests.py
index b8b46b34bb..e4cc05e0c6 100644
--- a/tests/regressiontests/localflavor/cz/tests.py
+++ b/tests/regressiontests/localflavor/cz/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.cz.forms import (CZPostalCodeField,
CZRegionSelect, CZBirthNumberField, CZICNumberField)
@@ -8,7 +10,7 @@ from django.test import SimpleTestCase
class CZLocalFlavorTests(SimpleTestCase):
def test_CZRegionSelect(self):
f = CZRegionSelect()
- out = u'''<select name="regions">
+ out = '''<select name="regions">
<option value="PR">Prague</option>
<option value="CE">Central Bohemian Region</option>
<option value="SO">South Bohemian Region</option>
@@ -27,7 +29,7 @@ class CZLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('regions', 'TT'), out)
def test_CZPostalCodeField(self):
- error_format = [u'Enter a postal code in the format XXXXX or XXX XX.']
+ error_format = ['Enter a postal code in the format XXXXX or XXX XX.']
valid = {
'91909': '91909',
'917 01': '91701',
@@ -42,8 +44,8 @@ class CZLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(CZPostalCodeField, valid, invalid)
def test_CZBirthNumberField(self):
- error_format = [u'Enter a birth number in the format XXXXXX/XXXX or XXXXXXXXXX.']
- error_invalid = [u'Enter a valid birth number.']
+ error_format = ['Enter a birth number in the format XXXXXX/XXXX or XXXXXXXXXX.']
+ error_invalid = ['Enter a valid birth number.']
valid = {
'880523/1237': '880523/1237',
'8805231237': '8805231237',
@@ -63,7 +65,7 @@ class CZLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(CZBirthNumberField, valid, invalid)
def test_CZICNumberField(self):
- error_invalid = [u'Enter a valid IC number.']
+ error_invalid = ['Enter a valid IC number.']
valid ={
'12345679': '12345679',
'12345601': '12345601',
diff --git a/tests/regressiontests/localflavor/de/tests.py b/tests/regressiontests/localflavor/de/tests.py
index a3f75ce2f1..bdf0bcf44f 100644
--- a/tests/regressiontests/localflavor/de/tests.py
+++ b/tests/regressiontests/localflavor/de/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.de.forms import (DEZipCodeField, DEStateSelect,
DEIdentityCardNumberField)
@@ -7,7 +9,7 @@ from django.test import SimpleTestCase
class DELocalFlavorTests(SimpleTestCase):
def test_DEStateSelect(self):
f = DEStateSelect()
- out = u'''<select name="states">
+ out = '''<select name="states">
<option value="BW">Baden-Wuerttemberg</option>
<option value="BY">Bavaria</option>
<option value="BE">Berlin</option>
@@ -28,7 +30,7 @@ class DELocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('states', 'TH'), out)
def test_DEZipCodeField(self):
- error_format = [u'Enter a zip code in the format XXXXX.']
+ error_format = ['Enter a zip code in the format XXXXX.']
valid = {
'99423': '99423',
}
@@ -38,7 +40,7 @@ class DELocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(DEZipCodeField, valid, invalid)
def test_DEIdentityCardNumberField(self):
- error_format = [u'Enter a valid German identity card number in XXXXXXXXXXX-XXXXXXX-XXXXXXX-X format.']
+ error_format = ['Enter a valid German identity card number in XXXXXXXXXXX-XXXXXXX-XXXXXXX-X format.']
valid = {
'7549313035D-6004103-0903042-0': '7549313035D-6004103-0903042-0',
'9786324830D 6104243 0910271 2': '9786324830D-6104243-0910271-2',
diff --git a/tests/regressiontests/localflavor/ec/tests.py b/tests/regressiontests/localflavor/ec/tests.py
index 0ebe2f396d..c72d77e558 100644
--- a/tests/regressiontests/localflavor/ec/tests.py
+++ b/tests/regressiontests/localflavor/ec/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.ec.forms import ECProvinceSelect
from django.test import SimpleTestCase
@@ -5,7 +7,7 @@ from django.test import SimpleTestCase
class ECLocalFlavorTests(SimpleTestCase):
def test_ECProvinceSelect(self):
p = ECProvinceSelect()
- out = u"""<select name="province">
+ out = """<select name="province">
<option value="A">Azuay</option>
<option value="B">Bol\xedvar</option>
<option value="F">Ca\xf1ar</option>
diff --git a/tests/regressiontests/localflavor/es/tests.py b/tests/regressiontests/localflavor/es/tests.py
index c13eac6d61..3fc072cffc 100644
--- a/tests/regressiontests/localflavor/es/tests.py
+++ b/tests/regressiontests/localflavor/es/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.es.forms import (ESPostalCodeField, ESPhoneNumberField,
ESIdentityCardNumberField, ESCCCField, ESRegionSelect, ESProvinceSelect)
@@ -7,7 +9,7 @@ from django.test import SimpleTestCase
class ESLocalFlavorTests(SimpleTestCase):
def test_ESRegionSelect(self):
f = ESRegionSelect()
- out = u'''<select name="regions">
+ out = '''<select name="regions">
<option value="AN">Andalusia</option>
<option value="AR">Aragon</option>
<option value="O">Principality of Asturias</option>
@@ -30,7 +32,7 @@ class ESLocalFlavorTests(SimpleTestCase):
def test_ESProvinceSelect(self):
f = ESProvinceSelect()
- out = u'''<select name="provinces">
+ out = '''<select name="provinces">
<option value="01">Araba</option>
<option value="02">Albacete</option>
<option value="03">Alacant</option>
@@ -87,7 +89,7 @@ class ESLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('provinces', '08'), out)
def test_ESPostalCodeField(self):
- error_invalid = [u'Enter a valid postal code in the range and format 01XXX - 52XXX.']
+ error_invalid = ['Enter a valid postal code in the range and format 01XXX - 52XXX.']
valid = {
'08028': '08028',
'28080': '28080',
@@ -103,7 +105,7 @@ class ESLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(ESPostalCodeField, valid, invalid)
def test_ESPhoneNumberField(self):
- error_invalid = [u'Enter a valid phone number in one of the formats 6XXXXXXXX, 8XXXXXXXX or 9XXXXXXXX.']
+ error_invalid = ['Enter a valid phone number in one of the formats 6XXXXXXXX, 8XXXXXXXX or 9XXXXXXXX.']
valid = {
'650010101': '650010101',
'931234567': '931234567',
@@ -119,10 +121,10 @@ class ESLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(ESPhoneNumberField, valid, invalid)
def test_ESIdentityCardNumberField(self):
- error_invalid = [u'Please enter a valid NIF, NIE, or CIF.']
- error_checksum_nif = [u'Invalid checksum for NIF.']
- error_checksum_nie = [u'Invalid checksum for NIE.']
- error_checksum_cif = [u'Invalid checksum for CIF.']
+ error_invalid = ['Please enter a valid NIF, NIE, or CIF.']
+ error_checksum_nif = ['Invalid checksum for NIF.']
+ error_checksum_nie = ['Invalid checksum for NIE.']
+ error_checksum_cif = ['Invalid checksum for CIF.']
valid = {
'78699688J': '78699688J',
'78699688-J': '78699688J',
@@ -155,8 +157,8 @@ class ESLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(ESIdentityCardNumberField, valid, invalid)
def test_ESCCCField(self):
- error_invalid = [u'Please enter a valid bank account number in format XXXX-XXXX-XX-XXXXXXXXXX.']
- error_checksum = [u'Invalid checksum for bank account number.']
+ error_invalid = ['Please enter a valid bank account number in format XXXX-XXXX-XX-XXXXXXXXXX.']
+ error_checksum = ['Invalid checksum for bank account number.']
valid = {
'20770338793100254321': '20770338793100254321',
'2077 0338 79 3100254321': '2077 0338 79 3100254321',
diff --git a/tests/regressiontests/localflavor/fi/tests.py b/tests/regressiontests/localflavor/fi/tests.py
index 70fce29f45..bfd2e2a010 100644
--- a/tests/regressiontests/localflavor/fi/tests.py
+++ b/tests/regressiontests/localflavor/fi/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.fi.forms import (FIZipCodeField,
FISocialSecurityNumber, FIMunicipalitySelect)
@@ -7,7 +9,7 @@ from django.test import SimpleTestCase
class FILocalFlavorTests(SimpleTestCase):
def test_FIMunicipalitySelect(self):
f = FIMunicipalitySelect()
- out = u'''<select name="municipalities">
+ out = '''<select name="municipalities">
<option value="akaa">Akaa</option>
<option value="alajarvi">Alaj\xe4rvi</option>
<option value="alavieska">Alavieska</option>
@@ -354,7 +356,7 @@ class FILocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('municipalities', 'turku'), out)
def test_FIZipCodeField(self):
- error_format = [u'Enter a zip code in the format XXXXX.']
+ error_format = ['Enter a zip code in the format XXXXX.']
valid = {
'20540': '20540',
'20101': '20101',
@@ -366,7 +368,7 @@ class FILocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(FIZipCodeField, valid, invalid)
def test_FISocialSecurityNumber(self):
- error_invalid = [u'Enter a valid Finnish social security number.']
+ error_invalid = ['Enter a valid Finnish social security number.']
valid = {
'010101-0101': '010101-0101',
'010101+0101': '010101+0101',
diff --git a/tests/regressiontests/localflavor/fr/tests.py b/tests/regressiontests/localflavor/fr/tests.py
index 9b65e1ec0d..55f8a68b3b 100644
--- a/tests/regressiontests/localflavor/fr/tests.py
+++ b/tests/regressiontests/localflavor/fr/tests.py
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
from django.contrib.localflavor.fr.forms import (FRZipCodeField,
FRPhoneNumberField, FRDepartmentSelect)
@@ -7,7 +9,7 @@ from django.test import SimpleTestCase
class FRLocalFlavorTests(SimpleTestCase):
def test_FRZipCodeField(self):
- error_format = [u'Enter a zip code in the format XXXXX.']
+ error_format = ['Enter a zip code in the format XXXXX.']
valid = {
'75001': '75001',
'93200': '93200',
@@ -19,7 +21,7 @@ class FRLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(FRZipCodeField, valid, invalid)
def test_FRPhoneNumberField(self):
- error_format = [u'Phone numbers must be in 0X XX XX XX XX format.']
+ error_format = ['Phone numbers must be in 0X XX XX XX XX format.']
valid = {
'01 55 44 58 64': '01 55 44 58 64',
'0155445864': '01 55 44 58 64',
@@ -35,7 +37,7 @@ class FRLocalFlavorTests(SimpleTestCase):
def test_FRDepartmentSelect(self):
f = FRDepartmentSelect()
- out = u'''<select name="dep">
+ out = '''<select name="dep">
<option value="01">01 - Ain</option>
<option value="02">02 - Aisne</option>
<option value="03">03 - Allier</option>
diff --git a/tests/regressiontests/localflavor/gb/tests.py b/tests/regressiontests/localflavor/gb/tests.py
index b32162d365..5a267105d5 100644
--- a/tests/regressiontests/localflavor/gb/tests.py
+++ b/tests/regressiontests/localflavor/gb/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.gb.forms import GBPostcodeField
from django.test import SimpleTestCase
@@ -5,7 +7,7 @@ from django.test import SimpleTestCase
class GBLocalFlavorTests(SimpleTestCase):
def test_GBPostcodeField(self):
- error_invalid = [u'Enter a valid postcode.']
+ error_invalid = ['Enter a valid postcode.']
valid = {
'BT32 4PX': 'BT32 4PX',
'GIR 0AA': 'GIR 0AA',
@@ -24,7 +26,7 @@ class GBLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(GBPostcodeField, valid, invalid)
valid = {}
invalid = {
- '1NV 4L1D': [u'Enter a bloody postcode!'],
+ '1NV 4L1D': ['Enter a bloody postcode!'],
}
kwargs = {'error_messages': {'invalid': 'Enter a bloody postcode!'}}
self.assertFieldOutput(GBPostcodeField, valid, invalid, field_kwargs=kwargs)
diff --git a/tests/regressiontests/localflavor/generic/tests.py b/tests/regressiontests/localflavor/generic/tests.py
index 12462a0ef2..4db26838fa 100644
--- a/tests/regressiontests/localflavor/generic/tests.py
+++ b/tests/regressiontests/localflavor/generic/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import datetime
from django.contrib.localflavor.generic.forms import DateField, DateTimeField
@@ -7,7 +9,7 @@ from django.test import SimpleTestCase
class GenericLocalFlavorTests(SimpleTestCase):
def test_GenericDateField(self):
- error_invalid = [u'Enter a valid date.']
+ error_invalid = ['Enter a valid date.']
valid = {
datetime.date(2006, 10, 25): datetime.date(2006, 10, 25),
datetime.datetime(2006, 10, 25, 14, 30): datetime.date(2006, 10, 25),
@@ -46,7 +48,7 @@ class GenericLocalFlavorTests(SimpleTestCase):
)
def test_GenericDateTimeField(self):
- error_invalid = [u'Enter a valid date/time.']
+ error_invalid = ['Enter a valid date/time.']
valid = {
datetime.date(2006, 10, 25): datetime.datetime(2006, 10, 25, 0, 0),
datetime.datetime(2006, 10, 25, 14, 30): datetime.datetime(2006, 10, 25, 14, 30),
diff --git a/tests/regressiontests/localflavor/hr/tests.py b/tests/regressiontests/localflavor/hr/tests.py
index 7050d7c5c2..c1b097c03f 100644
--- a/tests/regressiontests/localflavor/hr/tests.py
+++ b/tests/regressiontests/localflavor/hr/tests.py
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
from django.contrib.localflavor.hr.forms import (HRCountySelect,
HRPhoneNumberPrefixSelect, HRLicensePlatePrefixSelect, HRPhoneNumberField,
HRLicensePlateField, HRPostalCodeField, HROIBField, HRJMBGField,
@@ -9,7 +11,7 @@ from django.test import SimpleTestCase
class HRLocalFlavorTests(SimpleTestCase):
def test_HRCountySelect(self):
f = HRCountySelect()
- out = u'''<select name="county">
+ out = '''<select name="county">
<option value="GZG" selected="selected">Grad Zagreb</option>
<option value="BBŽ">Bjelovarsko-bilogorska županija</option>
<option value="BPŽ">Brodsko-posavska županija</option>
@@ -36,7 +38,7 @@ class HRLocalFlavorTests(SimpleTestCase):
def test_HRPhoneNumberPrefixSelect(self):
f = HRPhoneNumberPrefixSelect()
- out = u'''<select name="phone">
+ out = '''<select name="phone">
<option value="1" selected="selected">01</option>
<option value="20">020</option>
<option value="21">021</option>
@@ -68,7 +70,7 @@ class HRLocalFlavorTests(SimpleTestCase):
def test_HRLicensePlatePrefixSelect(self):
f = HRLicensePlatePrefixSelect()
- out = u'''<select name="license">
+ out = '''<select name="license">
<option value="BJ" selected="selected">BJ</option>
<option value="BM">BM</option>
<option value="ČK">ČK</option>
@@ -107,9 +109,9 @@ class HRLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('license', 'BJ'), out)
def test_HRPhoneNumberField(self):
- error_invalid = [u'Enter a valid phone number']
- error_area = [u'Enter a valid area or mobile network code']
- error_number = [u'The phone nubmer is too long']
+ error_invalid = ['Enter a valid phone number']
+ error_area = ['Enter a valid area or mobile network code']
+ error_number = ['The phone nubmer is too long']
valid = {
'+38511234567': '+38511234567',
'0038511234567': '+38511234567',
@@ -126,12 +128,12 @@ class HRLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(HRPhoneNumberField, valid, invalid)
def test_HRLicensePlateField(self):
- error_invalid = [u'Enter a valid vehicle license plate number']
- error_area = [u'Enter a valid location code']
- error_number = [u'Number part cannot be zero']
+ error_invalid = ['Enter a valid vehicle license plate number']
+ error_area = ['Enter a valid location code']
+ error_number = ['Number part cannot be zero']
valid = {
- 'ZG 1234-AA': u'ZG 1234-AA',
- 'ZG 123-A': u'ZG 123-A',
+ 'ZG 1234-AA': 'ZG 1234-AA',
+ 'ZG 123-A': 'ZG 123-A',
}
invalid = {
'PV12345': error_invalid,
@@ -141,7 +143,7 @@ class HRLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(HRLicensePlateField, valid, invalid)
def test_HRPostalCodeField(self):
- error_invalid = [u'Enter a valid 5 digit postal code']
+ error_invalid = ['Enter a valid 5 digit postal code']
valid = {
'10000': '10000',
'35410': '35410',
@@ -153,19 +155,19 @@ class HRLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(HRPostalCodeField, valid, invalid)
def test_HROIBField(self):
- error_invalid = [u'Enter a valid 11 digit OIB']
+ error_invalid = ['Enter a valid 11 digit OIB']
valid = {
'12345678901': '12345678901',
}
invalid = {
- '1234567890': [u'Ensure this value has at least 11 characters (it has 10).'] + error_invalid,
+ '1234567890': ['Ensure this value has at least 11 characters (it has 10).'] + error_invalid,
'ABCDEFGHIJK': error_invalid,
}
self.assertFieldOutput(HROIBField, valid, invalid)
def test_HRJMBGField(self):
- error_invalid = [u'Enter a valid 13 digit JMBG']
- error_date = [u'Error in date segment']
+ error_invalid = ['Enter a valid 13 digit JMBG']
+ error_date = ['Error in date segment']
valid = {
'1211984302155': '1211984302155',
'2701984307107': '2701984307107',
@@ -178,8 +180,8 @@ class HRLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(HRJMBGField, valid, invalid)
def test_HRJMBAGField(self):
- error_invalid = [u'Enter a valid 19 digit JMBAG starting with 601983']
- error_copy = [u'Card issue number cannot be zero']
+ error_invalid = ['Enter a valid 19 digit JMBAG starting with 601983']
+ error_copy = ['Card issue number cannot be zero']
valid = {
'601983 11 0130185856 4': '6019831101301858564',
}
diff --git a/tests/regressiontests/localflavor/id/tests.py b/tests/regressiontests/localflavor/id/tests.py
index 580083d3bf..dd712d02a3 100644
--- a/tests/regressiontests/localflavor/id/tests.py
+++ b/tests/regressiontests/localflavor/id/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import warnings
from django.contrib.localflavor.id.forms import (IDPhoneNumberField,
@@ -21,7 +23,7 @@ class IDLocalFlavorTests(SimpleTestCase):
def test_IDProvinceSelect(self):
f = IDProvinceSelect()
- out = u'''<select name="provinces">
+ out = '''<select name="provinces">
<option value="ACE">Aceh</option>
<option value="BLI">Bali</option>
<option value="BTN">Banten</option>
@@ -60,7 +62,7 @@ class IDLocalFlavorTests(SimpleTestCase):
def test_IDLicensePlatePrefixSelect(self):
f = IDLicensePlatePrefixSelect()
- out = u'''<select name="codes">
+ out = '''<select name="codes">
<option value="A">Banten</option>
<option value="AA">Magelang</option>
<option value="AB">Yogyakarta</option>
@@ -121,14 +123,14 @@ class IDLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('codes', 'BE'), out)
def test_IDPhoneNumberField(self):
- error_invalid = [u'Enter a valid phone number']
+ error_invalid = ['Enter a valid phone number']
valid = {
- '0812-3456789': u'0812-3456789',
- '081234567890': u'081234567890',
- '021 345 6789': u'021 345 6789',
- '0213456789': u'0213456789',
- '+62-21-3456789': u'+62-21-3456789',
- '(021) 345 6789': u'(021) 345 6789',
+ '0812-3456789': '0812-3456789',
+ '081234567890': '081234567890',
+ '021 345 6789': '021 345 6789',
+ '0213456789': '0213456789',
+ '+62-21-3456789': '+62-21-3456789',
+ '(021) 345 6789': '(021) 345 6789',
}
invalid = {
'0123456789': error_invalid,
@@ -140,11 +142,11 @@ class IDLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(IDPhoneNumberField, valid, invalid)
def test_IDPostCodeField(self):
- error_invalid = [u'Enter a valid post code']
+ error_invalid = ['Enter a valid post code']
valid = {
- '12340': u'12340',
- '25412': u'25412',
- ' 12340 ': u'12340',
+ '12340': '12340',
+ '25412': '25412',
+ ' 12340 ': '12340',
}
invalid = {
'12 3 4 0': error_invalid,
@@ -156,11 +158,11 @@ class IDLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(IDPostCodeField, valid, invalid)
def test_IDNationalIdentityNumberField(self):
- error_invalid = [u'Enter a valid NIK/KTP number']
+ error_invalid = ['Enter a valid NIK/KTP number']
valid = {
- ' 12.3456.010178 3456 ': u'12.3456.010178.3456',
- '1234560101783456': u'12.3456.010178.3456',
- '12.3456.010101.3456': u'12.3456.010101.3456',
+ ' 12.3456.010178 3456 ': '12.3456.010178.3456',
+ '1234560101783456': '12.3456.010178.3456',
+ '12.3456.010101.3456': '12.3456.010101.3456',
}
invalid = {
'12.3456.310278.3456': error_invalid,
@@ -171,14 +173,14 @@ class IDLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(IDNationalIdentityNumberField, valid, invalid)
def test_IDLicensePlateField(self):
- error_invalid = [u'Enter a valid vehicle license plate number']
+ error_invalid = ['Enter a valid vehicle license plate number']
valid = {
- ' b 1234 ab ': u'B 1234 AB',
- 'B 1234 ABC': u'B 1234 ABC',
- 'A 12': u'A 12',
- 'DK 12345 12': u'DK 12345 12',
- 'RI 10': u'RI 10',
- 'CD 12 12': u'CD 12 12',
+ ' b 1234 ab ': 'B 1234 AB',
+ 'B 1234 ABC': 'B 1234 ABC',
+ 'A 12': 'A 12',
+ 'DK 12345 12': 'DK 12345 12',
+ 'RI 10': 'RI 10',
+ 'CD 12 12': 'CD 12 12',
}
invalid = {
'CD 10 12': error_invalid,
diff --git a/tests/regressiontests/localflavor/ie/tests.py b/tests/regressiontests/localflavor/ie/tests.py
index 712f492a65..717fa9d1c7 100644
--- a/tests/regressiontests/localflavor/ie/tests.py
+++ b/tests/regressiontests/localflavor/ie/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.ie.forms import IECountySelect
from django.test import SimpleTestCase
@@ -6,7 +8,7 @@ from django.test import SimpleTestCase
class IELocalFlavorTests(SimpleTestCase):
def test_IECountySelect(self):
f = IECountySelect()
- out = u'''<select name="counties">
+ out = '''<select name="counties">
<option value="antrim">Antrim</option>
<option value="armagh">Armagh</option>
<option value="carlow">Carlow</option>
diff --git a/tests/regressiontests/localflavor/il/tests.py b/tests/regressiontests/localflavor/il/tests.py
index a3b91e850e..1b87cf2c19 100644
--- a/tests/regressiontests/localflavor/il/tests.py
+++ b/tests/regressiontests/localflavor/il/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.il.forms import (ILPostalCodeField,
ILIDNumberField)
@@ -6,7 +8,7 @@ from django.test import SimpleTestCase
class ILLocalFlavorTests(SimpleTestCase):
def test_ILPostalCodeField(self):
- error_format = [u'Enter a postal code in the format XXXXX']
+ error_format = ['Enter a postal code in the format XXXXX']
valid = {
'69973': '69973',
'699 73': '69973',
@@ -21,7 +23,7 @@ class ILLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(ILPostalCodeField, valid, invalid)
def test_ILIDNumberField(self):
- error_invalid = [u'Enter a valid ID number.']
+ error_invalid = ['Enter a valid ID number.']
valid = {
'3933742-3': '39337423',
'39337423': '39337423',
diff --git a/tests/regressiontests/localflavor/in_/tests.py b/tests/regressiontests/localflavor/in_/tests.py
index d079aed1f5..57d50f0ebf 100644
--- a/tests/regressiontests/localflavor/in_/tests.py
+++ b/tests/regressiontests/localflavor/in_/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.in_.forms import (INZipCodeField,
INStateField, INStateSelect, INPhoneNumberField)
@@ -7,7 +9,7 @@ from django.test import SimpleTestCase
class INLocalFlavorTests(SimpleTestCase):
def test_INPhoneNumberField(self):
- error_format = [u'Phone numbers must be in 02X-8X or 03X-7X or 04X-6X format.']
+ error_format = ['Phone numbers must be in 02X-8X or 03X-7X or 04X-6X format.']
valid = {
'0423-2443667': '0423-2443667',
'0423 2443667': '0423 2443667',
@@ -27,7 +29,7 @@ class INLocalFlavorTests(SimpleTestCase):
def test_INPStateSelect(self):
f = INStateSelect()
- out = u'''<select name="state">
+ out = '''<select name="state">
<option value="KA">Karnataka</option>
<option value="AP" selected="selected">Andhra Pradesh</option>
<option value="KL">Kerala</option>
@@ -67,7 +69,7 @@ class INLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('state', 'AP'), out)
def test_INZipCodeField(self):
- error_format = [u'Enter a zip code in the format XXXXXX or XXX XXX.']
+ error_format = ['Enter a zip code in the format XXXXXX or XXX XXX.']
valid = {
'360311': '360311',
'360 311': '360311',
@@ -82,7 +84,7 @@ class INLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(INZipCodeField, valid, invalid)
def test_INStateField(self):
- error_format = [u'Enter an Indian state or territory.']
+ error_format = ['Enter an Indian state or territory.']
valid = {
'an': 'AN',
'AN': 'AN',
diff --git a/tests/regressiontests/localflavor/is_/tests.py b/tests/regressiontests/localflavor/is_/tests.py
index 835df6a8a7..3ed15e937b 100644
--- a/tests/regressiontests/localflavor/is_/tests.py
+++ b/tests/regressiontests/localflavor/is_/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.is_.forms import (ISIdNumberField,
ISPhoneNumberField, ISPostalCodeSelect)
@@ -7,7 +9,7 @@ from django.test import SimpleTestCase
class ISLocalFlavorTests(SimpleTestCase):
def test_ISPostalCodeSelect(self):
f = ISPostalCodeSelect()
- out = u'''<select name="foo">
+ out = '''<select name="foo">
<option value="101">101 Reykjav\xedk</option>
<option value="103">103 Reykjav\xedk</option>
<option value="104">104 Reykjav\xedk</option>
@@ -159,10 +161,10 @@ class ISLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('foo', 'bar'), out)
def test_ISIdNumberField(self):
- error_atleast = [u'Ensure this value has at least 10 characters (it has 9).']
- error_invalid = [u'Enter a valid Icelandic identification number. The format is XXXXXX-XXXX.']
- error_atmost = [u'Ensure this value has at most 11 characters (it has 12).']
- error_notvalid = [u'The Icelandic identification number is not valid.']
+ error_atleast = ['Ensure this value has at least 10 characters (it has 9).']
+ error_invalid = ['Enter a valid Icelandic identification number. The format is XXXXXX-XXXX.']
+ error_atmost = ['Ensure this value has at most 11 characters (it has 12).']
+ error_notvalid = ['The Icelandic identification number is not valid.']
valid = {
'2308803449': '230880-3449',
'230880-3449': '230880-3449',
@@ -179,9 +181,9 @@ class ISLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(ISIdNumberField, valid, invalid)
def test_ISPhoneNumberField(self):
- error_invalid = [u'Enter a valid value.']
- error_atleast = [u'Ensure this value has at least 7 characters (it has 6).']
- error_atmost = [u'Ensure this value has at most 8 characters (it has 9).']
+ error_invalid = ['Enter a valid value.']
+ error_atleast = ['Ensure this value has at least 7 characters (it has 6).']
+ error_atmost = ['Ensure this value has at most 8 characters (it has 9).']
valid = {
'1234567': '1234567',
'123 4567': '1234567',
diff --git a/tests/regressiontests/localflavor/it/tests.py b/tests/regressiontests/localflavor/it/tests.py
index b774141c2d..680444400f 100644
--- a/tests/regressiontests/localflavor/it/tests.py
+++ b/tests/regressiontests/localflavor/it/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.it.forms import (ITZipCodeField, ITRegionSelect,
ITSocialSecurityNumberField, ITVatNumberField)
@@ -7,7 +9,7 @@ from django.test import SimpleTestCase
class ITLocalFlavorTests(SimpleTestCase):
def test_ITRegionSelect(self):
f = ITRegionSelect()
- out = u'''<select name="regions">
+ out = '''<select name="regions">
<option value="ABR">Abruzzo</option>
<option value="BAS">Basilicata</option>
<option value="CAL">Calabria</option>
@@ -32,7 +34,7 @@ class ITLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('regions', 'PMN'), out)
def test_ITZipCodeField(self):
- error_invalid = [u'Enter a valid zip code.']
+ error_invalid = ['Enter a valid zip code.']
valid = {
'00100': '00100',
}
@@ -42,7 +44,7 @@ class ITLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(ITZipCodeField, valid, invalid)
def test_ITSocialSecurityNumberField(self):
- error_invalid = [u'Enter a valid Social Security number.']
+ error_invalid = ['Enter a valid Social Security number.']
valid = {
'LVSGDU99T71H501L': 'LVSGDU99T71H501L',
'LBRRME11A01L736W': 'LBRRME11A01L736W',
@@ -56,7 +58,7 @@ class ITLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(ITSocialSecurityNumberField, valid, invalid)
def test_ITVatNumberField(self):
- error_invalid = [u'Enter a valid VAT number.']
+ error_invalid = ['Enter a valid VAT number.']
valid = {
'07973780013': '07973780013',
'7973780013': '07973780013',
diff --git a/tests/regressiontests/localflavor/jp/tests.py b/tests/regressiontests/localflavor/jp/tests.py
index 7f0e8be184..d31c679bcb 100644
--- a/tests/regressiontests/localflavor/jp/tests.py
+++ b/tests/regressiontests/localflavor/jp/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.jp.forms import (JPPostalCodeField,
JPPrefectureSelect)
@@ -7,7 +9,7 @@ from django.test import SimpleTestCase
class JPLocalFlavorTests(SimpleTestCase):
def test_JPPrefectureSelect(self):
f = JPPrefectureSelect()
- out = u'''<select name="prefecture">
+ out = '''<select name="prefecture">
<option value="hokkaido">Hokkaido</option>
<option value="aomori">Aomori</option>
<option value="iwate">Iwate</option>
@@ -59,7 +61,7 @@ class JPLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('prefecture', 'kanagawa'), out)
def test_JPPostalCodeField(self):
- error_format = [u'Enter a postal code in the format XXXXXXX or XXX-XXXX.']
+ error_format = ['Enter a postal code in the format XXXXXXX or XXX-XXXX.']
valid = {
'251-0032': '2510032',
'2510032': '2510032',
diff --git a/tests/regressiontests/localflavor/kw/tests.py b/tests/regressiontests/localflavor/kw/tests.py
index c46241f4f4..0cf645b918 100644
--- a/tests/regressiontests/localflavor/kw/tests.py
+++ b/tests/regressiontests/localflavor/kw/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.kw.forms import KWCivilIDNumberField
from django.test import SimpleTestCase
@@ -5,7 +7,7 @@ from django.test import SimpleTestCase
class KWLocalFlavorTests(SimpleTestCase):
def test_KWCivilIDNumberField(self):
- error_invalid = [u'Enter a valid Kuwaiti Civil ID number']
+ error_invalid = ['Enter a valid Kuwaiti Civil ID number']
valid = {
'282040701483': '282040701483',
}
diff --git a/tests/regressiontests/localflavor/mk/tests.py b/tests/regressiontests/localflavor/mk/tests.py
index 3a8add6e34..fdc9932f6a 100644
--- a/tests/regressiontests/localflavor/mk/tests.py
+++ b/tests/regressiontests/localflavor/mk/tests.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from django.contrib.localflavor.mk.forms import (
MKIdentityCardNumberField, MKMunicipalitySelect, UMCNField)
@@ -41,7 +41,7 @@ class MKLocalFlavorTests(SimpleTestCase):
})
self.assertFalse(form.is_valid())
self.assertEqual(
- form.errors['municipality_req'], [u'This field is required.'])
+ form.errors['municipality_req'], ['This field is required.'])
def test_umcn_invalid(self):
"""
@@ -56,7 +56,7 @@ class MKLocalFlavorTests(SimpleTestCase):
'id_number':'A1234567',
})
self.assertFalse(form.is_valid())
- self.assertEqual(form.errors['umcn'], [u'The UMCN is not valid.'])
+ self.assertEqual(form.errors['umcn'], ['The UMCN is not valid.'])
form = MKPersonForm({
'first_name':'Someone',
@@ -67,7 +67,7 @@ class MKLocalFlavorTests(SimpleTestCase):
'id_number':'A1234567',
})
self.assertEqual(form.errors['umcn'],
- [u'The first 7 digits of the UMCN must represent a valid past date.'])
+ ['The first 7 digits of the UMCN must represent a valid past date.'])
def test_idnumber_invalid(self):
"""
@@ -85,8 +85,8 @@ class MKLocalFlavorTests(SimpleTestCase):
})
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['id_number'],
- [u'Identity card numbers must contain either 4 to 7 '
- 'digits or an uppercase letter and 7 digits.'])
+ ['Identity card numbers must contain either 4 to 7 '
+ 'digits or an uppercase letter and 7 digits.'])
def test_field_blank_option(self):
"""
@@ -183,7 +183,7 @@ class MKLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(str(self.form['municipality']), municipality_select_html)
def test_MKIdentityCardNumberField(self):
- error_invalid = [u'Identity card numbers must contain either 4 to 7 '
+ error_invalid = ['Identity card numbers must contain either 4 to 7 '
'digits or an uppercase letter and 7 digits.']
valid = {
'L0018077':'L0018077',
@@ -198,7 +198,7 @@ class MKLocalFlavorTests(SimpleTestCase):
def test_MKMunicipalitySelect(self):
f = MKMunicipalitySelect()
- out=u'''<select name="municipality">
+ out='''<select name="municipality">
<option value="AD">Aerodrom</option>
<option value="AR">Ara\u010dinovo</option>
<option value="BR">Berovo</option>
@@ -287,10 +287,10 @@ class MKLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('municipality', 'DL' ), out)
def test_UMCNField(self):
- error_invalid = [u'This field should contain exactly 13 digits.']
- error_checksum = [u'The UMCN is not valid.']
- error_date = [u'The first 7 digits of the UMCN '
- 'must represent a valid past date.']
+ error_invalid = ['This field should contain exactly 13 digits.']
+ error_checksum = ['The UMCN is not valid.']
+ error_date = ['The first 7 digits of the UMCN '
+ 'must represent a valid past date.']
valid = {
'2402983450006': '2402983450006',
'2803984430038': '2803984430038',
diff --git a/tests/regressiontests/localflavor/mx/tests.py b/tests/regressiontests/localflavor/mx/tests.py
index 1657596223..5eeceec276 100644
--- a/tests/regressiontests/localflavor/mx/tests.py
+++ b/tests/regressiontests/localflavor/mx/tests.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from django.contrib.localflavor.mx.forms import (MXZipCodeField, MXRFCField,
MXStateSelect, MXCURPField)
@@ -21,7 +21,7 @@ class MXLocalFlavorTests(SimpleTestCase):
def test_get_display_methods(self):
"""Test that the get_*_display() methods are added to the model instances."""
place = self.form.save()
- self.assertEqual(place.get_state_display(), u'Michoacán')
+ self.assertEqual(place.get_state_display(), 'Michoacán')
def test_errors(self):
"""Test that required MXFields throw appropriate errors."""
@@ -32,10 +32,10 @@ class MXLocalFlavorTests(SimpleTestCase):
'zip_code': 'xxx',
})
self.assertFalse(form.is_valid())
- self.assertEqual(form.errors['state'], [u'Select a valid choice. Invalid state is not one of the available choices.'])
- self.assertEqual(form.errors['rfc'], [u'Enter a valid RFC.'])
- self.assertEqual(form.errors['curp'], [u'Ensure this value has at least 18 characters (it has 12).', u'Enter a valid CURP.'])
- self.assertEqual(form.errors['zip_code'], [u'Enter a valid zip code in the format XXXXX.'])
+ self.assertEqual(form.errors['state'], ['Select a valid choice. Invalid state is not one of the available choices.'])
+ self.assertEqual(form.errors['rfc'], ['Enter a valid RFC.'])
+ self.assertEqual(form.errors['curp'], ['Ensure this value has at least 18 characters (it has 12).', 'Enter a valid CURP.'])
+ self.assertEqual(form.errors['zip_code'], ['Enter a valid zip code in the format XXXXX.'])
def test_field_blank_option(self):
"""Test that the empty option is there."""
@@ -79,7 +79,7 @@ class MXLocalFlavorTests(SimpleTestCase):
def test_MXStateSelect(self):
f = MXStateSelect()
- out = u'''<select name="state">
+ out = '''<select name="state">
<option value="AGU">Aguascalientes</option>
<option value="BCN">Baja California</option>
<option value="BCS">Baja California Sur</option>
@@ -116,12 +116,12 @@ class MXLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('state', 'MIC'), out)
def test_MXZipCodeField(self):
- error_format = [u'Enter a valid zip code in the format XXXXX.']
+ error_format = ['Enter a valid zip code in the format XXXXX.']
valid = {
- '58120': u'58120',
- '58502': u'58502',
- '59310': u'59310',
- '99999': u'99999',
+ '58120': '58120',
+ '58502': '58502',
+ '59310': '59310',
+ '99999': '99999',
}
invalid = {
'17000': error_format,
@@ -132,16 +132,16 @@ class MXLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(MXZipCodeField, valid, invalid)
def test_MXRFCField(self):
- error_format = [u'Enter a valid RFC.']
- error_checksum = [u'Invalid checksum for RFC.']
+ error_format = ['Enter a valid RFC.']
+ error_checksum = ['Invalid checksum for RFC.']
valid = {
- 'MoFN641205eX5': u'MOFN641205EX5',
- 'ICa060120873': u'ICA060120873',
- 'eUcG751104rT0': u'EUCG751104RT0',
- 'GME08100195A': u'GME08100195A',
- 'AA&060524KX5': u'AA&060524KX5',
- 'CAÑ0708045P7': u'CAÑ0708045P7',
- 'aaa000101aa9': u'AAA000101AA9',
+ 'MoFN641205eX5': 'MOFN641205EX5',
+ 'ICa060120873': 'ICA060120873',
+ 'eUcG751104rT0': 'EUCG751104RT0',
+ 'GME08100195A': 'GME08100195A',
+ 'AA&060524KX5': 'AA&060524KX5',
+ 'CAÑ0708045P7': 'CAÑ0708045P7',
+ 'aaa000101aa9': 'AAA000101AA9',
}
invalid = {
'MED0000000XA': error_format,
@@ -166,19 +166,19 @@ class MXLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(MXRFCField, valid, invalid)
def test_MXCURPField(self):
- error_format = [u'Enter a valid CURP.']
- error_checksum = [u'Invalid checksum for CURP.']
+ error_format = ['Enter a valid CURP.']
+ error_checksum = ['Invalid checksum for CURP.']
valid = {
- 'AaMG890608HDFLJL00': u'AAMG890608HDFLJL00',
- 'BAAd890419HMNRRV07': u'BAAD890419HMNRRV07',
- 'VIAA900930MMNClL08': u'VIAA900930MMNCLL08',
- 'HEGR891009HMNRRD09': u'HEGR891009HMNRRD09',
- 'MARR890512HMNRMN09': u'MARR890512HMNRMN09',
- 'MESJ890928HMNZNS00': u'MESJ890928HMNZNS00',
- 'BAAA890317HDFRLL03': u'BAAA890317HDFRLL03',
- 'TOMA880125HMNRRNO2': u'TOMA880125HMNRRNO2',
- 'OOMG890727HMNRSR06': u'OOMG890727HMNRSR06',
- 'AAAA000101HDFCCC09': u'AAAA000101HDFCCC09',
+ 'AaMG890608HDFLJL00': 'AAMG890608HDFLJL00',
+ 'BAAd890419HMNRRV07': 'BAAD890419HMNRRV07',
+ 'VIAA900930MMNClL08': 'VIAA900930MMNCLL08',
+ 'HEGR891009HMNRRD09': 'HEGR891009HMNRRD09',
+ 'MARR890512HMNRMN09': 'MARR890512HMNRMN09',
+ 'MESJ890928HMNZNS00': 'MESJ890928HMNZNS00',
+ 'BAAA890317HDFRLL03': 'BAAA890317HDFRLL03',
+ 'TOMA880125HMNRRNO2': 'TOMA880125HMNRRNO2',
+ 'OOMG890727HMNRSR06': 'OOMG890727HMNRSR06',
+ 'AAAA000101HDFCCC09': 'AAAA000101HDFCCC09',
}
invalid = {
'AAAA000000HDFCCC09': error_format,
diff --git a/tests/regressiontests/localflavor/nl/tests.py b/tests/regressiontests/localflavor/nl/tests.py
index ebe4cc138f..ef8bd3cf35 100644
--- a/tests/regressiontests/localflavor/nl/tests.py
+++ b/tests/regressiontests/localflavor/nl/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.nl.forms import (NLPhoneNumberField,
NLZipCodeField, NLSoFiNumberField, NLProvinceSelect)
@@ -7,7 +9,7 @@ from django.test import SimpleTestCase
class NLLocalFlavorTests(SimpleTestCase):
def test_NLProvinceSelect(self):
f = NLProvinceSelect()
- out = u'''<select name="provinces">
+ out = '''<select name="provinces">
<option value="DR">Drenthe</option>
<option value="FL">Flevoland</option>
<option value="FR">Friesland</option>
@@ -24,7 +26,7 @@ class NLLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('provinces', 'OV'), out)
def test_NLPhoneNumberField(self):
- error_invalid = [u'Enter a valid phone number']
+ error_invalid = ['Enter a valid phone number']
valid = {
'012-3456789': '012-3456789',
'0123456789': '0123456789',
@@ -37,7 +39,7 @@ class NLLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(NLPhoneNumberField, valid, invalid)
def test_NLZipCodeField(self):
- error_invalid = [u'Enter a valid postal code']
+ error_invalid = ['Enter a valid postal code']
valid = {
'1234ab': '1234 AB',
'1234 ab': '1234 AB',
@@ -50,7 +52,7 @@ class NLLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(NLZipCodeField, valid, invalid)
def test_NLSoFiNumberField(self):
- error_invalid = [u'Enter a valid SoFi number']
+ error_invalid = ['Enter a valid SoFi number']
valid = {
'123456782': '123456782',
}
diff --git a/tests/regressiontests/localflavor/pl/tests.py b/tests/regressiontests/localflavor/pl/tests.py
index bc4d260abc..82c5d615c1 100644
--- a/tests/regressiontests/localflavor/pl/tests.py
+++ b/tests/regressiontests/localflavor/pl/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.pl.forms import (PLProvinceSelect,
PLCountySelect, PLPostalCodeField, PLNIPField, PLPESELField, PLNationalIDCardNumberField, PLREGONField)
@@ -7,7 +9,7 @@ from django.test import SimpleTestCase
class PLLocalFlavorTests(SimpleTestCase):
def test_PLProvinceSelect(self):
f = PLProvinceSelect()
- out = u'''<select name="voivodeships">
+ out = '''<select name="voivodeships">
<option value="lower_silesia">Lower Silesia</option>
<option value="kuyavia-pomerania">Kuyavia-Pomerania</option>
<option value="lublin">Lublin</option>
@@ -29,7 +31,7 @@ class PLLocalFlavorTests(SimpleTestCase):
def test_PLCountrySelect(self):
f = PLCountySelect()
- out = u'''<select name="administrativeunit">
+ out = '''<select name="administrativeunit">
<option value="wroclaw">Wroc\u0142aw</option>
<option value="jeleniagora">Jelenia G\xf3ra</option>
<option value="legnica">Legnica</option>
@@ -410,7 +412,7 @@ class PLLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('administrativeunit', 'katowice'), out)
def test_PLPostalCodeField(self):
- error_format = [u'Enter a postal code in the format XX-XXX.']
+ error_format = ['Enter a postal code in the format XX-XXX.']
valid = {
'41-403': '41-403',
}
@@ -420,8 +422,8 @@ class PLLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(PLPostalCodeField, valid, invalid)
def test_PLNIPField(self):
- error_format = [u'Enter a tax number field (NIP) in the format XXX-XXX-XX-XX, XXX-XX-XX-XXX or XXXXXXXXXX.']
- error_checksum = [u'Wrong checksum for the Tax Number (NIP).']
+ error_format = ['Enter a tax number field (NIP) in the format XXX-XXX-XX-XX, XXX-XX-XX-XXX or XXXXXXXXXX.']
+ error_checksum = ['Wrong checksum for the Tax Number (NIP).']
valid = {
'646-241-41-24': '6462414124',
'646-24-14-124': '6462414124',
@@ -429,14 +431,14 @@ class PLLocalFlavorTests(SimpleTestCase):
}
invalid = {
'43-343-234-323': error_format,
- '64-62-414-124': error_format,
+ '64-62-414-124': error_format,
'646-241-41-23': error_checksum,
}
self.assertFieldOutput(PLNIPField, valid, invalid)
def test_PLPESELField(self):
- error_checksum = [u'Wrong checksum for the National Identification Number.']
- error_format = [u'National Identification Number consists of 11 digits.']
+ error_checksum = ['Wrong checksum for the National Identification Number.']
+ error_format = ['National Identification Number consists of 11 digits.']
valid = {
'80071610614': '80071610614',
}
@@ -448,8 +450,8 @@ class PLLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(PLPESELField, valid, invalid)
def test_PLNationalIDCardNumberField(self):
- error_checksum = [u'Wrong checksum for the National ID Card Number.']
- error_format = [u'National ID Card Number consists of 3 letters and 6 digits.']
+ error_checksum = ['Wrong checksum for the National ID Card Number.']
+ error_format = ['National ID Card Number consists of 3 letters and 6 digits.']
valid = {
'ABC123458': 'ABC123458',
'abc123458': 'ABC123458',
@@ -463,8 +465,8 @@ class PLLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(PLNationalIDCardNumberField, valid, invalid)
def test_PLREGONField(self):
- error_checksum = [u'Wrong checksum for the National Business Register Number (REGON).']
- error_format = [u'National Business Register Number (REGON) consists of 9 or 14 digits.']
+ error_checksum = ['Wrong checksum for the National Business Register Number (REGON).']
+ error_format = ['National Business Register Number (REGON) consists of 9 or 14 digits.']
valid = {
'12345678512347': '12345678512347',
'590096454': '590096454',
diff --git a/tests/regressiontests/localflavor/pt/tests.py b/tests/regressiontests/localflavor/pt/tests.py
index 29aa1781eb..051e78084b 100644
--- a/tests/regressiontests/localflavor/pt/tests.py
+++ b/tests/regressiontests/localflavor/pt/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.pt.forms import PTZipCodeField, PTPhoneNumberField
from django.test import SimpleTestCase
@@ -5,7 +7,7 @@ from django.test import SimpleTestCase
class PTLocalFlavorTests(SimpleTestCase):
def test_PTZipCodeField(self):
- error_format = [u'Enter a zip code in the format XXXX-XXX.']
+ error_format = ['Enter a zip code in the format XXXX-XXX.']
valid = {
'3030-034': '3030-034',
'1003456': '1003-456',
@@ -17,7 +19,7 @@ class PTLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(PTZipCodeField, valid, invalid)
def test_PTPhoneNumberField(self):
- error_format = [u'Phone numbers must have 9 digits, or start by + or 00.']
+ error_format = ['Phone numbers must have 9 digits, or start by + or 00.']
valid = {
'917845189': '917845189',
'91 784 5189': '917845189',
diff --git a/tests/regressiontests/localflavor/py/tests.py b/tests/regressiontests/localflavor/py/tests.py
index 772039d3ef..fb7836dc9a 100644
--- a/tests/regressiontests/localflavor/py/tests.py
+++ b/tests/regressiontests/localflavor/py/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.py.forms import (PyDepartmentSelect,
PyNumberedDepartmentSelect)
@@ -6,7 +8,7 @@ from django.test import SimpleTestCase
class PYLocalFlavorTests(SimpleTestCase):
def test_PyDepartmentSelect(self):
py = PyDepartmentSelect()
- out = u'''<select name="department">
+ out = '''<select name="department">
<option value="AG">Alto Paraguay</option>
<option value="AA">Alto Paran\xe1</option>
<option value="AM">Amambay</option>
@@ -30,7 +32,7 @@ class PYLocalFlavorTests(SimpleTestCase):
def test_PyNumberedDepartmentSelect(self):
py = PyNumberedDepartmentSelect()
- out = u'''<select name="department">
+ out = '''<select name="department">
<option value="CN">I Concepci\xf3n</option>
<option value="SP">II San Pedro</option>
<option value="CR">III Cordillera</option>
diff --git a/tests/regressiontests/localflavor/ro/tests.py b/tests/regressiontests/localflavor/ro/tests.py
index 407e614b3e..2e63bdc619 100644
--- a/tests/regressiontests/localflavor/ro/tests.py
+++ b/tests/regressiontests/localflavor/ro/tests.py
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
from django.contrib.localflavor.ro.forms import (ROCIFField, ROCNPField,
ROCountyField, ROCountySelect, ROIBANField, ROPhoneNumberField,
ROPostalCodeField)
@@ -9,7 +11,7 @@ from django.test import SimpleTestCase
class ROLocalFlavorTests(SimpleTestCase):
def test_ROCountySelect(self):
f = ROCountySelect()
- out = u'''<select name="county">
+ out = '''<select name="county">
<option value="AB">Alba</option>
<option value="AR">Arad</option>
<option value="AG">Arge\u015f</option>
@@ -56,12 +58,12 @@ class ROLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('county', 'CJ'), out)
def test_ROCIFField(self):
- error_invalid = [u'Enter a valid CIF.']
- error_atmost = [u'Ensure this value has at most 10 characters (it has 11).']
- error_atleast = [u'Ensure this value has at least 2 characters (it has 1).']
+ error_invalid = ['Enter a valid CIF.']
+ error_atmost = ['Ensure this value has at most 10 characters (it has 11).']
+ error_atleast = ['Ensure this value has at least 2 characters (it has 1).']
valid = {
- '21694681': u'21694681',
- 'RO21694681': u'21694681',
+ '21694681': '21694681',
+ 'RO21694681': '21694681',
}
invalid = {
'21694680': error_invalid,
@@ -71,9 +73,9 @@ class ROLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(ROCIFField, valid, invalid)
def test_ROCNPField(self):
- error_invalid = [u'Enter a valid CNP.']
- error_atleast = [u'Ensure this value has at least 13 characters (it has 10).']
- error_atmost = [u'Ensure this value has at most 13 characters (it has 14).']
+ error_invalid = ['Enter a valid CNP.']
+ error_atleast = ['Ensure this value has at least 13 characters (it has 10).']
+ error_atmost = ['Ensure this value has at most 13 characters (it has 14).']
valid = {
'1981211204489': '1981211204489',
}
@@ -87,12 +89,12 @@ class ROLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(ROCNPField, valid, invalid)
def test_ROCountyField(self):
- error_format = [u'Enter a Romanian county code or name.']
+ error_format = ['Enter a Romanian county code or name.']
valid = {
'CJ': 'CJ',
'cj': 'CJ',
- u'Argeş': 'AG',
- u'argeş': 'AG',
+ 'Argeş': 'AG',
+ 'argeş': 'AG',
}
invalid = {
'Arges': error_format,
@@ -100,8 +102,8 @@ class ROLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(ROCountyField, valid, invalid)
def test_ROIBANField(self):
- error_invalid = [u'Enter a valid IBAN in ROXX-XXXX-XXXX-XXXX-XXXX-XXXX format']
- error_atleast = [u'Ensure this value has at least 24 characters (it has 23).']
+ error_invalid = ['Enter a valid IBAN in ROXX-XXXX-XXXX-XXXX-XXXX-XXXX format']
+ error_atleast = ['Ensure this value has at least 24 characters (it has 23).']
valid = {
'RO56RZBR0000060003291177': 'RO56RZBR0000060003291177',
'RO56-RZBR-0000-0600-0329-1177': 'RO56RZBR0000060003291177',
@@ -114,9 +116,9 @@ class ROLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(ROIBANField, valid, invalid)
def test_ROPhoneNumberField(self):
- error_format = [u'Phone numbers must be in XXXX-XXXXXX format.']
- error_atleast = [u'Ensure this value has at least 10 characters (it has 9).']
- error_invalid = [u'Phone numbers must be in XXXX-XXXXXX format.']
+ error_format = ['Phone numbers must be in XXXX-XXXXXX format.']
+ error_atleast = ['Ensure this value has at least 10 characters (it has 9).']
+ error_invalid = ['Phone numbers must be in XXXX-XXXXXX format.']
valid = {
'0264485936': '0264485936',
'(0264)-485936': '0264485936',
@@ -128,9 +130,9 @@ class ROLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(ROPhoneNumberField, valid, invalid)
def test_ROPostalCodeField(self):
- error_atleast = [u'Ensure this value has at least 6 characters (it has 5).']
- error_atmost = [u'Ensure this value has at most 6 characters (it has 7).']
- error_invalid = [u'Enter a valid postal code in the format XXXXXX']
+ error_atleast = ['Ensure this value has at least 6 characters (it has 5).']
+ error_atmost = ['Ensure this value has at most 6 characters (it has 7).']
+ error_invalid = ['Enter a valid postal code in the format XXXXXX']
valid = {
'400473': '400473',
diff --git a/tests/regressiontests/localflavor/ru/tests.py b/tests/regressiontests/localflavor/ru/tests.py
index bb85fe8181..758c5ae7d8 100644
--- a/tests/regressiontests/localflavor/ru/tests.py
+++ b/tests/regressiontests/localflavor/ru/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.ru.forms import *
from django.test import SimpleTestCase
@@ -6,7 +8,7 @@ from django.test import SimpleTestCase
class RULocalFlavorTests(SimpleTestCase):
def test_RUPassportNumberField(self):
- error = [u'Enter a passport number in the format XXXX XXXXXX.']
+ error = ['Enter a passport number in the format XXXX XXXXXX.']
valid = {
'1981 211204': '1981 211204',
'0305 967876': '0305 967876',
@@ -19,7 +21,7 @@ class RULocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(RUPassportNumberField, valid, invalid)
def test_RUAlienPassportNumberField(self):
- error = [u'Enter a passport number in the format XX XXXXXXX.']
+ error = ['Enter a passport number in the format XX XXXXXXX.']
valid = {
'19 8111204': '19 8111204',
'03 0567876': '03 0567876',
@@ -32,7 +34,7 @@ class RULocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(RUAlienPassportNumberField, valid, invalid)
def test_RUPostalCodeField(self):
- error = [u'Enter a postal code in the format XXXXXX.']
+ error = ['Enter a postal code in the format XXXXXX.']
valid = {
'987654': '987654',
'123456': '123456'
@@ -46,7 +48,7 @@ class RULocalFlavorTests(SimpleTestCase):
def test_RUCountySelect(self):
f = RUCountySelect()
- out = u'''<select name="county">
+ out = '''<select name="county">
<option value="Central Federal County">Central Federal County</option>
<option value="South Federal County">South Federal County</option>
<option value="North-West Federal County">North-West Federal County</option>
@@ -60,7 +62,7 @@ class RULocalFlavorTests(SimpleTestCase):
def test_RURegionSelect(self):
f = RURegionSelect()
- out = u'''<select name="region">
+ out = '''<select name="region">
<option value="77">Moskva</option>
<option value="78">Saint-Peterburg</option>
<option value="50">Moskovskaya oblast&#39;</option>
diff --git a/tests/regressiontests/localflavor/se/tests.py b/tests/regressiontests/localflavor/se/tests.py
index ead9053ea2..f61c61e9d4 100644
--- a/tests/regressiontests/localflavor/se/tests.py
+++ b/tests/regressiontests/localflavor/se/tests.py
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
from django.contrib.localflavor.se.forms import (SECountySelect,
SEOrganisationNumberField, SEPersonalIdentityNumberField,
SEPostalCodeField)
@@ -24,7 +26,7 @@ class SELocalFlavorTests(SimpleTestCase):
def test_SECountySelect(self):
f = SECountySelect()
- out = u'''<select name="swedish_county">
+ out = '''<select name="swedish_county">
<option value="AB">Stockholm</option>
<option value="AC">V\xe4sterbotten</option>
<option value="BD">Norrbotten</option>
@@ -50,7 +52,7 @@ class SELocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('swedish_county', 'E'), out)
def test_SEOrganizationNumberField(self):
- error_invalid = [u'Enter a valid Swedish organisation number.']
+ error_invalid = ['Enter a valid Swedish organisation number.']
valid = {
'870512-1989': '198705121989',
'19870512-1989': '198705121989',
@@ -95,8 +97,8 @@ class SELocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(SEOrganisationNumberField, valid, invalid)
def test_SEPersonalIdentityNumberField(self):
- error_invalid = [u'Enter a valid Swedish personal identity number.']
- error_coord = [u'Co-ordination numbers are not allowed.']
+ error_invalid = ['Enter a valid Swedish personal identity number.']
+ error_coord = ['Co-ordination numbers are not allowed.']
valid = {
'870512-1989': '198705121989',
'870512-2128': '198705122128',
@@ -148,7 +150,7 @@ class SELocalFlavorTests(SimpleTestCase):
field_kwargs=kwargs)
def test_SEPostalCodeField(self):
- error_format = [u'Enter a Swedish postal code in the format XXXXX.']
+ error_format = ['Enter a Swedish postal code in the format XXXXX.']
valid = {
'589 37': '58937',
'58937': '58937',
diff --git a/tests/regressiontests/localflavor/si/tests.py b/tests/regressiontests/localflavor/si/tests.py
index 4e8fe25c47..123683bff4 100644
--- a/tests/regressiontests/localflavor/si/tests.py
+++ b/tests/regressiontests/localflavor/si/tests.py
@@ -1,4 +1,5 @@
# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
from datetime import date
@@ -9,7 +10,7 @@ from django.test import SimpleTestCase
class SILocalFlavorTests(SimpleTestCase):
def test_SITaxNumberField(self):
- error_invalid = [u'Enter a valid tax number in form SIXXXXXXXX']
+ error_invalid = ['Enter a valid tax number in form SIXXXXXXXX']
valid = {
'15012557': '15012557',
'SI15012557': '15012557',
@@ -26,9 +27,9 @@ class SILocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(SITaxNumberField, valid, invalid)
def test_SIEMSOField(self):
- error_invalid = [u'This field should contain exactly 13 digits.']
- error_invalid_date = [u'The first 7 digits of the EMSO must represent a valid past date.']
- error_invalid_chksum = [u'The EMSO is not valid.']
+ error_invalid = ['This field should contain exactly 13 digits.']
+ error_invalid_date = ['The first 7 digits of the EMSO must represent a valid past date.']
+ error_invalid_chksum = ['The EMSO is not valid.']
valid = {
'0205951500462': '0205951500462',
'2309002500068': '2309002500068',
@@ -58,7 +59,7 @@ class SILocalFlavorTests(SimpleTestCase):
self.assertEqual(f.info, info)
def test_SIPhoneNumberField(self):
- error_invalid = [u'Enter phone number in form +386XXXXXXXX or 0XXXXXXXX.']
+ error_invalid = ['Enter phone number in form +386XXXXXXXX or 0XXXXXXXX.']
valid = {
'+38640999999': '40999999',
'+3861999999': '1999999',
@@ -81,14 +82,14 @@ class SILocalFlavorTests(SimpleTestCase):
'1000': '1000'
}
invalid = {
- '1113': [u'Select a valid choice. 1113 is not one of the available choices.'],
- '111': [u'Select a valid choice. 111 is not one of the available choices.'],
+ '1113': ['Select a valid choice. 1113 is not one of the available choices.'],
+ '111': ['Select a valid choice. 111 is not one of the available choices.'],
}
self.assertFieldOutput(SIPostalCodeField, valid, invalid)
def test_SIPostalCodeSelect(self):
f = SIPostalCodeSelect()
- out = u'''<select name="Kranj">
+ out = '''<select name="Kranj">
<option value="8341">Adle\u0161i\u010di</option>
<option value="5270">Ajdov\u0161\u010dina</option>
<option value="6280">Ankaran - Ancarano</option>
diff --git a/tests/regressiontests/localflavor/sk/tests.py b/tests/regressiontests/localflavor/sk/tests.py
index 319fd827be..b51fee2681 100644
--- a/tests/regressiontests/localflavor/sk/tests.py
+++ b/tests/regressiontests/localflavor/sk/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.sk.forms import (SKRegionSelect,
SKPostalCodeField, SKDistrictSelect)
@@ -7,7 +9,7 @@ from django.test import SimpleTestCase
class SKLocalFlavorTests(SimpleTestCase):
def test_SKRegionSelect(self):
f = SKRegionSelect()
- out = u'''<select name="regions">
+ out = '''<select name="regions">
<option value="BB">Banska Bystrica region</option>
<option value="BA">Bratislava region</option>
<option value="KE">Kosice region</option>
@@ -21,7 +23,7 @@ class SKLocalFlavorTests(SimpleTestCase):
def test_SKDistrictSelect(self):
f = SKDistrictSelect()
- out = u'''<select name="Districts">
+ out = '''<select name="Districts">
<option value="BB">Banska Bystrica</option>
<option value="BS">Banska Stiavnica</option>
<option value="BJ">Bardejov</option>
@@ -105,7 +107,7 @@ class SKLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('Districts', 'RK'), out)
def test_SKPostalCodeField(self):
- error_format = [u'Enter a postal code in the format XXXXX or XXX XX.']
+ error_format = ['Enter a postal code in the format XXXXX or XXX XX.']
valid = {
'91909': '91909',
'917 01': '91701',
diff --git a/tests/regressiontests/localflavor/us/tests.py b/tests/regressiontests/localflavor/us/tests.py
index a7f84ac4ae..45967cb9dc 100644
--- a/tests/regressiontests/localflavor/us/tests.py
+++ b/tests/regressiontests/localflavor/us/tests.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from django.contrib.localflavor.us.forms import (USZipCodeField,
USPhoneNumberField, USStateField, USStateSelect,
@@ -23,7 +23,7 @@ class USLocalFlavorTests(SimpleTestCase):
"""Test that required USStateFields throw appropriate errors."""
form = USPlaceForm({'state':'GA', 'name':'Place in GA'})
self.assertFalse(form.is_valid())
- self.assertEqual(form.errors['state_req'], [u'This field is required.'])
+ self.assertEqual(form.errors['state_req'], ['This field is required.'])
def test_field_blank_option(self):
"""Test that the empty option is there."""
@@ -164,7 +164,7 @@ class USLocalFlavorTests(SimpleTestCase):
def test_USStateSelect(self):
f = USStateSelect()
- out = u'''<select name="state">
+ out = '''<select name="state">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AS">American Samoa</option>
@@ -228,7 +228,7 @@ class USLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('state', 'IL'), out)
def test_USZipCodeField(self):
- error_format = [u'Enter a zip code in the format XXXXX or XXXXX-XXXX.']
+ error_format = ['Enter a zip code in the format XXXXX or XXXXX-XXXX.']
valid = {
'60606': '60606',
60606: '60606',
@@ -243,7 +243,7 @@ class USLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(USZipCodeField, valid, invalid)
def test_USPhoneNumberField(self):
- error_format = [u'Phone numbers must be in XXX-XXX-XXXX format.']
+ error_format = ['Phone numbers must be in XXX-XXX-XXXX format.']
valid = {
'312-555-1212': '312-555-1212',
'3125551212': '312-555-1212',
@@ -261,7 +261,7 @@ class USLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(USPhoneNumberField, valid, invalid)
def test_USStateField(self):
- error_invalid = [u'Enter a U.S. state or territory.']
+ error_invalid = ['Enter a U.S. state or territory.']
valid = {
'il': 'IL',
'IL': 'IL',
@@ -274,7 +274,7 @@ class USLocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(USStateField, valid, invalid)
def test_USSocialSecurityNumberField(self):
- error_invalid = [u'Enter a valid U.S. Social Security number in XXX-XX-XXXX format.']
+ error_invalid = ['Enter a valid U.S. Social Security number in XXX-XX-XXXX format.']
valid = {
'987-65-4330': '987-65-4330',
diff --git a/tests/regressiontests/localflavor/uy/tests.py b/tests/regressiontests/localflavor/uy/tests.py
index eda0068d3e..5bbbbe4122 100644
--- a/tests/regressiontests/localflavor/uy/tests.py
+++ b/tests/regressiontests/localflavor/uy/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.uy.forms import UYDepartamentSelect, UYCIField
from django.contrib.localflavor.uy.util import get_validation_digit
@@ -7,7 +9,7 @@ from django.test import SimpleTestCase
class UYLocalFlavorTests(SimpleTestCase):
def test_UYDepartmentSelect(self):
f = UYDepartamentSelect()
- out = u'''<select name="departamentos">
+ out = '''<select name="departamentos">
<option value="G">Artigas</option>
<option value="A">Canelones</option>
<option value="E">Cerro Largo</option>
@@ -31,8 +33,8 @@ class UYLocalFlavorTests(SimpleTestCase):
self.assertHTMLEqual(f.render('departamentos', 'S'), out)
def test_UYCIField(self):
- error_format = [u'Enter a valid CI number in X.XXX.XXX-X,XXXXXXX-X or XXXXXXXX format.']
- error_invalid = [u'Enter a valid CI number.']
+ error_format = ['Enter a valid CI number in X.XXX.XXX-X,XXXXXXX-X or XXXXXXXX format.']
+ error_invalid = ['Enter a valid CI number.']
valid = {
'4098053': '4098053',
'409805-3': '409805-3',
@@ -42,9 +44,9 @@ class UYLocalFlavorTests(SimpleTestCase):
'1.005.411-2': '1.005.411-2',
}
invalid = {
- 'foo': [u'Enter a valid CI number in X.XXX.XXX-X,XXXXXXX-X or XXXXXXXX format.'],
- '409805-2': [u'Enter a valid CI number.'],
- '1.005.411-5': [u'Enter a valid CI number.'],
+ 'foo': ['Enter a valid CI number in X.XXX.XXX-X,XXXXXXX-X or XXXXXXXX format.'],
+ '409805-2': ['Enter a valid CI number.'],
+ '1.005.411-5': ['Enter a valid CI number.'],
}
self.assertFieldOutput(UYCIField, valid, invalid)
self.assertEqual(get_validation_digit(409805), 3)
diff --git a/tests/regressiontests/localflavor/za/tests.py b/tests/regressiontests/localflavor/za/tests.py
index 948bd7f320..81e8d65eec 100644
--- a/tests/regressiontests/localflavor/za/tests.py
+++ b/tests/regressiontests/localflavor/za/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.localflavor.za.forms import ZAIDField, ZAPostCodeField
from django.test import SimpleTestCase
@@ -5,7 +7,7 @@ from django.test import SimpleTestCase
class ZALocalFlavorTests(SimpleTestCase):
def test_ZAIDField(self):
- error_invalid = [u'Enter a valid South African ID number']
+ error_invalid = ['Enter a valid South African ID number']
valid = {
'0002290001003': '0002290001003',
'000229 0001 003': '0002290001003',
@@ -18,7 +20,7 @@ class ZALocalFlavorTests(SimpleTestCase):
self.assertFieldOutput(ZAIDField, valid, invalid)
def test_ZAPostCodeField(self):
- error_invalid = [u'Enter a valid South African postal code']
+ error_invalid = ['Enter a valid South African postal code']
valid = {
'0000': '0000',
}
diff --git a/tests/regressiontests/logging_tests/tests.py b/tests/regressiontests/logging_tests/tests.py
index 887897a16f..4ae3c1b1a9 100644
--- a/tests/regressiontests/logging_tests/tests.py
+++ b/tests/regressiontests/logging_tests/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import copy
import warnings
@@ -215,8 +217,8 @@ class AdminEmailHandlerTest(TestCase):
AdminErrorHandler to fail.
Refs #17281.
"""
- message = u'Message \r\n with newlines'
- expected_subject = u'ERROR: Message \\r\\n with newlines'
+ message = 'Message \r\n with newlines'
+ expected_subject = 'ERROR: Message \\r\\n with newlines'
self.assertEqual(len(mail.outbox), 0)
diff --git a/tests/regressiontests/m2m_through_regress/models.py b/tests/regressiontests/m2m_through_regress/models.py
index ff71348931..1db3de1a4c 100644
--- a/tests/regressiontests/m2m_through_regress/models.py
+++ b/tests/regressiontests/m2m_through_regress/models.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.auth.models import User
from django.db import models
@@ -71,4 +73,4 @@ class CarDriver(models.Model):
driver = models.ForeignKey('Driver', to_field='name')
def __unicode__(self, ):
- return u"pk=%s car=%s driver=%s" % (str(self.pk), self.car, self.driver)
+ return "pk=%s car=%s driver=%s" % (str(self.pk), self.car, self.driver)
diff --git a/tests/regressiontests/mail/tests.py b/tests/regressiontests/mail/tests.py
index 85e73c197f..cdd6dd1b9e 100644
--- a/tests/regressiontests/mail/tests.py
+++ b/tests/regressiontests/mail/tests.py
@@ -1,4 +1,6 @@
# coding: utf-8
+from __future__ import unicode_literals
+
import asyncore
import email
import os
@@ -137,7 +139,7 @@ class MailTests(TestCase):
self.assertEqual(email.message()['To'], '=?utf-8?q?S=C3=BCrname=2C_Firstname?= <to@example.com>, other@example.com')
def test_unicode_headers(self):
- email = EmailMessage(u"Gżegżółka", "Content", "from@example.com", ["to@example.com"],
+ email = EmailMessage("Gżegżółka", "Content", "from@example.com", ["to@example.com"],
headers={"Sender": '"Firstname Sürname" <sender@example.com>',
"Comments": 'My Sürname is non-ASCII'})
message = email.message()
@@ -158,7 +160,7 @@ class MailTests(TestCase):
msg.attach_alternative(html_content, "text/html")
msg.encoding = 'iso-8859-1'
self.assertEqual(msg.message()['To'], '=?iso-8859-1?q?S=FCrname=2C_Firstname?= <to@example.com>')
- self.assertEqual(msg.message()['Subject'].encode(), u'=?iso-8859-1?q?Message_from_Firstname_S=FCrname?=')
+ self.assertEqual(msg.message()['Subject'].encode(), '=?iso-8859-1?q?Message_from_Firstname_S=FCrname?=')
def test_encoding(self):
"""
@@ -205,11 +207,11 @@ class MailTests(TestCase):
content = 'This is the message.'
msg = EmailMessage(subject, content, from_email, [to], headers=headers)
# Unicode in file name
- msg.attach(u"une pièce jointe.pdf", b"%PDF-1.4.%...", mimetype="application/pdf")
+ msg.attach("une pièce jointe.pdf", b"%PDF-1.4.%...", mimetype="application/pdf")
msg_str = msg.message().as_string()
message = email.message_from_string(msg_str)
payload = message.get_payload()
- self.assertEqual(payload[1].get_filename(), u'une pièce jointe.pdf')
+ self.assertEqual(payload[1].get_filename(), 'une pièce jointe.pdf')
def test_dummy_backend(self):
"""
@@ -310,7 +312,7 @@ class MailTests(TestCase):
self.assertFalse(b'Content-Transfer-Encoding: quoted-printable' in s)
self.assertTrue(b'Content-Transfer-Encoding: 8bit' in s)
- msg = EmailMessage('Subject', u'Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
+ msg = EmailMessage('Subject', 'Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
s = msg.message().as_string()
self.assertFalse(b'Content-Transfer-Encoding: quoted-printable' in s)
self.assertTrue(b'Content-Transfer-Encoding: 8bit' in s)
@@ -444,7 +446,7 @@ class BaseEmailBackendTests(object):
"""
Regression test for #14301
"""
- self.assertTrue(send_mail('Subject', 'Content', 'from@öäü.com', [u'to@öäü.com']))
+ self.assertTrue(send_mail('Subject', 'Content', 'from@öäü.com', ['to@öäü.com']))
message = self.get_the_message()
self.assertEqual(message.get('subject'), 'Subject')
self.assertEqual(message.get('from'), 'from@xn--4ca9at.com')
@@ -452,7 +454,7 @@ class BaseEmailBackendTests(object):
self.flush_mailbox()
m = EmailMessage('Subject', 'Content', 'from@öäü.com',
- [u'to@öäü.com'], cc=[u'cc@öäü.com'])
+ ['to@öäü.com'], cc=['cc@öäü.com'])
m.send()
message = self.get_the_message()
self.assertEqual(message.get('subject'), 'Subject')
diff --git a/tests/regressiontests/many_to_one_regress/models.py b/tests/regressiontests/many_to_one_regress/models.py
index 53348a753d..1e59c4c8c8 100644
--- a/tests/regressiontests/many_to_one_regress/models.py
+++ b/tests/regressiontests/many_to_one_regress/models.py
@@ -1,6 +1,7 @@
"""
Regression tests for a few ForeignKey bugs.
"""
+from __future__ import unicode_literals
from django.db import models
@@ -43,4 +44,4 @@ class Relation(models.Model):
right = models.ForeignKey(Record, related_name='right_set')
def __unicode__(self):
- return u"%s - %s" % (self.left.category.name, self.right.category.name)
+ return "%s - %s" % (self.left.category.name, self.right.category.name)
diff --git a/tests/regressiontests/model_fields/tests.py b/tests/regressiontests/model_fields/tests.py
index 9c0f888a99..5d3d42ef2a 100644
--- a/tests/regressiontests/model_fields/tests.py
+++ b/tests/regressiontests/model_fields/tests.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import datetime
from decimal import Decimal
@@ -78,8 +78,8 @@ class DecimalFieldTests(test.TestCase):
def test_format(self):
f = models.DecimalField(max_digits=5, decimal_places=1)
- self.assertEqual(f._format(f.to_python(2)), u'2.0')
- self.assertEqual(f._format(f.to_python('2.6')), u'2.6')
+ self.assertEqual(f._format(f.to_python(2)), '2.0')
+ self.assertEqual(f._format(f.to_python('2.6')), '2.6')
self.assertEqual(f._format(None), None)
def test_get_db_prep_lookup(self):
@@ -92,7 +92,7 @@ class DecimalFieldTests(test.TestCase):
We should be able to filter decimal fields using strings (#8023)
"""
Foo.objects.create(id=1, a='abc', d=Decimal("12.34"))
- self.assertEqual(list(Foo.objects.filter(d=u'1.23')), [])
+ self.assertEqual(list(Foo.objects.filter(d='1.23')), [])
def test_save_without_float_conversion(self):
"""
@@ -168,7 +168,7 @@ class BooleanFieldTests(unittest.TestCase):
Test that BooleanField with choices and defaults doesn't generate a
formfield with the blank option (#9640, #10549).
"""
- choices = [(1, u'Si'), (2, 'No')]
+ choices = [(1, 'Si'), (2, 'No')]
f = models.BooleanField(choices=choices, default=1, null=True)
self.assertEqual(f.formfield().choices, [('', '---------')] + choices)
diff --git a/tests/regressiontests/model_forms_regress/models.py b/tests/regressiontests/model_forms_regress/models.py
index d070a9be75..9259e260f0 100644
--- a/tests/regressiontests/model_forms_regress/models.py
+++ b/tests/regressiontests/model_forms_regress/models.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import os
from django.core.exceptions import ValidationError
@@ -13,7 +15,7 @@ class Triple(models.Model):
right = models.IntegerField()
class Meta:
- unique_together = (('left', 'middle'), (u'middle', u'right'))
+ unique_together = (('left', 'middle'), ('middle', 'right'))
class FilePathModel(models.Model):
path = models.FilePathField(path=os.path.dirname(__file__), match=".*\.py$", blank=True)
diff --git a/tests/regressiontests/model_forms_regress/tests.py b/tests/regressiontests/model_forms_regress/tests.py
index d33f52af9a..a0f9bba170 100644
--- a/tests/regressiontests/model_forms_regress/tests.py
+++ b/tests/regressiontests/model_forms_regress/tests.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from datetime import date
@@ -134,7 +134,7 @@ class ManyToManyCallableInitialTests(TestCase):
# Create a ModelForm, instantiate it, and check that the output is as expected
ModelForm = modelform_factory(Article, formfield_callback=formfield_for_dbfield)
form = ModelForm()
- self.assertHTMLEqual(form.as_ul(), u"""<li><label for="id_headline">Headline:</label> <input id="id_headline" type="text" name="headline" maxlength="100" /></li>
+ self.assertHTMLEqual(form.as_ul(), """<li><label for="id_headline">Headline:</label> <input id="id_headline" type="text" name="headline" maxlength="100" /></li>
<li><label for="id_publications">Publications:</label> <select multiple="multiple" name="publications" id="id_publications">
<option value="%d" selected="selected">First Book</option>
<option value="%d" selected="selected">Second Book</option>
@@ -194,7 +194,7 @@ class OneToOneFieldTests(TestCase):
publication = Publication.objects.create(title="Pravda",
date_published=date(1991, 8, 22))
author = Author.objects.create(publication=publication, full_name='John Doe')
- form = AuthorForm({'publication':u'', 'full_name':'John Doe'}, instance=author)
+ form = AuthorForm({'publication':'', 'full_name':'John Doe'}, instance=author)
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data['publication'], None)
author = form.save()
@@ -212,7 +212,7 @@ class OneToOneFieldTests(TestCase):
publication = Publication.objects.create(title="Pravda",
date_published=date(1991, 8, 22))
author = Author1.objects.create(publication=publication, full_name='John Doe')
- form = AuthorForm({'publication':u'', 'full_name':'John Doe'}, instance=author)
+ form = AuthorForm({'publication':'', 'full_name':'John Doe'}, instance=author)
self.assertTrue(not form.is_valid())
@@ -419,7 +419,7 @@ class FileFieldTests(unittest.TestCase):
data={'myfile-clear': 'true'})
self.assertTrue(not form.is_valid())
self.assertEqual(form.errors['myfile'],
- [u'Please either submit a file or check the clear checkbox, not both.'])
+ ['Please either submit a file or check the clear checkbox, not both.'])
rendered = unicode(form)
self.assertTrue('something.txt' in rendered)
self.assertTrue('myfile-clear' in rendered)
@@ -435,8 +435,8 @@ class EditionForm(forms.ModelForm):
class UniqueErrorsTests(TestCase):
def setUp(self):
- self.author1 = Person.objects.create(name=u'Author #1')
- self.author2 = Person.objects.create(name=u'Author #2')
+ self.author1 = Person.objects.create(name='Author #1')
+ self.author2 = Person.objects.create(name='Author #2')
self.pub1 = Publication.objects.create(title='Pub #1', date_published=date(2000, 10, 31))
self.pub2 = Publication.objects.create(title='Pub #2', date_published=date(2004, 1, 5))
form = EditionForm(data={'author': self.author1.pk, 'publication': self.pub1.pk, 'edition': 1, 'isbn': '9783161484100'})
@@ -444,13 +444,13 @@ class UniqueErrorsTests(TestCase):
def test_unique_error_message(self):
form = EditionForm(data={'author': self.author1.pk, 'publication': self.pub2.pk, 'edition': 1, 'isbn': '9783161484100'})
- self.assertEqual(form.errors, {'isbn': [u'Edition with this Isbn already exists.']})
+ self.assertEqual(form.errors, {'isbn': ['Edition with this Isbn already exists.']})
def test_unique_together_error_message(self):
form = EditionForm(data={'author': self.author1.pk, 'publication': self.pub1.pk, 'edition': 2, 'isbn': '9783161489999'})
- self.assertEqual(form.errors, {'__all__': [u'Edition with this Author and Publication already exists.']})
+ self.assertEqual(form.errors, {'__all__': ['Edition with this Author and Publication already exists.']})
form = EditionForm(data={'author': self.author2.pk, 'publication': self.pub1.pk, 'edition': 1, 'isbn': '9783161487777'})
- self.assertEqual(form.errors, {'__all__': [u'Edition with this Publication and Edition already exists.']})
+ self.assertEqual(form.errors, {'__all__': ['Edition with this Publication and Edition already exists.']})
class EmptyFieldsTestCase(TestCase):
diff --git a/tests/regressiontests/model_formsets_regress/tests.py b/tests/regressiontests/model_formsets_regress/tests.py
index f1e935e2ea..68ebe48bde 100644
--- a/tests/regressiontests/model_formsets_regress/tests.py
+++ b/tests/regressiontests/model_formsets_regress/tests.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from django import forms
from django.forms.formsets import BaseFormSet, DELETION_FIELD_NAME
@@ -22,13 +22,13 @@ class InlineFormsetTests(TestCase):
# Now create a new User and UserSite instance
data = {
- 'serial': u'1',
- 'username': u'apollo13',
- 'usersite_set-TOTAL_FORMS': u'1',
- 'usersite_set-INITIAL_FORMS': u'0',
- 'usersite_set-MAX_NUM_FORMS': u'0',
- 'usersite_set-0-data': u'10',
- 'usersite_set-0-user': u'apollo13'
+ 'serial': '1',
+ 'username': 'apollo13',
+ 'usersite_set-TOTAL_FORMS': '1',
+ 'usersite_set-INITIAL_FORMS': '0',
+ 'usersite_set-MAX_NUM_FORMS': '0',
+ 'usersite_set-0-data': '10',
+ 'usersite_set-0-user': 'apollo13'
}
user = User()
form = Form(data)
@@ -42,47 +42,47 @@ class InlineFormsetTests(TestCase):
form_set.save()
usersite = UserSite.objects.all().values()
self.assertEqual(usersite[0]['data'], 10)
- self.assertEqual(usersite[0]['user_id'], u'apollo13')
+ self.assertEqual(usersite[0]['user_id'], 'apollo13')
else:
self.fail('Errors found on formset:%s' % form_set.errors)
# Now update the UserSite instance
data = {
- 'usersite_set-TOTAL_FORMS': u'1',
- 'usersite_set-INITIAL_FORMS': u'1',
- 'usersite_set-MAX_NUM_FORMS': u'0',
+ 'usersite_set-TOTAL_FORMS': '1',
+ 'usersite_set-INITIAL_FORMS': '1',
+ 'usersite_set-MAX_NUM_FORMS': '0',
'usersite_set-0-id': unicode(usersite[0]['id']),
- 'usersite_set-0-data': u'11',
- 'usersite_set-0-user': u'apollo13'
+ 'usersite_set-0-data': '11',
+ 'usersite_set-0-user': 'apollo13'
}
form_set = FormSet(data, instance=user)
if form_set.is_valid():
form_set.save()
usersite = UserSite.objects.all().values()
self.assertEqual(usersite[0]['data'], 11)
- self.assertEqual(usersite[0]['user_id'], u'apollo13')
+ self.assertEqual(usersite[0]['user_id'], 'apollo13')
else:
self.fail('Errors found on formset:%s' % form_set.errors)
# Now add a new UserSite instance
data = {
- 'usersite_set-TOTAL_FORMS': u'2',
- 'usersite_set-INITIAL_FORMS': u'1',
- 'usersite_set-MAX_NUM_FORMS': u'0',
+ 'usersite_set-TOTAL_FORMS': '2',
+ 'usersite_set-INITIAL_FORMS': '1',
+ 'usersite_set-MAX_NUM_FORMS': '0',
'usersite_set-0-id': unicode(usersite[0]['id']),
- 'usersite_set-0-data': u'11',
- 'usersite_set-0-user': u'apollo13',
- 'usersite_set-1-data': u'42',
- 'usersite_set-1-user': u'apollo13'
+ 'usersite_set-0-data': '11',
+ 'usersite_set-0-user': 'apollo13',
+ 'usersite_set-1-data': '42',
+ 'usersite_set-1-user': 'apollo13'
}
form_set = FormSet(data, instance=user)
if form_set.is_valid():
form_set.save()
usersite = UserSite.objects.all().values().order_by('data')
self.assertEqual(usersite[0]['data'], 11)
- self.assertEqual(usersite[0]['user_id'], u'apollo13')
+ self.assertEqual(usersite[0]['user_id'], 'apollo13')
self.assertEqual(usersite[1]['data'], 42)
- self.assertEqual(usersite[1]['user_id'], u'apollo13')
+ self.assertEqual(usersite[1]['user_id'], 'apollo13')
else:
self.fail('Errors found on formset:%s' % form_set.errors)
@@ -98,11 +98,11 @@ class InlineFormsetTests(TestCase):
# Now create a new Restaurant and Manager instance
data = {
- 'name': u"Guido's House of Pasta",
- 'manager_set-TOTAL_FORMS': u'1',
- 'manager_set-INITIAL_FORMS': u'0',
- 'manager_set-MAX_NUM_FORMS': u'0',
- 'manager_set-0-name': u'Guido Van Rossum'
+ 'name': "Guido's House of Pasta",
+ 'manager_set-TOTAL_FORMS': '1',
+ 'manager_set-INITIAL_FORMS': '0',
+ 'manager_set-MAX_NUM_FORMS': '0',
+ 'manager_set-0-name': 'Guido Van Rossum'
}
restaurant = User()
form = Form(data)
@@ -121,11 +121,11 @@ class InlineFormsetTests(TestCase):
# Now update the Manager instance
data = {
- 'manager_set-TOTAL_FORMS': u'1',
- 'manager_set-INITIAL_FORMS': u'1',
- 'manager_set-MAX_NUM_FORMS': u'0',
+ 'manager_set-TOTAL_FORMS': '1',
+ 'manager_set-INITIAL_FORMS': '1',
+ 'manager_set-MAX_NUM_FORMS': '0',
'manager_set-0-id': unicode(manager[0]['id']),
- 'manager_set-0-name': u'Terry Gilliam'
+ 'manager_set-0-name': 'Terry Gilliam'
}
form_set = FormSet(data, instance=restaurant)
if form_set.is_valid():
@@ -137,12 +137,12 @@ class InlineFormsetTests(TestCase):
# Now add a new Manager instance
data = {
- 'manager_set-TOTAL_FORMS': u'2',
- 'manager_set-INITIAL_FORMS': u'1',
- 'manager_set-MAX_NUM_FORMS': u'0',
+ 'manager_set-TOTAL_FORMS': '2',
+ 'manager_set-INITIAL_FORMS': '1',
+ 'manager_set-MAX_NUM_FORMS': '0',
'manager_set-0-id': unicode(manager[0]['id']),
- 'manager_set-0-name': u'Terry Gilliam',
- 'manager_set-1-name': u'John Cleese'
+ 'manager_set-0-name': 'Terry Gilliam',
+ 'manager_set-1-name': 'John Cleese'
}
form_set = FormSet(data, instance=restaurant)
if form_set.is_valid():
@@ -185,12 +185,12 @@ class InlineFormsetTests(TestCase):
# Add a new host, modify previous host, and save-as-new
data = {
- 'host_set-TOTAL_FORMS': u'2',
- 'host_set-INITIAL_FORMS': u'1',
- 'host_set-MAX_NUM_FORMS': u'0',
+ 'host_set-TOTAL_FORMS': '2',
+ 'host_set-INITIAL_FORMS': '1',
+ 'host_set-MAX_NUM_FORMS': '0',
'host_set-0-id': unicode(host1.id),
- 'host_set-0-hostname': u'tranquility.hub.dal.net',
- 'host_set-1-hostname': u'matrix.de.eu.dal.net'
+ 'host_set-0-hostname': 'tranquility.hub.dal.net',
+ 'host_set-1-hostname': 'matrix.de.eu.dal.net'
}
# To save a formset as new, it needs a new hub instance
@@ -212,7 +212,7 @@ class InlineFormsetTests(TestCase):
formset = FormSet(instance=user, initial=[{'data': 41}, {'data': 42}])
self.assertEqual(formset.forms[0].initial['data'], 7)
self.assertEqual(formset.extra_forms[0].initial['data'], 41)
- self.assertTrue(u'value="42"' in formset.extra_forms[1].as_p())
+ self.assertTrue('value="42"' in formset.extra_forms[1].as_p())
class FormsetTests(TestCase):
@@ -222,15 +222,15 @@ class FormsetTests(TestCase):
'''
Formset = modelformset_factory(User)
data = {
- 'form-TOTAL_FORMS': u'2',
- 'form-INITIAL_FORMS': u'0',
- 'form-MAX_NUM_FORMS': u'0',
+ 'form-TOTAL_FORMS': '2',
+ 'form-INITIAL_FORMS': '0',
+ 'form-MAX_NUM_FORMS': '0',
'form-0-id': '',
- 'form-0-username': u'apollo13',
- 'form-0-serial': u'1',
+ 'form-0-username': 'apollo13',
+ 'form-0-serial': '1',
'form-1-id': '',
- 'form-1-username': u'apollo13',
- 'form-1-serial': u'2',
+ 'form-1-username': 'apollo13',
+ 'form-1-serial': '2',
}
formset = Formset(data)
# check if the returned error classes are correct
@@ -244,17 +244,17 @@ class FormsetTests(TestCase):
def test_initial_data(self):
User.objects.create(username="bibi", serial=1)
Formset = modelformset_factory(User, extra=2)
- formset = Formset(initial=[{'username': u'apollo11'}, {'username': u'apollo12'}])
+ formset = Formset(initial=[{'username': 'apollo11'}, {'username': 'apollo12'}])
self.assertEqual(formset.forms[0].initial['username'], "bibi")
self.assertEqual(formset.extra_forms[0].initial['username'], "apollo11")
- self.assertTrue(u'value="apollo12"' in formset.extra_forms[1].as_p())
+ self.assertTrue('value="apollo12"' in formset.extra_forms[1].as_p())
def test_extraneous_query_is_not_run(self):
Formset = modelformset_factory(Network)
- data = {u'test-TOTAL_FORMS': u'1',
- u'test-INITIAL_FORMS': u'0',
- u'test-MAX_NUM_FORMS': u'',
- u'test-0-name': u'Random Place', }
+ data = {'test-TOTAL_FORMS': '1',
+ 'test-INITIAL_FORMS': '0',
+ 'test-MAX_NUM_FORMS': '',
+ 'test-0-name': 'Random Place', }
with self.assertNumQueries(1):
formset = Formset(data, prefix="test")
formset.save()
diff --git a/tests/regressiontests/model_inheritance_regress/models.py b/tests/regressiontests/model_inheritance_regress/models.py
index 161569bcb3..5481298963 100644
--- a/tests/regressiontests/model_inheritance_regress/models.py
+++ b/tests/regressiontests/model_inheritance_regress/models.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import datetime
from django.db import models
@@ -10,20 +12,20 @@ class Place(models.Model):
ordering = ('name',)
def __unicode__(self):
- return u"%s the place" % self.name
+ return "%s the place" % self.name
class Restaurant(Place):
serves_hot_dogs = models.BooleanField()
serves_pizza = models.BooleanField()
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 ParkingLot(Place):
# An explicit link to the parent (we can control the attribute name).
@@ -31,7 +33,7 @@ class ParkingLot(Place):
capacity = models.IntegerField()
def __unicode__(self):
- return u"%s the parking lot" % self.name
+ return "%s the parking lot" % self.name
class ParkingLot2(Place):
# In lieu of any other connector, an existing OneToOneField will be
@@ -108,7 +110,7 @@ class AuditBase(models.Model):
class Meta:
abstract = True
- verbose_name_plural = u'Audits'
+ verbose_name_plural = 'Audits'
class CertificationAudit(AuditBase):
class Meta(AuditBase.Meta):
diff --git a/tests/regressiontests/model_inheritance_regress/tests.py b/tests/regressiontests/model_inheritance_regress/tests.py
index 3cb6f9d603..6855d70071 100644
--- a/tests/regressiontests/model_inheritance_regress/tests.py
+++ b/tests/regressiontests/model_inheritance_regress/tests.py
@@ -1,8 +1,7 @@
"""
Regression tests for Model inheritance behavior.
"""
-
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import datetime
from operator import attrgetter
@@ -53,14 +52,14 @@ class ModelInheritanceTest(TestCase):
dicts = list(Restaurant.objects.values('name','serves_hot_dogs'))
self.assertEqual(dicts, [{
- 'name': u"Guido's House of Pasta",
+ 'name': "Guido's House of Pasta",
'serves_hot_dogs': True
}])
dicts = list(ItalianRestaurant.objects.values(
'name','serves_hot_dogs','serves_gnocchi'))
self.assertEqual(dicts, [{
- 'name': u"Guido's House of Pasta",
+ 'name': "Guido's House of Pasta",
'serves_gnocchi': True,
'serves_hot_dogs': True,
}])
@@ -68,7 +67,7 @@ class ModelInheritanceTest(TestCase):
dicts = list(ParkingLot.objects.values('name','capacity'))
self.assertEqual(dicts, [{
'capacity': 100,
- 'name': u'Main St',
+ 'name': 'Main St',
}])
# You can also update objects when using a raw save.
@@ -95,14 +94,14 @@ class ModelInheritanceTest(TestCase):
dicts = list(Restaurant.objects.values('name','serves_hot_dogs'))
self.assertEqual(dicts, [{
- 'name': u"Guido's All New House of Pasta",
+ 'name': "Guido's All New House of Pasta",
'serves_hot_dogs': False,
}])
dicts = list(ItalianRestaurant.objects.values(
'name', 'serves_hot_dogs', 'serves_gnocchi'))
self.assertEqual(dicts, [{
- 'name': u"Guido's All New House of Pasta",
+ 'name': "Guido's All New House of Pasta",
'serves_gnocchi': False,
'serves_hot_dogs': False,
}])
@@ -110,7 +109,7 @@ class ModelInheritanceTest(TestCase):
dicts = list(ParkingLot.objects.values('name','capacity'))
self.assertEqual(dicts, [{
'capacity': 50,
- 'name': u'Derelict lot',
+ 'name': 'Derelict lot',
}])
# If you try to raw_save a parent attribute onto a child object,
@@ -124,7 +123,7 @@ class ModelInheritanceTest(TestCase):
dicts = list(ItalianRestaurant.objects.values(
'name','serves_hot_dogs','serves_gnocchi'))
self.assertEqual(dicts, [{
- 'name': u"Guido's All New House of Pasta",
+ 'name': "Guido's All New House of Pasta",
'serves_gnocchi': False,
'serves_hot_dogs': False,
}])
@@ -372,7 +371,7 @@ class ModelInheritanceTest(TestCase):
# verbose_name.
self.assertEqual(
InternalCertificationAudit._meta.verbose_name_plural,
- u'Audits'
+ 'Audits'
)
def test_inherited_nullable_exclude(self):
diff --git a/tests/regressiontests/model_inheritance_select_related/models.py b/tests/regressiontests/model_inheritance_select_related/models.py
index d5f4152d0a..f810531bff 100644
--- a/tests/regressiontests/model_inheritance_select_related/models.py
+++ b/tests/regressiontests/model_inheritance_select_related/models.py
@@ -2,6 +2,7 @@
Regression tests for the interaction between model inheritance and
select_related().
"""
+from __future__ import unicode_literals
from django.db import models
@@ -13,14 +14,14 @@ class Place(models.Model):
ordering = ('name',)
def __unicode__(self):
- return u"%s the place" % self.name
+ return "%s the place" % self.name
class Restaurant(Place):
serves_sushi = models.BooleanField()
serves_steak = models.BooleanField()
def __unicode__(self):
- return u"%s the restaurant" % self.name
+ return "%s the restaurant" % self.name
class Person(models.Model):
name = models.CharField(max_length=50)
diff --git a/tests/regressiontests/model_regress/tests.py b/tests/regressiontests/model_regress/tests.py
index 77bb4f23eb..7ba9d421d7 100644
--- a/tests/regressiontests/model_regress/tests.py
+++ b/tests/regressiontests/model_regress/tests.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import datetime
from operator import attrgetter
@@ -38,7 +38,7 @@ class ModelTests(TestCase):
# Empty strings should be returned as Unicode
a = Article.objects.get(pk=a.pk)
- self.assertEqual(a.misc_data, u'')
+ self.assertEqual(a.misc_data, '')
self.assertIs(type(a.misc_data), unicode)
def test_long_textfield(self):
diff --git a/tests/regressiontests/modeladmin/tests.py b/tests/regressiontests/modeladmin/tests.py
index 04b02eb36b..c2a1ca05ba 100644
--- a/tests/regressiontests/modeladmin/tests.py
+++ b/tests/regressiontests/modeladmin/tests.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from datetime import date
@@ -15,7 +15,7 @@ from django.core.exceptions import ImproperlyConfigured
from django.forms.models import BaseModelFormSet
from django.forms.widgets import Select
from django.test import TestCase
-from django.test.utils import override_settings
+from django.test.utils import override_settings, str_prefix
from django.utils import unittest
from .models import Band, Concert, ValidationTestModel, ValidationTestInlineModel
@@ -387,13 +387,13 @@ class ModelAdminTests(TestCase):
Select)
self.assertEqual(
list(cmafa.base_fields['main_band'].widget.choices),
- [(u'', u'---------'), (self.band.id, u'The Doors')])
+ [('', '---------'), (self.band.id, 'The Doors')])
self.assertEqual(
type(cmafa.base_fields['opening_band'].widget.widget), Select)
self.assertEqual(
list(cmafa.base_fields['opening_band'].widget.choices),
- [(u'', u'---------'), (self.band.id, u'The Doors')])
+ [('', '---------'), (self.band.id, 'The Doors')])
self.assertEqual(type(cmafa.base_fields['day'].widget), Select)
self.assertEqual(list(cmafa.base_fields['day'].widget.choices),
@@ -427,7 +427,7 @@ class ModelAdminTests(TestCase):
self.assertEqual(cmafa.base_fields['main_band'].widget.attrs,
{'class': 'radiolist inline'})
self.assertEqual(list(cmafa.base_fields['main_band'].widget.choices),
- [(self.band.id, u'The Doors')])
+ [(self.band.id, 'The Doors')])
self.assertEqual(
type(cmafa.base_fields['opening_band'].widget.widget),
@@ -436,7 +436,7 @@ class ModelAdminTests(TestCase):
{'class': 'radiolist'})
self.assertEqual(
list(cmafa.base_fields['opening_band'].widget.choices),
- [(u'', u'None'), (self.band.id, u'The Doors')])
+ [('', 'None'), (self.band.id, 'The Doors')])
self.assertEqual(type(cmafa.base_fields['day'].widget),
AdminRadioSelect)
@@ -450,7 +450,7 @@ class ModelAdminTests(TestCase):
self.assertEqual(cmafa.base_fields['transport'].widget.attrs,
{'class': 'radiolist inline'})
self.assertEqual(list(cmafa.base_fields['transport'].widget.choices),
- [('', u'None'), (1, 'Plane'), (2, 'Train'), (3, 'Bus')])
+ [('', 'None'), (1, 'Plane'), (2, 'Train'), (3, 'Bus')])
class AdminConcertForm(forms.ModelForm):
class Meta:
@@ -947,7 +947,7 @@ class ValidationTests(unittest.TestCase):
self.assertRaisesRegexp(
ImproperlyConfigured,
- "ValidationTestModelAdmin.list_display\[0\], 'non_existent_field' is not a callable or an attribute of 'ValidationTestModelAdmin' or found in the model 'ValidationTestModel'.",
+ str_prefix("ValidationTestModelAdmin.list_display\[0\], %(_)s'non_existent_field' is not a callable or an attribute of 'ValidationTestModelAdmin' or found in the model 'ValidationTestModel'."),
validate,
ValidationTestModelAdmin,
ValidationTestModel,
diff --git a/tests/regressiontests/multiple_database/tests.py b/tests/regressiontests/multiple_database/tests.py
index e2f433ece1..595c5edb3b 100644
--- a/tests/regressiontests/multiple_database/tests.py
+++ b/tests/regressiontests/multiple_database/tests.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import datetime
import pickle
@@ -172,14 +172,14 @@ class QueryTestCase(TestCase):
# Check that queries work across m2m joins
self.assertEqual(list(Book.objects.using('default').filter(authors__name='Marty Alchin').values_list('title', flat=True)),
- [u'Pro Django'])
+ ['Pro Django'])
self.assertEqual(list(Book.objects.using('other').filter(authors__name='Marty Alchin').values_list('title', flat=True)),
[])
self.assertEqual(list(Book.objects.using('default').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
[])
self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
- [u'Dive into Python'])
+ ['Dive into Python'])
# Reget the objects to clear caches
dive = Book.objects.using('other').get(title="Dive into Python")
@@ -187,10 +187,10 @@ class QueryTestCase(TestCase):
# Retrive related object by descriptor. Related objects should be database-baound
self.assertEqual(list(dive.authors.all().values_list('name', flat=True)),
- [u'Mark Pilgrim'])
+ ['Mark Pilgrim'])
self.assertEqual(list(mark.book_set.all().values_list('title', flat=True)),
- [u'Dive into Python'])
+ ['Dive into Python'])
def test_m2m_forward_operations(self):
"M2M forward manipulations are all constrained to a single DB"
@@ -211,14 +211,14 @@ class QueryTestCase(TestCase):
dive.authors.add(john)
self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
- [u'Dive into Python'])
+ ['Dive into Python'])
self.assertEqual(list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)),
- [u'Dive into Python'])
+ ['Dive into Python'])
# Remove the second author
dive.authors.remove(john)
self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
- [u'Dive into Python'])
+ ['Dive into Python'])
self.assertEqual(list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)),
[])
@@ -234,7 +234,7 @@ class QueryTestCase(TestCase):
self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
[])
self.assertEqual(list(Book.objects.using('other').filter(authors__name='Jane Brown').values_list('title', flat=True)),
- [u'Dive into Python'])
+ ['Dive into Python'])
def test_m2m_reverse_operations(self):
"M2M reverse manipulations are all constrained to a single DB"
@@ -254,14 +254,14 @@ class QueryTestCase(TestCase):
# Add a books to the m2m
mark.book_set.add(grease)
self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
- [u'Mark Pilgrim'])
+ ['Mark Pilgrim'])
self.assertEqual(list(Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)),
- [u'Mark Pilgrim'])
+ ['Mark Pilgrim'])
# Remove a book from the m2m
mark.book_set.remove(grease)
self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
- [u'Mark Pilgrim'])
+ ['Mark Pilgrim'])
self.assertEqual(list(Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)),
[])
@@ -277,7 +277,7 @@ class QueryTestCase(TestCase):
self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
[])
self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into HTML5').values_list('name', flat=True)),
- [u'Mark Pilgrim'])
+ ['Mark Pilgrim'])
def test_m2m_cross_database_protection(self):
"Operations that involve sharing M2M objects across databases raise an error"
@@ -418,14 +418,14 @@ class QueryTestCase(TestCase):
# Check that queries work across foreign key joins
self.assertEqual(list(Person.objects.using('default').filter(edited__title='Pro Django').values_list('name', flat=True)),
- [u'George Vilches'])
+ ['George Vilches'])
self.assertEqual(list(Person.objects.using('other').filter(edited__title='Pro Django').values_list('name', flat=True)),
[])
self.assertEqual(list(Person.objects.using('default').filter(edited__title='Dive into Python').values_list('name', flat=True)),
[])
self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)),
- [u'Chris Mills'])
+ ['Chris Mills'])
# Reget the objects to clear caches
chris = Person.objects.using('other').get(name="Chris Mills")
@@ -433,7 +433,7 @@ class QueryTestCase(TestCase):
# Retrive related object by descriptor. Related objects should be database-baound
self.assertEqual(list(chris.edited.values_list('title', flat=True)),
- [u'Dive into Python'])
+ ['Dive into Python'])
def test_foreign_key_reverse_operations(self):
"FK reverse manipulations are all constrained to a single DB"
@@ -454,16 +454,16 @@ class QueryTestCase(TestCase):
chris.edited.add(html5)
self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
- [u'Chris Mills'])
+ ['Chris Mills'])
self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)),
- [u'Chris Mills'])
+ ['Chris Mills'])
# Remove the second editor
chris.edited.remove(html5)
self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
[])
self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)),
- [u'Chris Mills'])
+ ['Chris Mills'])
# Clear all edited books
chris.edited.clear()
@@ -477,7 +477,7 @@ class QueryTestCase(TestCase):
self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
[])
self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Water').values_list('name', flat=True)),
- [u'Chris Mills'])
+ ['Chris Mills'])
self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)),
[])
@@ -532,37 +532,37 @@ class QueryTestCase(TestCase):
self.assertEqual(html5._state.db, 'other')
# ... but it isn't saved yet
self.assertEqual(list(Person.objects.using('other').values_list('name',flat=True)),
- [u'Mark Pilgrim'])
+ ['Mark Pilgrim'])
self.assertEqual(list(Book.objects.using('other').values_list('title',flat=True)),
- [u'Dive into Python'])
+ ['Dive into Python'])
# When saved (no using required), new objects goes to 'other'
chris.save()
html5.save()
self.assertEqual(list(Person.objects.using('default').values_list('name',flat=True)),
- [u'Marty Alchin'])
+ ['Marty Alchin'])
self.assertEqual(list(Person.objects.using('other').values_list('name',flat=True)),
- [u'Chris Mills', u'Mark Pilgrim'])
+ ['Chris Mills', 'Mark Pilgrim'])
self.assertEqual(list(Book.objects.using('default').values_list('title',flat=True)),
- [u'Pro Django'])
+ ['Pro Django'])
self.assertEqual(list(Book.objects.using('other').values_list('title',flat=True)),
- [u'Dive into HTML5', u'Dive into Python'])
+ ['Dive into HTML5', 'Dive into Python'])
# This also works if you assign the FK in the constructor
water = Book(title="Dive into Water", published=datetime.date(2001, 1, 1), editor=mark)
self.assertEqual(water._state.db, 'other')
# ... but it isn't saved yet
self.assertEqual(list(Book.objects.using('default').values_list('title',flat=True)),
- [u'Pro Django'])
+ ['Pro Django'])
self.assertEqual(list(Book.objects.using('other').values_list('title',flat=True)),
- [u'Dive into HTML5', u'Dive into Python'])
+ ['Dive into HTML5', 'Dive into Python'])
# When saved, the new book goes to 'other'
water.save()
self.assertEqual(list(Book.objects.using('default').values_list('title',flat=True)),
- [u'Pro Django'])
+ ['Pro Django'])
self.assertEqual(list(Book.objects.using('other').values_list('title',flat=True)),
- [u'Dive into HTML5', u'Dive into Python', u'Dive into Water'])
+ ['Dive into HTML5', 'Dive into Python', 'Dive into Water'])
def test_foreign_key_deletion(self):
"Cascaded deletions of Foreign Key relations issue queries on the right database"
@@ -611,14 +611,14 @@ class QueryTestCase(TestCase):
# Check that queries work across joins
self.assertEqual(list(User.objects.using('default').filter(userprofile__flavor='chocolate').values_list('username', flat=True)),
- [u'alice'])
+ ['alice'])
self.assertEqual(list(User.objects.using('other').filter(userprofile__flavor='chocolate').values_list('username', flat=True)),
[])
self.assertEqual(list(User.objects.using('default').filter(userprofile__flavor='crunchy frog').values_list('username', flat=True)),
[])
self.assertEqual(list(User.objects.using('other').filter(userprofile__flavor='crunchy frog').values_list('username', flat=True)),
- [u'bob'])
+ ['bob'])
# Reget the objects to clear caches
alice_profile = UserProfile.objects.using('default').get(flavor='chocolate')
@@ -666,22 +666,22 @@ class QueryTestCase(TestCase):
# ... but it isn't saved yet
self.assertEqual(list(User.objects.using('other').values_list('username',flat=True)),
- [u'bob'])
+ ['bob'])
self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor',flat=True)),
- [u'crunchy frog'])
+ ['crunchy frog'])
# When saved (no using required), new objects goes to 'other'
charlie.save()
bob_profile.save()
new_bob_profile.save()
self.assertEqual(list(User.objects.using('default').values_list('username',flat=True)),
- [u'alice'])
+ ['alice'])
self.assertEqual(list(User.objects.using('other').values_list('username',flat=True)),
- [u'bob', u'charlie'])
+ ['bob', 'charlie'])
self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor',flat=True)),
- [u'chocolate'])
+ ['chocolate'])
self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor',flat=True)),
- [u'crunchy frog', u'spring surprise'])
+ ['crunchy frog', 'spring surprise'])
# This also works if you assign the O2O relation in the constructor
denise = User.objects.db_manager('other').create_user('denise','denise@example.com')
@@ -690,16 +690,16 @@ class QueryTestCase(TestCase):
self.assertEqual(denise_profile._state.db, 'other')
# ... but it isn't saved yet
self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor',flat=True)),
- [u'chocolate'])
+ ['chocolate'])
self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor',flat=True)),
- [u'crunchy frog', u'spring surprise'])
+ ['crunchy frog', 'spring surprise'])
# When saved, the new profile goes to 'other'
denise_profile.save()
self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor',flat=True)),
- [u'chocolate'])
+ ['chocolate'])
self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor',flat=True)),
- [u'crunchy frog', u'spring surprise', u'tofu'])
+ ['crunchy frog', 'spring surprise', 'tofu'])
def test_generic_key_separation(self):
"Generic fields are constrained to a single database"
@@ -728,7 +728,7 @@ class QueryTestCase(TestCase):
# Retrive related object by descriptor. Related objects should be database-bound
self.assertEqual(list(dive.reviews.all().values_list('source', flat=True)),
- [u'Python Weekly'])
+ ['Python Weekly'])
def test_generic_key_reverse_operations(self):
"Generic reverse manipulations are all constrained to a single DB"
@@ -746,21 +746,21 @@ class QueryTestCase(TestCase):
self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
[])
self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
- [u'Python Weekly'])
+ ['Python Weekly'])
# Add a second review
dive.reviews.add(review2)
self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
[])
self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
- [u'Python Monthly', u'Python Weekly'])
+ ['Python Monthly', 'Python Weekly'])
# Remove the second author
dive.reviews.remove(review1)
self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
[])
self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
- [u'Python Monthly'])
+ ['Python Monthly'])
# Clear all reviews
dive.reviews.clear()
@@ -774,7 +774,7 @@ class QueryTestCase(TestCase):
self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
[])
self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
- [u'Python Daily'])
+ ['Python Daily'])
def test_generic_key_cross_database_protection(self):
"Operations that involve sharing generic key objects across databases raise an error"
@@ -818,16 +818,16 @@ class QueryTestCase(TestCase):
self.assertEqual(review3._state.db, 'other')
# ... but it isn't saved yet
self.assertEqual(list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)),
- [u'Python Monthly'])
+ ['Python Monthly'])
self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source',flat=True)),
- [u'Python Weekly'])
+ ['Python Weekly'])
# When saved, John goes to 'other'
review3.save()
self.assertEqual(list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)),
- [u'Python Monthly'])
+ ['Python Monthly'])
self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source',flat=True)),
- [u'Python Daily', u'Python Weekly'])
+ ['Python Daily', 'Python Weekly'])
def test_generic_key_deletion(self):
"Cascaded deletions of Generic Key relations issue queries on the right database"
@@ -1103,8 +1103,8 @@ class RouterTestCase(TestCase):
# Related object queries stick to the same database
# as the original object, regardless of the router
- self.assertEqual(list(pro.authors.values_list('name', flat=True)), [u'Marty Alchin'])
- self.assertEqual(pro.editor.name, u'Marty Alchin')
+ self.assertEqual(list(pro.authors.values_list('name', flat=True)), ['Marty Alchin'])
+ self.assertEqual(pro.editor.name, 'Marty Alchin')
# get_or_create is a special case. The get needs to be targeted at
# the write database in order to avoid potential transaction
@@ -1543,7 +1543,7 @@ class RouterTestCase(TestCase):
str(qs.query)
# If you evaluate the query, it should work, running on 'other'
- self.assertEqual(list(qs.values_list('title', flat=True)), [u'Dive into Python'])
+ self.assertEqual(list(qs.values_list('title', flat=True)), ['Dive into Python'])
class AuthTestCase(TestCase):
multi_db = True
diff --git a/tests/regressiontests/null_fk/tests.py b/tests/regressiontests/null_fk/tests.py
index abcfde9391..96a06b6769 100644
--- a/tests/regressiontests/null_fk/tests.py
+++ b/tests/regressiontests/null_fk/tests.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from django.db.models import Q
from django.test import TestCase
@@ -28,8 +28,8 @@ class NullFkTests(TestCase):
self.assertQuerysetEqual(
Comment.objects.select_related('post__forum__system_info').all(),
[
- (c1.id, u'My first comment', '<Post: First Post>'),
- (c2.id, u'My second comment', 'None')
+ (c1.id, 'My first comment', '<Post: First Post>'),
+ (c2.id, 'My second comment', 'None')
],
transform = lambda c: (c.id, c.comment_text, repr(c.post))
)
@@ -40,8 +40,8 @@ class NullFkTests(TestCase):
self.assertQuerysetEqual(
Comment.objects.select_related('post__forum__system_info__system_details'),
[
- (c1.id, u'My first comment', '<Post: First Post>'),
- (c2.id, u'My second comment', 'None')
+ (c1.id, 'My first comment', '<Post: First Post>'),
+ (c2.id, 'My second comment', 'None')
],
transform = lambda c: (c.id, c.comment_text, repr(c.post))
)
diff --git a/tests/regressiontests/null_fk_ordering/models.py b/tests/regressiontests/null_fk_ordering/models.py
index ac714f9ad5..e4a19f1512 100644
--- a/tests/regressiontests/null_fk_ordering/models.py
+++ b/tests/regressiontests/null_fk_ordering/models.py
@@ -5,6 +5,7 @@ Regression tests for proper working of ForeignKey(null=True). Tests these bugs:
xpected results
"""
+from __future__ import unicode_literals
from django.db import models
@@ -18,7 +19,7 @@ class Article(models.Model):
author = models.ForeignKey(Author, null=True)
def __unicode__(self):
- return u'Article titled: %s' % (self.title, )
+ return 'Article titled: %s' % (self.title, )
class Meta:
ordering = ['author__name', ]
diff --git a/tests/regressiontests/null_queries/models.py b/tests/regressiontests/null_queries/models.py
index ff9916fa2f..886bd75276 100644
--- a/tests/regressiontests/null_queries/models.py
+++ b/tests/regressiontests/null_queries/models.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.db import models
@@ -5,14 +7,14 @@ class Poll(models.Model):
question = models.CharField(max_length=200)
def __unicode__(self):
- return u"Q: %s " % self.question
+ return "Q: %s " % self.question
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
def __unicode__(self):
- return u"Choice: %s in poll %s" % (self.choice, self.poll)
+ return "Choice: %s in poll %s" % (self.choice, self.poll)
# A set of models with an inner one pointing to two outer ones.
class OuterA(models.Model):
diff --git a/tests/regressiontests/one_to_one_regress/models.py b/tests/regressiontests/one_to_one_regress/models.py
index 0e4eef65ca..5d32bf03f8 100644
--- a/tests/regressiontests/one_to_one_regress/models.py
+++ b/tests/regressiontests/one_to_one_regress/models.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.db import models
@@ -6,7 +8,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)
@@ -14,14 +16,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 Bar(models.Model):
place = models.OneToOneField(Place)
serves_cocktails = models.BooleanField()
def __unicode__(self):
- return u"%s the bar" % self.place.name
+ return "%s the bar" % self.place.name
class UndergroundBar(models.Model):
place = models.OneToOneField(Place, null=True)
@@ -32,7 +34,7 @@ class Favorites(models.Model):
restaurants = models.ManyToManyField(Restaurant)
def __unicode__(self):
- return u"Favorites for %s" % self.name
+ return "Favorites for %s" % self.name
class Target(models.Model):
pass
diff --git a/tests/regressiontests/pagination_regress/tests.py b/tests/regressiontests/pagination_regress/tests.py
index 9f381a5981..59ac41e062 100644
--- a/tests/regressiontests/pagination_regress/tests.py
+++ b/tests/regressiontests/pagination_regress/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.utils.unittest import TestCase
@@ -96,9 +98,9 @@ class PaginatorTests(TestCase):
((eleven, 10, 1, True), (11, 1, [1])),
# Non-integer inputs
((ten, '4', 1, False), (10, 3, [1, 2, 3])),
- ((ten, u'4', 1, False), (10, 3, [1, 2, 3])),
+ ((ten, '4', 1, False), (10, 3, [1, 2, 3])),
+ ((ten, 4, '1', False), (10, 3, [1, 2, 3])),
((ten, 4, '1', False), (10, 3, [1, 2, 3])),
- ((ten, 4, u'1', False), (10, 3, [1, 2, 3])),
)
for params, output in tests:
self.check_paginator(params, output)
diff --git a/tests/regressiontests/queries/models.py b/tests/regressiontests/queries/models.py
index e4ce9d7b60..8c34b50e93 100644
--- a/tests/regressiontests/queries/models.py
+++ b/tests/regressiontests/queries/models.py
@@ -1,6 +1,7 @@
"""
Various complex queries that have been problematic in the past.
"""
+from __future__ import unicode_literals
import threading
@@ -294,14 +295,14 @@ class Eaten(models.Model):
meal = models.CharField(max_length=20)
def __unicode__(self):
- return u"%s at %s" % (self.food, self.meal)
+ return "%s at %s" % (self.food, self.meal)
class Node(models.Model):
num = models.IntegerField(unique=True)
parent = models.ForeignKey("self", to_field="num", null=True)
def __unicode__(self):
- return u"%s" % self.num
+ return "%s" % self.num
# Bug #12252
class ObjectA(models.Model):
diff --git a/tests/regressiontests/queries/tests.py b/tests/regressiontests/queries/tests.py
index 1035a38840..4cc7208a96 100644
--- a/tests/regressiontests/queries/tests.py
+++ b/tests/regressiontests/queries/tests.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import,unicode_literals
import datetime
from operator import attrgetter
@@ -11,6 +11,7 @@ from django.db import DatabaseError, connection, connections, DEFAULT_DB_ALIAS
from django.db.models import Count
from django.db.models.query import Q, ITER_CHUNK_SIZE, EmptyQuerySet
from django.test import TestCase, skipUnlessDBFeature
+from django.test.utils import str_prefix
from django.utils import unittest
from django.utils.datastructures import SortedDict
@@ -466,7 +467,7 @@ class Queries1Tests(BaseQuerysetTest):
# ordering columns.
self.assertValueQuerysetEqual(
Note.objects.values('misc').distinct().order_by('note', '-misc'),
- [{'misc': u'foo'}, {'misc': u'bar'}, {'misc': u'foo'}]
+ [{'misc': 'foo'}, {'misc': 'bar'}, {'misc': 'foo'}]
)
def test_ticket4358(self):
@@ -506,7 +507,7 @@ class Queries1Tests(BaseQuerysetTest):
# return 'one' and 'two' as strings, not Unicode objects. It's a side-effect of
# using constants here and not a real concern.
d = Item.objects.extra(select=SortedDict(s), select_params=params).values('a', 'b')[0]
- self.assertEqual(d, {'a': u'one', 'b': u'two'})
+ self.assertEqual(d, {'a': 'one', 'b': 'two'})
# Order by the number of tags attached to an item.
l = Item.objects.extra(select={'count': 'select count(*) from queries_item_tags where queries_item_tags.item_id = queries_item.id'}).order_by('-count')
@@ -582,7 +583,7 @@ class Queries1Tests(BaseQuerysetTest):
# works.
self.assertValueQuerysetEqual(
Item.objects.values('note__note').order_by('queries_note.note', 'id'),
- [{'note__note': u'n2'}, {'note__note': u'n3'}, {'note__note': u'n3'}, {'note__note': u'n3'}]
+ [{'note__note': 'n2'}, {'note__note': 'n3'}, {'note__note': 'n3'}, {'note__note': 'n3'}]
)
def test_ticket7096(self):
@@ -1051,15 +1052,15 @@ class Queries4Tests(BaseQuerysetTest):
# A values() or values_list() query across joined models must use outer
# joins appropriately.
- # Note: In Oracle, we expect a null CharField to return u'' instead of
+ # Note: In Oracle, we expect a null CharField to return '' instead of
# None.
if connection.features.interprets_empty_strings_as_nulls:
- expected_null_charfield_repr = u''
+ expected_null_charfield_repr = ''
else:
expected_null_charfield_repr = None
self.assertValueQuerysetEqual(
Report.objects.values_list("creator__extra__info", flat=True).order_by("name"),
- [u'e1', u'e2', expected_null_charfield_repr],
+ ['e1', 'e2', expected_null_charfield_repr],
)
# Similarly for select_related(), joins beyond an initial nullable join
@@ -1080,7 +1081,7 @@ class Queries4Tests(BaseQuerysetTest):
m2 = Member.objects.create(name="m2", details=d2)
Child.objects.create(person=m2, parent=m1)
obj = m1.children.select_related("person__details")[0]
- self.assertEqual(obj.person.details.data, u'd2')
+ self.assertEqual(obj.person.details.data, 'd2')
def test_order_by_resetting(self):
# Calling order_by() with no parameters removes any existing ordering on the
@@ -1530,12 +1531,12 @@ class RawQueriesTests(TestCase):
query = "SELECT * FROM queries_note WHERE note = %s"
params = ['n1']
qs = Note.objects.raw(query, params=params)
- self.assertEqual(repr(qs), "<RawQuerySet: 'SELECT * FROM queries_note WHERE note = n1'>")
+ self.assertEqual(repr(qs), str_prefix("<RawQuerySet: %(_)s'SELECT * FROM queries_note WHERE note = n1'>"))
query = "SELECT * FROM queries_note WHERE note = %s and misc = %s"
params = ['n1', 'foo']
qs = Note.objects.raw(query, params=params)
- self.assertEqual(repr(qs), "<RawQuerySet: 'SELECT * FROM queries_note WHERE note = n1 and misc = foo'>")
+ self.assertEqual(repr(qs), str_prefix("<RawQuerySet: %(_)s'SELECT * FROM queries_note WHERE note = n1 and misc = foo'>"))
class GeneratorExpressionTests(TestCase):
diff --git a/tests/regressiontests/requests/tests.py b/tests/regressiontests/requests/tests.py
index 3d2b196194..146dca2b7b 100644
--- a/tests/regressiontests/requests/tests.py
+++ b/tests/regressiontests/requests/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import time
import warnings
from datetime import datetime, timedelta
@@ -6,6 +8,7 @@ from StringIO import StringIO
from django.conf import settings
from django.core.handlers.wsgi import WSGIRequest, LimitedStream
from django.http import HttpRequest, HttpResponse, parse_cookie, build_request_repr, UnreadablePostError
+from django.test.utils import str_prefix
from django.utils import unittest
from django.utils.http import cookie_date
from django.utils.timezone import utc
@@ -21,15 +24,15 @@ class RequestsTests(unittest.TestCase):
def test_httprequest_repr(self):
request = HttpRequest()
- request.path = u'/somepath/'
- request.GET = {u'get-key': u'get-value'}
- request.POST = {u'post-key': u'post-value'}
- request.COOKIES = {u'post-key': u'post-value'}
- request.META = {u'post-key': u'post-value'}
- self.assertEqual(repr(request), u"<HttpRequest\npath:/somepath/,\nGET:{u'get-key': u'get-value'},\nPOST:{u'post-key': u'post-value'},\nCOOKIES:{u'post-key': u'post-value'},\nMETA:{u'post-key': u'post-value'}>")
+ request.path = '/somepath/'
+ request.GET = {'get-key': 'get-value'}
+ request.POST = {'post-key': 'post-value'}
+ request.COOKIES = {'post-key': 'post-value'}
+ request.META = {'post-key': 'post-value'}
+ self.assertEqual(repr(request), str_prefix("<HttpRequest\npath:/somepath/,\nGET:{%(_)s'get-key': %(_)s'get-value'},\nPOST:{%(_)s'post-key': %(_)s'post-value'},\nCOOKIES:{%(_)s'post-key': %(_)s'post-value'},\nMETA:{%(_)s'post-key': %(_)s'post-value'}>"))
self.assertEqual(build_request_repr(request), repr(request))
- self.assertEqual(build_request_repr(request, path_override='/otherpath/', GET_override={u'a': u'b'}, POST_override={u'c': u'd'}, COOKIES_override={u'e': u'f'}, META_override={u'g': u'h'}),
- u"<HttpRequest\npath:/otherpath/,\nGET:{u'a': u'b'},\nPOST:{u'c': u'd'},\nCOOKIES:{u'e': u'f'},\nMETA:{u'g': u'h'}>")
+ self.assertEqual(build_request_repr(request, path_override='/otherpath/', GET_override={'a': 'b'}, POST_override={'c': 'd'}, COOKIES_override={'e': 'f'}, META_override={'g': 'h'}),
+ str_prefix("<HttpRequest\npath:/otherpath/,\nGET:{%(_)s'a': %(_)s'b'},\nPOST:{%(_)s'c': %(_)s'd'},\nCOOKIES:{%(_)s'e': %(_)s'f'},\nMETA:{%(_)s'g': %(_)s'h'}>"))
def test_wsgirequest(self):
request = WSGIRequest({'PATH_INFO': 'bogus', 'REQUEST_METHOD': 'bogus', 'wsgi.input': StringIO('')})
@@ -43,14 +46,14 @@ class RequestsTests(unittest.TestCase):
def test_wsgirequest_repr(self):
request = WSGIRequest({'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': StringIO('')})
- request.GET = {u'get-key': u'get-value'}
- request.POST = {u'post-key': u'post-value'}
- request.COOKIES = {u'post-key': u'post-value'}
- request.META = {u'post-key': u'post-value'}
- self.assertEqual(repr(request), u"<WSGIRequest\npath:/somepath/,\nGET:{u'get-key': u'get-value'},\nPOST:{u'post-key': u'post-value'},\nCOOKIES:{u'post-key': u'post-value'},\nMETA:{u'post-key': u'post-value'}>")
+ request.GET = {'get-key': 'get-value'}
+ request.POST = {'post-key': 'post-value'}
+ request.COOKIES = {'post-key': 'post-value'}
+ request.META = {'post-key': 'post-value'}
+ self.assertEqual(repr(request), str_prefix("<WSGIRequest\npath:/somepath/,\nGET:{%(_)s'get-key': %(_)s'get-value'},\nPOST:{%(_)s'post-key': %(_)s'post-value'},\nCOOKIES:{%(_)s'post-key': %(_)s'post-value'},\nMETA:{%(_)s'post-key': %(_)s'post-value'}>"))
self.assertEqual(build_request_repr(request), repr(request))
- self.assertEqual(build_request_repr(request, path_override='/otherpath/', GET_override={u'a': u'b'}, POST_override={u'c': u'd'}, COOKIES_override={u'e': u'f'}, META_override={u'g': u'h'}),
- u"<WSGIRequest\npath:/otherpath/,\nGET:{u'a': u'b'},\nPOST:{u'c': u'd'},\nCOOKIES:{u'e': u'f'},\nMETA:{u'g': u'h'}>")
+ self.assertEqual(build_request_repr(request, path_override='/otherpath/', GET_override={'a': 'b'}, POST_override={'c': 'd'}, COOKIES_override={'e': 'f'}, META_override={'g': 'h'}),
+ str_prefix("<WSGIRequest\npath:/otherpath/,\nGET:{%(_)s'a': %(_)s'b'},\nPOST:{%(_)s'c': %(_)s'd'},\nCOOKIES:{%(_)s'e': %(_)s'f'},\nMETA:{%(_)s'g': %(_)s'h'}>"))
def test_parse_cookie(self):
self.assertEqual(parse_cookie('invalid:key=true'), {})
@@ -73,10 +76,10 @@ class RequestsTests(unittest.TestCase):
# Check if X_FORWARDED_HOST is provided.
request = HttpRequest()
request.META = {
- u'HTTP_X_FORWARDED_HOST': u'forward.com',
- u'HTTP_HOST': u'example.com',
- u'SERVER_NAME': u'internal.com',
- u'SERVER_PORT': 80,
+ 'HTTP_X_FORWARDED_HOST': 'forward.com',
+ 'HTTP_HOST': 'example.com',
+ 'SERVER_NAME': 'internal.com',
+ 'SERVER_PORT': 80,
}
# X_FORWARDED_HOST is ignored.
self.assertEqual(request.get_host(), 'example.com')
@@ -84,25 +87,25 @@ class RequestsTests(unittest.TestCase):
# Check if X_FORWARDED_HOST isn't provided.
request = HttpRequest()
request.META = {
- u'HTTP_HOST': u'example.com',
- u'SERVER_NAME': u'internal.com',
- u'SERVER_PORT': 80,
+ 'HTTP_HOST': 'example.com',
+ 'SERVER_NAME': 'internal.com',
+ 'SERVER_PORT': 80,
}
self.assertEqual(request.get_host(), 'example.com')
# Check if HTTP_HOST isn't provided.
request = HttpRequest()
request.META = {
- u'SERVER_NAME': u'internal.com',
- u'SERVER_PORT': 80,
+ 'SERVER_NAME': 'internal.com',
+ 'SERVER_PORT': 80,
}
self.assertEqual(request.get_host(), 'internal.com')
# Check if HTTP_HOST isn't provided, and we're on a nonstandard port
request = HttpRequest()
request.META = {
- u'SERVER_NAME': u'internal.com',
- u'SERVER_PORT': 8042,
+ 'SERVER_NAME': 'internal.com',
+ 'SERVER_PORT': 8042,
}
self.assertEqual(request.get_host(), 'internal.com:8042')
@@ -117,10 +120,10 @@ class RequestsTests(unittest.TestCase):
# Check if X_FORWARDED_HOST is provided.
request = HttpRequest()
request.META = {
- u'HTTP_X_FORWARDED_HOST': u'forward.com',
- u'HTTP_HOST': u'example.com',
- u'SERVER_NAME': u'internal.com',
- u'SERVER_PORT': 80,
+ 'HTTP_X_FORWARDED_HOST': 'forward.com',
+ 'HTTP_HOST': 'example.com',
+ 'SERVER_NAME': 'internal.com',
+ 'SERVER_PORT': 80,
}
# X_FORWARDED_HOST is obeyed.
self.assertEqual(request.get_host(), 'forward.com')
@@ -128,25 +131,25 @@ class RequestsTests(unittest.TestCase):
# Check if X_FORWARDED_HOST isn't provided.
request = HttpRequest()
request.META = {
- u'HTTP_HOST': u'example.com',
- u'SERVER_NAME': u'internal.com',
- u'SERVER_PORT': 80,
+ 'HTTP_HOST': 'example.com',
+ 'SERVER_NAME': 'internal.com',
+ 'SERVER_PORT': 80,
}
self.assertEqual(request.get_host(), 'example.com')
# Check if HTTP_HOST isn't provided.
request = HttpRequest()
request.META = {
- u'SERVER_NAME': u'internal.com',
- u'SERVER_PORT': 80,
+ 'SERVER_NAME': 'internal.com',
+ 'SERVER_PORT': 80,
}
self.assertEqual(request.get_host(), 'internal.com')
# Check if HTTP_HOST isn't provided, and we're on a nonstandard port
request = HttpRequest()
request.META = {
- u'SERVER_NAME': u'internal.com',
- u'SERVER_PORT': 8042,
+ 'SERVER_NAME': 'internal.com',
+ 'SERVER_PORT': 8042,
}
self.assertEqual(request.get_host(), 'internal.com:8042')
@@ -275,7 +278,7 @@ class RequestsTests(unittest.TestCase):
request = WSGIRequest({'REQUEST_METHOD': 'POST',
'CONTENT_LENGTH': len(payload),
'wsgi.input': StringIO(payload)})
- self.assertEqual(request.POST, {u'name': [u'value']})
+ self.assertEqual(request.POST, {'name': ['value']})
self.assertEqual(request.body, b'name=value')
self.assertEqual(request.read(), b'name=value')
@@ -305,12 +308,12 @@ class RequestsTests(unittest.TestCase):
'',
'value',
'--boundary--'
- ''])
+ '']).encode('utf-8')
request = WSGIRequest({'REQUEST_METHOD': 'POST',
'CONTENT_TYPE': 'multipart/form-data; boundary=boundary',
'CONTENT_LENGTH': len(payload),
'wsgi.input': StringIO(payload)})
- self.assertEqual(request.POST, {u'name': [u'value']})
+ self.assertEqual(request.POST, {'name': ['value']})
self.assertRaises(Exception, lambda: request.body)
def test_POST_multipart_with_content_length_zero(self):
@@ -327,7 +330,7 @@ class RequestsTests(unittest.TestCase):
'',
'value',
'--boundary--'
- ''])
+ '']).encode('utf-8')
request = WSGIRequest({'REQUEST_METHOD': 'POST',
'CONTENT_TYPE': 'multipart/form-data; boundary=boundary',
'CONTENT_LENGTH': 0,
@@ -350,7 +353,7 @@ class RequestsTests(unittest.TestCase):
'CONTENT_LENGTH': len(payload),
'wsgi.input': StringIO(payload)})
raw_data = request.body
- self.assertEqual(request.POST, {u'name': [u'value']})
+ self.assertEqual(request.POST, {'name': ['value']})
def test_POST_after_body_read_and_stream_read(self):
"""
@@ -363,7 +366,7 @@ class RequestsTests(unittest.TestCase):
'wsgi.input': StringIO(payload)})
raw_data = request.body
self.assertEqual(request.read(1), b'n')
- self.assertEqual(request.POST, {u'name': [u'value']})
+ self.assertEqual(request.POST, {'name': ['value']})
def test_POST_after_body_read_and_stream_read_multipart(self):
"""
@@ -376,7 +379,7 @@ class RequestsTests(unittest.TestCase):
'',
'value',
'--boundary--'
- ''])
+ '']).encode('utf-8')
request = WSGIRequest({'REQUEST_METHOD': 'POST',
'CONTENT_TYPE': 'multipart/form-data; boundary=boundary',
'CONTENT_LENGTH': len(payload),
@@ -384,7 +387,7 @@ class RequestsTests(unittest.TestCase):
raw_data = request.body
# Consume enough data to mess up the parsing:
self.assertEqual(request.read(13), b'--boundary\r\nC')
- self.assertEqual(request.POST, {u'name': [u'value']})
+ self.assertEqual(request.POST, {'name': ['value']})
def test_raw_post_data_returns_body(self):
"""
diff --git a/tests/regressiontests/select_related_regress/models.py b/tests/regressiontests/select_related_regress/models.py
index 43e64f0e69..1af9ff4bca 100644
--- a/tests/regressiontests/select_related_regress/models.py
+++ b/tests/regressiontests/select_related_regress/models.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.db import models
@@ -5,21 +7,21 @@ class Building(models.Model):
name = models.CharField(max_length=10)
def __unicode__(self):
- return u"Building: %s" % self.name
+ return "Building: %s" % self.name
class Device(models.Model):
building = models.ForeignKey('Building')
name = models.CharField(max_length=10)
def __unicode__(self):
- return u"device '%s' in building %s" % (self.name, self.building)
+ return "device '%s' in building %s" % (self.name, self.building)
class Port(models.Model):
device = models.ForeignKey('Device')
port_number = models.CharField(max_length=10)
def __unicode__(self):
- return u"%s/%s" % (self.device.name, self.port_number)
+ return "%s/%s" % (self.device.name, self.port_number)
class Connection(models.Model):
start = models.ForeignKey(Port, related_name='connection_start',
@@ -27,7 +29,7 @@ class Connection(models.Model):
end = models.ForeignKey(Port, related_name='connection_end', unique=True)
def __unicode__(self):
- return u"%s to %s" % (self.start, self.end)
+ return "%s to %s" % (self.start, self.end)
# Another non-tree hierarchy that exercises code paths similar to the above
# example, but in a slightly different configuration.
diff --git a/tests/regressiontests/select_related_regress/tests.py b/tests/regressiontests/select_related_regress/tests.py
index 4cd4f788e2..e35157dbaf 100644
--- a/tests/regressiontests/select_related_regress/tests.py
+++ b/tests/regressiontests/select_related_regress/tests.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from django.test import TestCase
@@ -34,11 +34,11 @@ class SelectRelatedRegressTests(TestCase):
connections=Connection.objects.filter(start__device__building=b, end__device__building=b).order_by('id')
self.assertEqual([(c.id, unicode(c.start), unicode(c.end)) for c in connections],
- [(c1.id, u'router/4', u'switch/7'), (c2.id, u'switch/7', u'server/1')])
+ [(c1.id, 'router/4', 'switch/7'), (c2.id, 'switch/7', 'server/1')])
connections=Connection.objects.filter(start__device__building=b, end__device__building=b).select_related().order_by('id')
self.assertEqual([(c.id, unicode(c.start), unicode(c.end)) for c in connections],
- [(c1.id, u'router/4', u'switch/7'), (c2.id, u'switch/7', u'server/1')])
+ [(c1.id, 'router/4', 'switch/7'), (c2.id, 'switch/7', 'server/1')])
# This final query should only have seven tables (port, device and building
# twice each, plus connection once). Thus, 6 joins plus the FROM table.
@@ -64,8 +64,8 @@ class SelectRelatedRegressTests(TestCase):
e = Enrollment.objects.create(std=s, cls=c)
e_related = Enrollment.objects.all().select_related()[0]
- self.assertEqual(e_related.std.person.user.name, u"std")
- self.assertEqual(e_related.cls.org.person.user.name, u"org")
+ self.assertEqual(e_related.std.person.user.name, "std")
+ self.assertEqual(e_related.cls.org.person.user.name, "org")
def test_regression_8036(self):
"""
@@ -114,27 +114,27 @@ class SelectRelatedRegressTests(TestCase):
c1 = Client.objects.create(name='Brian Burke', state=wa, status=active)
burke = Client.objects.select_related('state').defer('state__name').get(name='Brian Burke')
- self.assertEqual(burke.name, u'Brian Burke')
- self.assertEqual(burke.state.name, u'Western Australia')
+ self.assertEqual(burke.name, 'Brian Burke')
+ self.assertEqual(burke.state.name, 'Western Australia')
# Still works if we're dealing with an inherited class
sc1 = SpecialClient.objects.create(name='Troy Buswell', state=wa, status=active, value=42)
troy = SpecialClient.objects.select_related('state').defer('state__name').get(name='Troy Buswell')
- self.assertEqual(troy.name, u'Troy Buswell')
+ self.assertEqual(troy.name, 'Troy Buswell')
self.assertEqual(troy.value, 42)
- self.assertEqual(troy.state.name, u'Western Australia')
+ self.assertEqual(troy.state.name, 'Western Australia')
# Still works if we defer an attribute on the inherited class
troy = SpecialClient.objects.select_related('state').defer('value', 'state__name').get(name='Troy Buswell')
- self.assertEqual(troy.name, u'Troy Buswell')
+ self.assertEqual(troy.name, 'Troy Buswell')
self.assertEqual(troy.value, 42)
- self.assertEqual(troy.state.name, u'Western Australia')
+ self.assertEqual(troy.state.name, 'Western Australia')
# Also works if you use only, rather than defer
troy = SpecialClient.objects.select_related('state').only('name').get(name='Troy Buswell')
- self.assertEqual(troy.name, u'Troy Buswell')
+ self.assertEqual(troy.name, 'Troy Buswell')
self.assertEqual(troy.value, 42)
- self.assertEqual(troy.state.name, u'Western Australia')
+ self.assertEqual(troy.state.name, 'Western Australia')
diff --git a/tests/regressiontests/serializers_regress/tests.py b/tests/regressiontests/serializers_regress/tests.py
index 6930fbf393..f1b70a1d2e 100644
--- a/tests/regressiontests/serializers_regress/tests.py
+++ b/tests/regressiontests/serializers_regress/tests.py
@@ -6,7 +6,7 @@ test case that is capable of testing the capabilities of
the serializers. This includes all valid data values, plus
forward, backwards and self references.
"""
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import datetime
import decimal
@@ -183,7 +183,7 @@ test_data = [
(data_obj, 15, CharData, None),
# (We use something that will fit into a latin1 database encoding here,
# because that is still the default used on many system setups.)
- (data_obj, 16, CharData, u'\xa5'),
+ (data_obj, 16, CharData, '\xa5'),
(data_obj, 20, DateData, datetime.date(2006,6,16)),
(data_obj, 21, DateData, None),
(data_obj, 30, DateTimeData, datetime.datetime(2006,6,16,10,42,37)),
diff --git a/tests/regressiontests/signed_cookies_tests/tests.py b/tests/regressiontests/signed_cookies_tests/tests.py
index 5a0b5f9aa4..800092a2d7 100644
--- a/tests/regressiontests/signed_cookies_tests/tests.py
+++ b/tests/regressiontests/signed_cookies_tests/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import time
from django.core import signing
@@ -15,7 +17,7 @@ class SignedCookieTest(TestCase):
request = HttpRequest()
request.COOKIES['c'] = response.cookies['c'].value
value = request.get_signed_cookie('c')
- self.assertEqual(value, u'hello')
+ self.assertEqual(value, 'hello')
def test_can_use_salt(self):
response = HttpResponse()
@@ -23,7 +25,7 @@ class SignedCookieTest(TestCase):
request = HttpRequest()
request.COOKIES['a'] = response.cookies['a'].value
value = request.get_signed_cookie('a', salt='one')
- self.assertEqual(value, u'hello')
+ self.assertEqual(value, 'hello')
self.assertRaises(signing.BadSignature,
request.get_signed_cookie, 'a', salt='two')
@@ -43,7 +45,7 @@ class SignedCookieTest(TestCase):
self.assertEqual(request.get_signed_cookie('c', default=None), None)
def test_max_age_argument(self):
- value = u'hello'
+ value = 'hello'
_time = time.time
time.time = lambda: 123456789
try:
diff --git a/tests/regressiontests/signing/tests.py b/tests/regressiontests/signing/tests.py
index 1da3345806..f3fe5f3ec7 100644
--- a/tests/regressiontests/signing/tests.py
+++ b/tests/regressiontests/signing/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import time
from django.core import signing
@@ -14,7 +16,7 @@ class TestSigner(TestCase):
for s in (
b'hello',
b'3098247:529:087:',
- u'\u2019'.encode('utf-8'),
+ '\u2019'.encode('utf-8'),
):
self.assertEqual(
signer.signature(s),
@@ -42,7 +44,7 @@ class TestSigner(TestCase):
'3098247529087',
'3098247:529:087:',
'jkw osanteuh ,rcuh nthu aou oauh ,ud du',
- u'\u2019',
+ '\u2019',
)
for example in examples:
self.assertNotEqual(
@@ -70,7 +72,7 @@ class TestSigner(TestCase):
objects = (
['a', 'list'],
b'a string',
- u'a unicode string \u2019',
+ 'a unicode string \u2019',
{'a': 'dictionary'},
)
for o in objects:
@@ -98,7 +100,7 @@ class TestSigner(TestCase):
class TestTimestampSigner(TestCase):
def test_timestamp_signer(self):
- value = u'hello'
+ value = 'hello'
_time = time.time
time.time = lambda: 123456789
try:
diff --git a/tests/regressiontests/staticfiles_tests/tests.py b/tests/regressiontests/staticfiles_tests/tests.py
index 3711d92448..8321fc2365 100644
--- a/tests/regressiontests/staticfiles_tests/tests.py
+++ b/tests/regressiontests/staticfiles_tests/tests.py
@@ -1,4 +1,5 @@
# -*- encoding: utf-8 -*-
+from __future__ import unicode_literals
import codecs
import os
@@ -56,9 +57,9 @@ class BaseStaticFilesTestCase(object):
testfiles_path = os.path.join(TEST_ROOT, 'apps', 'test', 'static', 'test')
# To make sure SVN doesn't hangs itself with the non-ASCII characters
# during checkout, we actually create one file dynamically.
- self._nonascii_filepath = os.path.join(testfiles_path, u'fi\u015fier.txt')
+ self._nonascii_filepath = os.path.join(testfiles_path, 'fi\u015fier.txt')
with codecs.open(self._nonascii_filepath, 'w', 'utf-8') as f:
- f.write(u"fi\u015fier in the app dir")
+ f.write("fi\u015fier in the app dir")
# And also create the stupid hidden file to dwarf the setup.py's
# package data handling.
self._hidden_filepath = os.path.join(testfiles_path, '.hidden')
@@ -76,7 +77,7 @@ class BaseStaticFilesTestCase(object):
def assertFileContains(self, filepath, text):
self.assertIn(text, self._get_file(smart_unicode(filepath)),
- u"'%s' not in '%s'" % (text, filepath))
+ "'%s' not in '%s'" % (text, filepath))
def assertFileNotFound(self, filepath):
self.assertRaises(IOError, self._get_file, filepath)
@@ -173,13 +174,13 @@ class TestDefaults(object):
"""
Can find a file with non-ASCII character in an app static/ directory.
"""
- self.assertFileContains(u'test/fişier.txt', u'fişier in the app dir')
+ self.assertFileContains('test/fişier.txt', 'fişier in the app dir')
def test_camelcase_filenames(self):
"""
Can find a file with capital letters.
"""
- self.assertFileContains(u'test/camelCase.txt', u'camelCase')
+ self.assertFileContains('test/camelCase.txt', 'camelCase')
class TestFindStatic(CollectionTestCase, TestDefaults):
diff --git a/tests/regressiontests/string_lookup/tests.py b/tests/regressiontests/string_lookup/tests.py
index b3f90169ca..02f766adce 100644
--- a/tests/regressiontests/string_lookup/tests.py
+++ b/tests/regressiontests/string_lookup/tests.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from django.test import TestCase
from .models import Foo, Whiz, Bar, Article, Base, Child
@@ -49,9 +49,9 @@ class StringLookupTests(TestCase):
A properly configured UTF-8 database can handle this.
"""
- fx = Foo(name='Bjorn', friend=u'François')
+ fx = Foo(name='Bjorn', friend='François')
fx.save()
- self.assertEqual(Foo.objects.get(friend__contains=u'\xe7'), fx)
+ self.assertEqual(Foo.objects.get(friend__contains='\xe7'), fx)
# We can also do the above query using UTF-8 strings.
self.assertEqual(Foo.objects.get(friend__contains=b'\xc3\xa7'), fx)
diff --git a/tests/regressiontests/syndication/feeds.py b/tests/regressiontests/syndication/feeds.py
index 41feb89550..748420c9d2 100644
--- a/tests/regressiontests/syndication/feeds.py
+++ b/tests/regressiontests/syndication/feeds.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from django.contrib.syndication import views
from django.core.exceptions import ObjectDoesNotExist
@@ -105,21 +105,21 @@ class MyCustomAtom1Feed(feedgenerator.Atom1Feed):
"""
def root_attributes(self):
attrs = super(MyCustomAtom1Feed, self).root_attributes()
- attrs[u'django'] = u'rocks'
+ attrs['django'] = 'rocks'
return attrs
def add_root_elements(self, handler):
super(MyCustomAtom1Feed, self).add_root_elements(handler)
- handler.addQuickElement(u'spam', u'eggs')
+ handler.addQuickElement('spam', 'eggs')
def item_attributes(self, item):
attrs = super(MyCustomAtom1Feed, self).item_attributes(item)
- attrs[u'bacon'] = u'yum'
+ attrs['bacon'] = 'yum'
return attrs
def add_item_elements(self, handler, item):
super(MyCustomAtom1Feed, self).add_item_elements(handler, item)
- handler.addQuickElement(u'ministry', u'silly walks')
+ handler.addQuickElement('ministry', 'silly walks')
class TestCustomFeed(TestAtomFeed):
diff --git a/tests/regressiontests/syndication/tests.py b/tests/regressiontests/syndication/tests.py
index 95b4efb4f4..1790d8cae6 100644
--- a/tests/regressiontests/syndication/tests.py
+++ b/tests/regressiontests/syndication/tests.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from xml.dom import minidom
@@ -199,7 +199,7 @@ class SyndicationFeedTest(FeedTestCase):
link = item.getElementsByTagName('link')[0]
if link.firstChild.wholeText == 'http://example.com/blog/4/':
title = item.getElementsByTagName('title')[0]
- self.assertEqual(title.firstChild.wholeText, u'A &amp; B &lt; C &gt; D')
+ self.assertEqual(title.firstChild.wholeText, 'A &amp; B &lt; C &gt; D')
def test_naive_datetime_conversion(self):
"""
diff --git a/tests/regressiontests/templates/callables.py b/tests/regressiontests/templates/callables.py
index 8afa703f63..882a8c6e06 100644
--- a/tests/regressiontests/templates/callables.py
+++ b/tests/regressiontests/templates/callables.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django import template
from django.utils.unittest import TestCase
@@ -20,7 +22,7 @@ class CallableVariablesTests(TestCase):
# ``my_doodad.__call__`` will be invoked first, yielding a dictionary
# without a key ``value``.
t = template.Template('{{ my_doodad.value }}')
- self.assertEqual(t.render(c), u'')
+ self.assertEqual(t.render(c), '')
# We can confirm that the doodad has been called
self.assertEqual(my_doodad.num_calls, 1)
@@ -28,7 +30,7 @@ class CallableVariablesTests(TestCase):
# But we can access keys on the dict that's returned
# by ``__call__``, instead.
t = template.Template('{{ my_doodad.the_value }}')
- self.assertEqual(t.render(c), u'42')
+ self.assertEqual(t.render(c), '42')
self.assertEqual(my_doodad.num_calls, 2)
def test_alters_data(self):
@@ -48,9 +50,9 @@ class CallableVariablesTests(TestCase):
# Since ``my_doodad.alters_data`` is True, the template system will not
# try to call our doodad but will use TEMPLATE_STRING_IF_INVALID
t = template.Template('{{ my_doodad.value }}')
- self.assertEqual(t.render(c), u'')
+ self.assertEqual(t.render(c), '')
t = template.Template('{{ my_doodad.the_value }}')
- self.assertEqual(t.render(c), u'')
+ self.assertEqual(t.render(c), '')
# Double-check that the object was really never called during the
# template rendering.
@@ -75,9 +77,9 @@ class CallableVariablesTests(TestCase):
# as normal, and we don't have access to the dict that it returns when
# called.
t = template.Template('{{ my_doodad.value }}')
- self.assertEqual(t.render(c), u'42')
+ self.assertEqual(t.render(c), '42')
t = template.Template('{{ my_doodad.the_value }}')
- self.assertEqual(t.render(c), u'')
+ self.assertEqual(t.render(c), '')
# Double-check that the object was really never called during the
# template rendering.
@@ -102,9 +104,9 @@ class CallableVariablesTests(TestCase):
c = template.Context({"my_doodad": my_doodad})
t = template.Template('{{ my_doodad.value }}')
- self.assertEqual(t.render(c), u'42')
+ self.assertEqual(t.render(c), '42')
t = template.Template('{{ my_doodad.the_value }}')
- self.assertEqual(t.render(c), u'')
+ self.assertEqual(t.render(c), '')
# Double-check that the object was really never called during the
# template rendering.
diff --git a/tests/regressiontests/templates/custom.py b/tests/regressiontests/templates/custom.py
index 6bbbe35f03..4e295d990e 100644
--- a/tests/regressiontests/templates/custom.py
+++ b/tests/regressiontests/templates/custom.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from django import template
from django.utils.unittest import TestCase
@@ -11,7 +11,7 @@ class CustomFilterTests(TestCase):
t = template.Template("{% load custom %}{{ string|trim:5 }}")
self.assertEqual(
t.render(template.Context({"string": "abcdefghijklmnopqrstuvwxyz"})),
- u"abcde"
+ "abcde"
)
@@ -25,50 +25,50 @@ class CustomTagTests(TestCase):
c = template.Context({'value': 42})
t = template.Template('{% load custom %}{% no_params %}')
- self.assertEqual(t.render(c), u'no_params - Expected result')
+ self.assertEqual(t.render(c), 'no_params - Expected result')
t = template.Template('{% load custom %}{% one_param 37 %}')
- self.assertEqual(t.render(c), u'one_param - Expected result: 37')
+ self.assertEqual(t.render(c), 'one_param - Expected result: 37')
t = template.Template('{% load custom %}{% explicit_no_context 37 %}')
- self.assertEqual(t.render(c), u'explicit_no_context - Expected result: 37')
+ self.assertEqual(t.render(c), 'explicit_no_context - Expected result: 37')
t = template.Template('{% load custom %}{% no_params_with_context %}')
- self.assertEqual(t.render(c), u'no_params_with_context - Expected result (context value: 42)')
+ self.assertEqual(t.render(c), 'no_params_with_context - Expected result (context value: 42)')
t = template.Template('{% load custom %}{% params_and_context 37 %}')
- self.assertEqual(t.render(c), u'params_and_context - Expected result (context value: 42): 37')
+ self.assertEqual(t.render(c), 'params_and_context - Expected result (context value: 42): 37')
t = template.Template('{% load custom %}{% simple_two_params 37 42 %}')
- self.assertEqual(t.render(c), u'simple_two_params - Expected result: 37, 42')
+ self.assertEqual(t.render(c), 'simple_two_params - Expected result: 37, 42')
t = template.Template('{% load custom %}{% simple_one_default 37 %}')
- self.assertEqual(t.render(c), u'simple_one_default - Expected result: 37, hi')
+ self.assertEqual(t.render(c), 'simple_one_default - Expected result: 37, hi')
t = template.Template('{% load custom %}{% simple_one_default 37 two="hello" %}')
- self.assertEqual(t.render(c), u'simple_one_default - Expected result: 37, hello')
+ self.assertEqual(t.render(c), 'simple_one_default - Expected result: 37, hello')
t = template.Template('{% load custom %}{% simple_one_default one=99 two="hello" %}')
- self.assertEqual(t.render(c), u'simple_one_default - Expected result: 99, hello')
+ self.assertEqual(t.render(c), 'simple_one_default - Expected result: 99, hello')
self.assertRaisesRegexp(template.TemplateSyntaxError,
"'simple_one_default' received unexpected keyword argument 'three'",
template.Template, '{% load custom %}{% simple_one_default 99 two="hello" three="foo" %}')
t = template.Template('{% load custom %}{% simple_one_default 37 42 %}')
- self.assertEqual(t.render(c), u'simple_one_default - Expected result: 37, 42')
+ self.assertEqual(t.render(c), 'simple_one_default - Expected result: 37, 42')
t = template.Template('{% load custom %}{% simple_unlimited_args 37 %}')
- self.assertEqual(t.render(c), u'simple_unlimited_args - Expected result: 37, hi')
+ self.assertEqual(t.render(c), 'simple_unlimited_args - Expected result: 37, hi')
t = template.Template('{% load custom %}{% simple_unlimited_args 37 42 56 89 %}')
- self.assertEqual(t.render(c), u'simple_unlimited_args - Expected result: 37, 42, 56, 89')
+ self.assertEqual(t.render(c), 'simple_unlimited_args - Expected result: 37, 42, 56, 89')
t = template.Template('{% load custom %}{% simple_only_unlimited_args %}')
- self.assertEqual(t.render(c), u'simple_only_unlimited_args - Expected result: ')
+ self.assertEqual(t.render(c), 'simple_only_unlimited_args - Expected result: ')
t = template.Template('{% load custom %}{% simple_only_unlimited_args 37 42 56 89 %}')
- self.assertEqual(t.render(c), u'simple_only_unlimited_args - Expected result: 37, 42, 56, 89')
+ self.assertEqual(t.render(c), 'simple_only_unlimited_args - Expected result: 37, 42, 56, 89')
self.assertRaisesRegexp(template.TemplateSyntaxError,
"'simple_two_params' received too many positional arguments",
@@ -79,7 +79,7 @@ class CustomTagTests(TestCase):
template.Template, '{% load custom %}{% simple_one_default 37 42 56 %}')
t = template.Template('{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 %}')
- self.assertEqual(t.render(c), u'simple_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4')
+ self.assertEqual(t.render(c), 'simple_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4')
self.assertRaisesRegexp(template.TemplateSyntaxError,
"'simple_unlimited_args_kwargs' received some positional argument\(s\) after some keyword argument\(s\)",
@@ -109,50 +109,50 @@ class CustomTagTests(TestCase):
c = template.Context({'value': 42})
t = template.Template('{% load custom %}{% inclusion_no_params %}')
- self.assertEqual(t.render(c), u'inclusion_no_params - Expected result\n')
+ self.assertEqual(t.render(c), 'inclusion_no_params - Expected result\n')
t = template.Template('{% load custom %}{% inclusion_one_param 37 %}')
- self.assertEqual(t.render(c), u'inclusion_one_param - Expected result: 37\n')
+ self.assertEqual(t.render(c), 'inclusion_one_param - Expected result: 37\n')
t = template.Template('{% load custom %}{% inclusion_explicit_no_context 37 %}')
- self.assertEqual(t.render(c), u'inclusion_explicit_no_context - Expected result: 37\n')
+ self.assertEqual(t.render(c), 'inclusion_explicit_no_context - Expected result: 37\n')
t = template.Template('{% load custom %}{% inclusion_no_params_with_context %}')
- self.assertEqual(t.render(c), u'inclusion_no_params_with_context - Expected result (context value: 42)\n')
+ self.assertEqual(t.render(c), 'inclusion_no_params_with_context - Expected result (context value: 42)\n')
t = template.Template('{% load custom %}{% inclusion_params_and_context 37 %}')
- self.assertEqual(t.render(c), u'inclusion_params_and_context - Expected result (context value: 42): 37\n')
+ self.assertEqual(t.render(c), 'inclusion_params_and_context - Expected result (context value: 42): 37\n')
t = template.Template('{% load custom %}{% inclusion_two_params 37 42 %}')
- self.assertEqual(t.render(c), u'inclusion_two_params - Expected result: 37, 42\n')
+ self.assertEqual(t.render(c), 'inclusion_two_params - Expected result: 37, 42\n')
t = template.Template('{% load custom %}{% inclusion_one_default 37 %}')
- self.assertEqual(t.render(c), u'inclusion_one_default - Expected result: 37, hi\n')
+ self.assertEqual(t.render(c), 'inclusion_one_default - Expected result: 37, hi\n')
t = template.Template('{% load custom %}{% inclusion_one_default 37 two="hello" %}')
- self.assertEqual(t.render(c), u'inclusion_one_default - Expected result: 37, hello\n')
+ self.assertEqual(t.render(c), 'inclusion_one_default - Expected result: 37, hello\n')
t = template.Template('{% load custom %}{% inclusion_one_default one=99 two="hello" %}')
- self.assertEqual(t.render(c), u'inclusion_one_default - Expected result: 99, hello\n')
+ self.assertEqual(t.render(c), 'inclusion_one_default - Expected result: 99, hello\n')
self.assertRaisesRegexp(template.TemplateSyntaxError,
"'inclusion_one_default' received unexpected keyword argument 'three'",
template.Template, '{% load custom %}{% inclusion_one_default 99 two="hello" three="foo" %}')
t = template.Template('{% load custom %}{% inclusion_one_default 37 42 %}')
- self.assertEqual(t.render(c), u'inclusion_one_default - Expected result: 37, 42\n')
+ self.assertEqual(t.render(c), 'inclusion_one_default - Expected result: 37, 42\n')
t = template.Template('{% load custom %}{% inclusion_unlimited_args 37 %}')
- self.assertEqual(t.render(c), u'inclusion_unlimited_args - Expected result: 37, hi\n')
+ self.assertEqual(t.render(c), 'inclusion_unlimited_args - Expected result: 37, hi\n')
t = template.Template('{% load custom %}{% inclusion_unlimited_args 37 42 56 89 %}')
- self.assertEqual(t.render(c), u'inclusion_unlimited_args - Expected result: 37, 42, 56, 89\n')
+ self.assertEqual(t.render(c), 'inclusion_unlimited_args - Expected result: 37, 42, 56, 89\n')
t = template.Template('{% load custom %}{% inclusion_only_unlimited_args %}')
- self.assertEqual(t.render(c), u'inclusion_only_unlimited_args - Expected result: \n')
+ self.assertEqual(t.render(c), 'inclusion_only_unlimited_args - Expected result: \n')
t = template.Template('{% load custom %}{% inclusion_only_unlimited_args 37 42 56 89 %}')
- self.assertEqual(t.render(c), u'inclusion_only_unlimited_args - Expected result: 37, 42, 56, 89\n')
+ self.assertEqual(t.render(c), 'inclusion_only_unlimited_args - Expected result: 37, 42, 56, 89\n')
self.assertRaisesRegexp(template.TemplateSyntaxError,
"'inclusion_two_params' received too many positional arguments",
@@ -171,7 +171,7 @@ class CustomTagTests(TestCase):
template.Template, '{% load custom %}{% inclusion_unlimited_args %}')
t = template.Template('{% load custom %}{% inclusion_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 %}')
- self.assertEqual(t.render(c), u'inclusion_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4\n')
+ self.assertEqual(t.render(c), 'inclusion_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4\n')
self.assertRaisesRegexp(template.TemplateSyntaxError,
"'inclusion_unlimited_args_kwargs' received some positional argument\(s\) after some keyword argument\(s\)",
@@ -191,40 +191,40 @@ class CustomTagTests(TestCase):
c = template.Context({'value': 42})
t = template.Template('{% load custom %}{% inclusion_no_params_from_template %}')
- self.assertEqual(t.render(c), u'inclusion_no_params_from_template - Expected result\n')
+ self.assertEqual(t.render(c), 'inclusion_no_params_from_template - Expected result\n')
t = template.Template('{% load custom %}{% inclusion_one_param_from_template 37 %}')
- self.assertEqual(t.render(c), u'inclusion_one_param_from_template - Expected result: 37\n')
+ self.assertEqual(t.render(c), 'inclusion_one_param_from_template - Expected result: 37\n')
t = template.Template('{% load custom %}{% inclusion_explicit_no_context_from_template 37 %}')
- self.assertEqual(t.render(c), u'inclusion_explicit_no_context_from_template - Expected result: 37\n')
+ self.assertEqual(t.render(c), 'inclusion_explicit_no_context_from_template - Expected result: 37\n')
t = template.Template('{% load custom %}{% inclusion_no_params_with_context_from_template %}')
- self.assertEqual(t.render(c), u'inclusion_no_params_with_context_from_template - Expected result (context value: 42)\n')
+ self.assertEqual(t.render(c), 'inclusion_no_params_with_context_from_template - Expected result (context value: 42)\n')
t = template.Template('{% load custom %}{% inclusion_params_and_context_from_template 37 %}')
- self.assertEqual(t.render(c), u'inclusion_params_and_context_from_template - Expected result (context value: 42): 37\n')
+ self.assertEqual(t.render(c), 'inclusion_params_and_context_from_template - Expected result (context value: 42): 37\n')
t = template.Template('{% load custom %}{% inclusion_two_params_from_template 37 42 %}')
- self.assertEqual(t.render(c), u'inclusion_two_params_from_template - Expected result: 37, 42\n')
+ self.assertEqual(t.render(c), 'inclusion_two_params_from_template - Expected result: 37, 42\n')
t = template.Template('{% load custom %}{% inclusion_one_default_from_template 37 %}')
- self.assertEqual(t.render(c), u'inclusion_one_default_from_template - Expected result: 37, hi\n')
+ self.assertEqual(t.render(c), 'inclusion_one_default_from_template - Expected result: 37, hi\n')
t = template.Template('{% load custom %}{% inclusion_one_default_from_template 37 42 %}')
- self.assertEqual(t.render(c), u'inclusion_one_default_from_template - Expected result: 37, 42\n')
+ self.assertEqual(t.render(c), 'inclusion_one_default_from_template - Expected result: 37, 42\n')
t = template.Template('{% load custom %}{% inclusion_unlimited_args_from_template 37 %}')
- self.assertEqual(t.render(c), u'inclusion_unlimited_args_from_template - Expected result: 37, hi\n')
+ self.assertEqual(t.render(c), 'inclusion_unlimited_args_from_template - Expected result: 37, hi\n')
t = template.Template('{% load custom %}{% inclusion_unlimited_args_from_template 37 42 56 89 %}')
- self.assertEqual(t.render(c), u'inclusion_unlimited_args_from_template - Expected result: 37, 42, 56, 89\n')
+ self.assertEqual(t.render(c), 'inclusion_unlimited_args_from_template - Expected result: 37, 42, 56, 89\n')
t = template.Template('{% load custom %}{% inclusion_only_unlimited_args_from_template %}')
- self.assertEqual(t.render(c), u'inclusion_only_unlimited_args_from_template - Expected result: \n')
+ self.assertEqual(t.render(c), 'inclusion_only_unlimited_args_from_template - Expected result: \n')
t = template.Template('{% load custom %}{% inclusion_only_unlimited_args_from_template 37 42 56 89 %}')
- self.assertEqual(t.render(c), u'inclusion_only_unlimited_args_from_template - Expected result: 37, 42, 56, 89\n')
+ self.assertEqual(t.render(c), 'inclusion_only_unlimited_args_from_template - Expected result: 37, 42, 56, 89\n')
def test_inclusion_tag_registration(self):
# Test that the decorators preserve the decorated function's docstring, name and attributes.
@@ -249,10 +249,10 @@ class CustomTagTests(TestCase):
"""
c = template.Context({})
t = template.Template('{% load custom %}{% inclusion_tag_current_app %}')
- self.assertEqual(t.render(c).strip(), u'None')
+ self.assertEqual(t.render(c).strip(), 'None')
c.current_app = 'advanced'
- self.assertEqual(t.render(c).strip(), u'advanced')
+ self.assertEqual(t.render(c).strip(), 'advanced')
def test_15070_use_l10n(self):
"""
@@ -261,59 +261,59 @@ class CustomTagTests(TestCase):
"""
c = template.Context({})
t = template.Template('{% load custom %}{% inclusion_tag_use_l10n %}')
- self.assertEqual(t.render(c).strip(), u'None')
+ self.assertEqual(t.render(c).strip(), 'None')
c.use_l10n = True
- self.assertEqual(t.render(c).strip(), u'True')
+ self.assertEqual(t.render(c).strip(), 'True')
def test_assignment_tags(self):
c = template.Context({'value': 42})
t = template.Template('{% load custom %}{% assignment_no_params as var %}The result is: {{ var }}')
- self.assertEqual(t.render(c), u'The result is: assignment_no_params - Expected result')
+ self.assertEqual(t.render(c), 'The result is: assignment_no_params - Expected result')
t = template.Template('{% load custom %}{% assignment_one_param 37 as var %}The result is: {{ var }}')
- self.assertEqual(t.render(c), u'The result is: assignment_one_param - Expected result: 37')
+ self.assertEqual(t.render(c), 'The result is: assignment_one_param - Expected result: 37')
t = template.Template('{% load custom %}{% assignment_explicit_no_context 37 as var %}The result is: {{ var }}')
- self.assertEqual(t.render(c), u'The result is: assignment_explicit_no_context - Expected result: 37')
+ self.assertEqual(t.render(c), 'The result is: assignment_explicit_no_context - Expected result: 37')
t = template.Template('{% load custom %}{% assignment_no_params_with_context as var %}The result is: {{ var }}')
- self.assertEqual(t.render(c), u'The result is: assignment_no_params_with_context - Expected result (context value: 42)')
+ self.assertEqual(t.render(c), 'The result is: assignment_no_params_with_context - Expected result (context value: 42)')
t = template.Template('{% load custom %}{% assignment_params_and_context 37 as var %}The result is: {{ var }}')
- self.assertEqual(t.render(c), u'The result is: assignment_params_and_context - Expected result (context value: 42): 37')
+ self.assertEqual(t.render(c), 'The result is: assignment_params_and_context - Expected result (context value: 42): 37')
t = template.Template('{% load custom %}{% assignment_two_params 37 42 as var %}The result is: {{ var }}')
- self.assertEqual(t.render(c), u'The result is: assignment_two_params - Expected result: 37, 42')
+ self.assertEqual(t.render(c), 'The result is: assignment_two_params - Expected result: 37, 42')
t = template.Template('{% load custom %}{% assignment_one_default 37 as var %}The result is: {{ var }}')
- self.assertEqual(t.render(c), u'The result is: assignment_one_default - Expected result: 37, hi')
+ self.assertEqual(t.render(c), 'The result is: assignment_one_default - Expected result: 37, hi')
t = template.Template('{% load custom %}{% assignment_one_default 37 two="hello" as var %}The result is: {{ var }}')
- self.assertEqual(t.render(c), u'The result is: assignment_one_default - Expected result: 37, hello')
+ self.assertEqual(t.render(c), 'The result is: assignment_one_default - Expected result: 37, hello')
t = template.Template('{% load custom %}{% assignment_one_default one=99 two="hello" as var %}The result is: {{ var }}')
- self.assertEqual(t.render(c), u'The result is: assignment_one_default - Expected result: 99, hello')
+ self.assertEqual(t.render(c), 'The result is: assignment_one_default - Expected result: 99, hello')
self.assertRaisesRegexp(template.TemplateSyntaxError,
"'assignment_one_default' received unexpected keyword argument 'three'",
template.Template, '{% load custom %}{% assignment_one_default 99 two="hello" three="foo" as var %}')
t = template.Template('{% load custom %}{% assignment_one_default 37 42 as var %}The result is: {{ var }}')
- self.assertEqual(t.render(c), u'The result is: assignment_one_default - Expected result: 37, 42')
+ self.assertEqual(t.render(c), 'The result is: assignment_one_default - Expected result: 37, 42')
t = template.Template('{% load custom %}{% assignment_unlimited_args 37 as var %}The result is: {{ var }}')
- self.assertEqual(t.render(c), u'The result is: assignment_unlimited_args - Expected result: 37, hi')
+ self.assertEqual(t.render(c), 'The result is: assignment_unlimited_args - Expected result: 37, hi')
t = template.Template('{% load custom %}{% assignment_unlimited_args 37 42 56 89 as var %}The result is: {{ var }}')
- self.assertEqual(t.render(c), u'The result is: assignment_unlimited_args - Expected result: 37, 42, 56, 89')
+ self.assertEqual(t.render(c), 'The result is: assignment_unlimited_args - Expected result: 37, 42, 56, 89')
t = template.Template('{% load custom %}{% assignment_only_unlimited_args as var %}The result is: {{ var }}')
- self.assertEqual(t.render(c), u'The result is: assignment_only_unlimited_args - Expected result: ')
+ self.assertEqual(t.render(c), 'The result is: assignment_only_unlimited_args - Expected result: ')
t = template.Template('{% load custom %}{% assignment_only_unlimited_args 37 42 56 89 as var %}The result is: {{ var }}')
- self.assertEqual(t.render(c), u'The result is: assignment_only_unlimited_args - Expected result: 37, 42, 56, 89')
+ self.assertEqual(t.render(c), 'The result is: assignment_only_unlimited_args - Expected result: 37, 42, 56, 89')
self.assertRaisesRegexp(template.TemplateSyntaxError,
"'assignment_one_param' tag takes at least 2 arguments and the second last argument must be 'as'",
@@ -344,7 +344,7 @@ class CustomTagTests(TestCase):
template.Template, '{% load custom %}{% assignment_unlimited_args as var %}The result is: {{ var }}')
t = template.Template('{% load custom %}{% assignment_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 as var %}The result is: {{ var }}')
- self.assertEqual(t.render(c), u'The result is: assignment_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4')
+ self.assertEqual(t.render(c), 'The result is: assignment_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4')
self.assertRaisesRegexp(template.TemplateSyntaxError,
"'assignment_unlimited_args_kwargs' received some positional argument\(s\) after some keyword argument\(s\)",
diff --git a/tests/regressiontests/templates/filters.py b/tests/regressiontests/templates/filters.py
index 41f8e43c9e..fd570700af 100644
--- a/tests/regressiontests/templates/filters.py
+++ b/tests/regressiontests/templates/filters.py
@@ -6,20 +6,22 @@ The tests are hidden inside a function so that things like timestamps and
timezones are only evaluated at the moment of execution and will therefore be
consistent.
"""
+from __future__ import unicode_literals
from datetime import date, datetime, timedelta
+from django.test.utils import str_prefix
from django.utils.tzinfo import LocalTimezone, FixedOffset
from django.utils.safestring import mark_safe
# These two classes are used to test auto-escaping of __unicode__ output.
class UnsafeClass:
def __unicode__(self):
- return u'you & me'
+ return 'you & me'
class SafeClass:
def __unicode__(self):
- return mark_safe(u'you &gt; me')
+ return mark_safe('you &gt; me')
# RESULT SYNTAX --
# 'template_name': ('template contents', 'context dict',
@@ -84,66 +86,66 @@ def get_filter_tests():
'filter-timeuntil12' : ('{{ a|timeuntil:b }}', {'a': today, 'b': today}, '0 minutes'),
'filter-timeuntil13' : ('{{ a|timeuntil:b }}', {'a': today, 'b': today - timedelta(hours=24)}, '1 day'),
- 'filter-addslash01': ("{% autoescape off %}{{ a|addslashes }} {{ b|addslashes }}{% endautoescape %}", {"a": "<a>'", "b": mark_safe("<a>'")}, ur"<a>\' <a>\'"),
- 'filter-addslash02': ("{{ a|addslashes }} {{ b|addslashes }}", {"a": "<a>'", "b": mark_safe("<a>'")}, ur"&lt;a&gt;\&#39; <a>\'"),
+ 'filter-addslash01': ("{% autoescape off %}{{ a|addslashes }} {{ b|addslashes }}{% endautoescape %}", {"a": "<a>'", "b": mark_safe("<a>'")}, r"<a>\' <a>\'"),
+ 'filter-addslash02': ("{{ a|addslashes }} {{ b|addslashes }}", {"a": "<a>'", "b": mark_safe("<a>'")}, r"&lt;a&gt;\&#39; <a>\'"),
- 'filter-capfirst01': ("{% autoescape off %}{{ a|capfirst }} {{ b|capfirst }}{% endautoescape %}", {"a": "fred>", "b": mark_safe("fred&gt;")}, u"Fred> Fred&gt;"),
- 'filter-capfirst02': ("{{ a|capfirst }} {{ b|capfirst }}", {"a": "fred>", "b": mark_safe("fred&gt;")}, u"Fred&gt; Fred&gt;"),
+ 'filter-capfirst01': ("{% autoescape off %}{{ a|capfirst }} {{ b|capfirst }}{% endautoescape %}", {"a": "fred>", "b": mark_safe("fred&gt;")}, "Fred> Fred&gt;"),
+ 'filter-capfirst02': ("{{ a|capfirst }} {{ b|capfirst }}", {"a": "fred>", "b": mark_safe("fred&gt;")}, "Fred&gt; Fred&gt;"),
# Note that applying fix_ampsersands in autoescape mode leads to
# double escaping.
- 'filter-fix_ampersands01': ("{% autoescape off %}{{ a|fix_ampersands }} {{ b|fix_ampersands }}{% endautoescape %}", {"a": "a&b", "b": mark_safe("a&b")}, u"a&amp;b a&amp;b"),
- 'filter-fix_ampersands02': ("{{ a|fix_ampersands }} {{ b|fix_ampersands }}", {"a": "a&b", "b": mark_safe("a&b")}, u"a&amp;amp;b a&amp;b"),
+ 'filter-fix_ampersands01': ("{% autoescape off %}{{ a|fix_ampersands }} {{ b|fix_ampersands }}{% endautoescape %}", {"a": "a&b", "b": mark_safe("a&b")}, "a&amp;b a&amp;b"),
+ 'filter-fix_ampersands02': ("{{ a|fix_ampersands }} {{ b|fix_ampersands }}", {"a": "a&b", "b": mark_safe("a&b")}, "a&amp;amp;b a&amp;b"),
- 'filter-floatformat01': ("{% autoescape off %}{{ a|floatformat }} {{ b|floatformat }}{% endautoescape %}", {"a": "1.42", "b": mark_safe("1.42")}, u"1.4 1.4"),
- 'filter-floatformat02': ("{{ a|floatformat }} {{ b|floatformat }}", {"a": "1.42", "b": mark_safe("1.42")}, u"1.4 1.4"),
+ 'filter-floatformat01': ("{% autoescape off %}{{ a|floatformat }} {{ b|floatformat }}{% endautoescape %}", {"a": "1.42", "b": mark_safe("1.42")}, "1.4 1.4"),
+ 'filter-floatformat02': ("{{ a|floatformat }} {{ b|floatformat }}", {"a": "1.42", "b": mark_safe("1.42")}, "1.4 1.4"),
# The contents of "linenumbers" is escaped according to the current
# autoescape setting.
- 'filter-linenumbers01': ("{{ a|linenumbers }} {{ b|linenumbers }}", {"a": "one\n<two>\nthree", "b": mark_safe("one\n&lt;two&gt;\nthree")}, u"1. one\n2. &lt;two&gt;\n3. three 1. one\n2. &lt;two&gt;\n3. three"),
- 'filter-linenumbers02': ("{% autoescape off %}{{ a|linenumbers }} {{ b|linenumbers }}{% endautoescape %}", {"a": "one\n<two>\nthree", "b": mark_safe("one\n&lt;two&gt;\nthree")}, u"1. one\n2. <two>\n3. three 1. one\n2. &lt;two&gt;\n3. three"),
+ 'filter-linenumbers01': ("{{ a|linenumbers }} {{ b|linenumbers }}", {"a": "one\n<two>\nthree", "b": mark_safe("one\n&lt;two&gt;\nthree")}, "1. one\n2. &lt;two&gt;\n3. three 1. one\n2. &lt;two&gt;\n3. three"),
+ 'filter-linenumbers02': ("{% autoescape off %}{{ a|linenumbers }} {{ b|linenumbers }}{% endautoescape %}", {"a": "one\n<two>\nthree", "b": mark_safe("one\n&lt;two&gt;\nthree")}, "1. one\n2. <two>\n3. three 1. one\n2. &lt;two&gt;\n3. three"),
- 'filter-lower01': ("{% autoescape off %}{{ a|lower }} {{ b|lower }}{% endautoescape %}", {"a": "Apple & banana", "b": mark_safe("Apple &amp; banana")}, u"apple & banana apple &amp; banana"),
- 'filter-lower02': ("{{ a|lower }} {{ b|lower }}", {"a": "Apple & banana", "b": mark_safe("Apple &amp; banana")}, u"apple &amp; banana apple &amp; banana"),
+ 'filter-lower01': ("{% autoescape off %}{{ a|lower }} {{ b|lower }}{% endautoescape %}", {"a": "Apple & banana", "b": mark_safe("Apple &amp; banana")}, "apple & banana apple &amp; banana"),
+ 'filter-lower02': ("{{ a|lower }} {{ b|lower }}", {"a": "Apple & banana", "b": mark_safe("Apple &amp; banana")}, "apple &amp; banana apple &amp; banana"),
# The make_list filter can destroy existing escaping, so the results are
# escaped.
- 'filter-make_list01': ("{% autoescape off %}{{ a|make_list }}{% endautoescape %}", {"a": mark_safe("&")}, u"[u'&']"),
- 'filter-make_list02': ("{{ a|make_list }}", {"a": mark_safe("&")}, u"[u&#39;&amp;&#39;]"),
- 'filter-make_list03': ('{% autoescape off %}{{ a|make_list|stringformat:"s"|safe }}{% endautoescape %}', {"a": mark_safe("&")}, u"[u'&']"),
- 'filter-make_list04': ('{{ a|make_list|stringformat:"s"|safe }}', {"a": mark_safe("&")}, u"[u'&']"),
+ 'filter-make_list01': ("{% autoescape off %}{{ a|make_list }}{% endautoescape %}", {"a": mark_safe("&")}, str_prefix("[%(_)s'&']")),
+ 'filter-make_list02': ("{{ a|make_list }}", {"a": mark_safe("&")}, "[u&#39;&amp;&#39;]"),
+ 'filter-make_list03': ('{% autoescape off %}{{ a|make_list|stringformat:"s"|safe }}{% endautoescape %}', {"a": mark_safe("&")}, str_prefix("[%(_)s'&']")),
+ 'filter-make_list04': ('{{ a|make_list|stringformat:"s"|safe }}', {"a": mark_safe("&")}, str_prefix("[%(_)s'&']")),
# Running slugify on a pre-escaped string leads to odd behavior,
# but the result is still safe.
- 'filter-slugify01': ("{% autoescape off %}{{ a|slugify }} {{ b|slugify }}{% endautoescape %}", {"a": "a & b", "b": mark_safe("a &amp; b")}, u"a-b a-amp-b"),
- 'filter-slugify02': ("{{ a|slugify }} {{ b|slugify }}", {"a": "a & b", "b": mark_safe("a &amp; b")}, u"a-b a-amp-b"),
+ 'filter-slugify01': ("{% autoescape off %}{{ a|slugify }} {{ b|slugify }}{% endautoescape %}", {"a": "a & b", "b": mark_safe("a &amp; b")}, "a-b a-amp-b"),
+ 'filter-slugify02': ("{{ a|slugify }} {{ b|slugify }}", {"a": "a & b", "b": mark_safe("a &amp; b")}, "a-b a-amp-b"),
# Notice that escaping is applied *after* any filters, so the string
# formatting here only needs to deal with pre-escaped characters.
'filter-stringformat01': ('{% autoescape off %}.{{ a|stringformat:"5s" }}. .{{ b|stringformat:"5s" }}.{% endautoescape %}',
- {"a": "a<b", "b": mark_safe("a<b")}, u". a<b. . a<b."),
+ {"a": "a<b", "b": mark_safe("a<b")}, ". a<b. . a<b."),
'filter-stringformat02': ('.{{ a|stringformat:"5s" }}. .{{ b|stringformat:"5s" }}.', {"a": "a<b", "b": mark_safe("a<b")},
- u". a&lt;b. . a<b."),
+ ". a&lt;b. . a<b."),
# Test the title filter
- 'filter-title1' : ('{{ a|title }}', {'a' : 'JOE\'S CRAB SHACK'}, u'Joe&#39;s Crab Shack'),
- 'filter-title2' : ('{{ a|title }}', {'a' : '555 WEST 53RD STREET'}, u'555 West 53rd Street'),
+ 'filter-title1' : ('{{ a|title }}', {'a' : 'JOE\'S CRAB SHACK'}, 'Joe&#39;s Crab Shack'),
+ 'filter-title2' : ('{{ a|title }}', {'a' : '555 WEST 53RD STREET'}, '555 West 53rd Street'),
'filter-truncatewords01': ('{% autoescape off %}{{ a|truncatewords:"2" }} {{ b|truncatewords:"2"}}{% endautoescape %}',
- {"a": "alpha & bravo", "b": mark_safe("alpha &amp; bravo")}, u"alpha & ... alpha &amp; ..."),
+ {"a": "alpha & bravo", "b": mark_safe("alpha &amp; bravo")}, "alpha & ... alpha &amp; ..."),
'filter-truncatewords02': ('{{ a|truncatewords:"2" }} {{ b|truncatewords:"2"}}',
- {"a": "alpha & bravo", "b": mark_safe("alpha &amp; bravo")}, u"alpha &amp; ... alpha &amp; ..."),
+ {"a": "alpha & bravo", "b": mark_safe("alpha &amp; bravo")}, "alpha &amp; ... alpha &amp; ..."),
- 'filter-truncatechars01': ('{{ a|truncatechars:5 }}', {'a': "Testing, testing"}, u"Te..."),
- 'filter-truncatechars02': ('{{ a|truncatechars:7 }}', {'a': "Testing"}, u"Testing"),
+ 'filter-truncatechars01': ('{{ a|truncatechars:5 }}', {'a': "Testing, testing"}, "Te..."),
+ 'filter-truncatechars02': ('{{ a|truncatechars:7 }}', {'a': "Testing"}, "Testing"),
# The "upper" filter messes up entities (which are case-sensitive),
# so it's not safe for non-escaping purposes.
- 'filter-upper01': ('{% autoescape off %}{{ a|upper }} {{ b|upper }}{% endautoescape %}', {"a": "a & b", "b": mark_safe("a &amp; b")}, u"A & B A &AMP; B"),
- 'filter-upper02': ('{{ a|upper }} {{ b|upper }}', {"a": "a & b", "b": mark_safe("a &amp; b")}, u"A &amp; B A &amp;AMP; B"),
+ 'filter-upper01': ('{% autoescape off %}{{ a|upper }} {{ b|upper }}{% endautoescape %}', {"a": "a & b", "b": mark_safe("a &amp; b")}, "A & B A &AMP; B"),
+ 'filter-upper02': ('{{ a|upper }} {{ b|upper }}', {"a": "a & b", "b": mark_safe("a &amp; b")}, "A &amp; B A &amp;AMP; B"),
- 'filter-urlize01': ('{% autoescape off %}{{ a|urlize }} {{ b|urlize }}{% endautoescape %}', {"a": "http://example.com/?x=&y=", "b": mark_safe("http://example.com?x=&amp;y=")}, u'<a href="http://example.com/?x=&y=" rel="nofollow">http://example.com/?x=&y=</a> <a href="http://example.com?x=&amp;y=" rel="nofollow">http://example.com?x=&amp;y=</a>'),
- 'filter-urlize02': ('{{ a|urlize }} {{ b|urlize }}', {"a": "http://example.com/?x=&y=", "b": mark_safe("http://example.com?x=&amp;y=")}, u'<a href="http://example.com/?x=&amp;y=" rel="nofollow">http://example.com/?x=&amp;y=</a> <a href="http://example.com?x=&amp;y=" rel="nofollow">http://example.com?x=&amp;y=</a>'),
+ 'filter-urlize01': ('{% autoescape off %}{{ a|urlize }} {{ b|urlize }}{% endautoescape %}', {"a": "http://example.com/?x=&y=", "b": mark_safe("http://example.com?x=&amp;y=")}, '<a href="http://example.com/?x=&y=" rel="nofollow">http://example.com/?x=&y=</a> <a href="http://example.com?x=&amp;y=" rel="nofollow">http://example.com?x=&amp;y=</a>'),
+ 'filter-urlize02': ('{{ a|urlize }} {{ b|urlize }}', {"a": "http://example.com/?x=&y=", "b": mark_safe("http://example.com?x=&amp;y=")}, '<a href="http://example.com/?x=&amp;y=" rel="nofollow">http://example.com/?x=&amp;y=</a> <a href="http://example.com?x=&amp;y=" rel="nofollow">http://example.com?x=&amp;y=</a>'),
'filter-urlize03': ('{% autoescape off %}{{ a|urlize }}{% endautoescape %}', {"a": mark_safe("a &amp; b")}, 'a &amp; b'),
'filter-urlize04': ('{{ a|urlize }}', {"a": mark_safe("a &amp; b")}, 'a &amp; b'),
@@ -156,73 +158,73 @@ def get_filter_tests():
'filter-urlize07': ('{{ a|urlize }}', {"a": "Email me at me@example.com"}, 'Email me at <a href="mailto:me@example.com">me@example.com</a>'),
'filter-urlize08': ('{{ a|urlize }}', {"a": "Email me at <me@example.com>"}, 'Email me at &lt;<a href="mailto:me@example.com">me@example.com</a>&gt;'),
- 'filter-urlizetrunc01': ('{% autoescape off %}{{ a|urlizetrunc:"8" }} {{ b|urlizetrunc:"8" }}{% endautoescape %}', {"a": '"Unsafe" http://example.com/x=&y=', "b": mark_safe('&quot;Safe&quot; http://example.com?x=&amp;y=')}, u'"Unsafe" <a href="http://example.com/x=&y=" rel="nofollow">http:...</a> &quot;Safe&quot; <a href="http://example.com?x=&amp;y=" rel="nofollow">http:...</a>'),
- 'filter-urlizetrunc02': ('{{ a|urlizetrunc:"8" }} {{ b|urlizetrunc:"8" }}', {"a": '"Unsafe" http://example.com/x=&y=', "b": mark_safe('&quot;Safe&quot; http://example.com?x=&amp;y=')}, u'&quot;Unsafe&quot; <a href="http://example.com/x=&amp;y=" rel="nofollow">http:...</a> &quot;Safe&quot; <a href="http://example.com?x=&amp;y=" rel="nofollow">http:...</a>'),
+ 'filter-urlizetrunc01': ('{% autoescape off %}{{ a|urlizetrunc:"8" }} {{ b|urlizetrunc:"8" }}{% endautoescape %}', {"a": '"Unsafe" http://example.com/x=&y=', "b": mark_safe('&quot;Safe&quot; http://example.com?x=&amp;y=')}, '"Unsafe" <a href="http://example.com/x=&y=" rel="nofollow">http:...</a> &quot;Safe&quot; <a href="http://example.com?x=&amp;y=" rel="nofollow">http:...</a>'),
+ 'filter-urlizetrunc02': ('{{ a|urlizetrunc:"8" }} {{ b|urlizetrunc:"8" }}', {"a": '"Unsafe" http://example.com/x=&y=', "b": mark_safe('&quot;Safe&quot; http://example.com?x=&amp;y=')}, '&quot;Unsafe&quot; <a href="http://example.com/x=&amp;y=" rel="nofollow">http:...</a> &quot;Safe&quot; <a href="http://example.com?x=&amp;y=" rel="nofollow">http:...</a>'),
'filter-wordcount01': ('{% autoescape off %}{{ a|wordcount }} {{ b|wordcount }}{% endautoescape %}', {"a": "a & b", "b": mark_safe("a &amp; b")}, "3 3"),
'filter-wordcount02': ('{{ a|wordcount }} {{ b|wordcount }}', {"a": "a & b", "b": mark_safe("a &amp; b")}, "3 3"),
- 'filter-wordwrap01': ('{% autoescape off %}{{ a|wordwrap:"3" }} {{ b|wordwrap:"3" }}{% endautoescape %}', {"a": "a & b", "b": mark_safe("a & b")}, u"a &\nb a &\nb"),
- 'filter-wordwrap02': ('{{ a|wordwrap:"3" }} {{ b|wordwrap:"3" }}', {"a": "a & b", "b": mark_safe("a & b")}, u"a &amp;\nb a &\nb"),
+ 'filter-wordwrap01': ('{% autoescape off %}{{ a|wordwrap:"3" }} {{ b|wordwrap:"3" }}{% endautoescape %}', {"a": "a & b", "b": mark_safe("a & b")}, "a &\nb a &\nb"),
+ 'filter-wordwrap02': ('{{ a|wordwrap:"3" }} {{ b|wordwrap:"3" }}', {"a": "a & b", "b": mark_safe("a & b")}, "a &amp;\nb a &\nb"),
- 'filter-ljust01': ('{% autoescape off %}.{{ a|ljust:"5" }}. .{{ b|ljust:"5" }}.{% endautoescape %}', {"a": "a&b", "b": mark_safe("a&b")}, u".a&b . .a&b ."),
- 'filter-ljust02': ('.{{ a|ljust:"5" }}. .{{ b|ljust:"5" }}.', {"a": "a&b", "b": mark_safe("a&b")}, u".a&amp;b . .a&b ."),
+ 'filter-ljust01': ('{% autoescape off %}.{{ a|ljust:"5" }}. .{{ b|ljust:"5" }}.{% endautoescape %}', {"a": "a&b", "b": mark_safe("a&b")}, ".a&b . .a&b ."),
+ 'filter-ljust02': ('.{{ a|ljust:"5" }}. .{{ b|ljust:"5" }}.', {"a": "a&b", "b": mark_safe("a&b")}, ".a&amp;b . .a&b ."),
- 'filter-rjust01': ('{% autoescape off %}.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.{% endautoescape %}', {"a": "a&b", "b": mark_safe("a&b")}, u". a&b. . a&b."),
- 'filter-rjust02': ('.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.', {"a": "a&b", "b": mark_safe("a&b")}, u". a&amp;b. . a&b."),
+ 'filter-rjust01': ('{% autoescape off %}.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.{% endautoescape %}', {"a": "a&b", "b": mark_safe("a&b")}, ". a&b. . a&b."),
+ 'filter-rjust02': ('.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.', {"a": "a&b", "b": mark_safe("a&b")}, ". a&amp;b. . a&b."),
- 'filter-center01': ('{% autoescape off %}.{{ a|center:"5" }}. .{{ b|center:"5" }}.{% endautoescape %}', {"a": "a&b", "b": mark_safe("a&b")}, u". a&b . . a&b ."),
- 'filter-center02': ('.{{ a|center:"5" }}. .{{ b|center:"5" }}.', {"a": "a&b", "b": mark_safe("a&b")}, u". a&amp;b . . a&b ."),
+ 'filter-center01': ('{% autoescape off %}.{{ a|center:"5" }}. .{{ b|center:"5" }}.{% endautoescape %}', {"a": "a&b", "b": mark_safe("a&b")}, ". a&b . . a&b ."),
+ 'filter-center02': ('.{{ a|center:"5" }}. .{{ b|center:"5" }}.', {"a": "a&b", "b": mark_safe("a&b")}, ". a&amp;b . . a&b ."),
- 'filter-cut01': ('{% autoescape off %}{{ a|cut:"x" }} {{ b|cut:"x" }}{% endautoescape %}', {"a": "x&y", "b": mark_safe("x&amp;y")}, u"&y &amp;y"),
- 'filter-cut02': ('{{ a|cut:"x" }} {{ b|cut:"x" }}', {"a": "x&y", "b": mark_safe("x&amp;y")}, u"&amp;y &amp;y"),
- 'filter-cut03': ('{% autoescape off %}{{ a|cut:"&" }} {{ b|cut:"&" }}{% endautoescape %}', {"a": "x&y", "b": mark_safe("x&amp;y")}, u"xy xamp;y"),
- 'filter-cut04': ('{{ a|cut:"&" }} {{ b|cut:"&" }}', {"a": "x&y", "b": mark_safe("x&amp;y")}, u"xy xamp;y"),
+ 'filter-cut01': ('{% autoescape off %}{{ a|cut:"x" }} {{ b|cut:"x" }}{% endautoescape %}', {"a": "x&y", "b": mark_safe("x&amp;y")}, "&y &amp;y"),
+ 'filter-cut02': ('{{ a|cut:"x" }} {{ b|cut:"x" }}', {"a": "x&y", "b": mark_safe("x&amp;y")}, "&amp;y &amp;y"),
+ 'filter-cut03': ('{% autoescape off %}{{ a|cut:"&" }} {{ b|cut:"&" }}{% endautoescape %}', {"a": "x&y", "b": mark_safe("x&amp;y")}, "xy xamp;y"),
+ 'filter-cut04': ('{{ a|cut:"&" }} {{ b|cut:"&" }}', {"a": "x&y", "b": mark_safe("x&amp;y")}, "xy xamp;y"),
# Passing ';' to cut can break existing HTML entities, so those strings
# are auto-escaped.
- 'filter-cut05': ('{% autoescape off %}{{ a|cut:";" }} {{ b|cut:";" }}{% endautoescape %}', {"a": "x&y", "b": mark_safe("x&amp;y")}, u"x&y x&ampy"),
- 'filter-cut06': ('{{ a|cut:";" }} {{ b|cut:";" }}', {"a": "x&y", "b": mark_safe("x&amp;y")}, u"x&amp;y x&amp;ampy"),
+ 'filter-cut05': ('{% autoescape off %}{{ a|cut:";" }} {{ b|cut:";" }}{% endautoescape %}', {"a": "x&y", "b": mark_safe("x&amp;y")}, "x&y x&ampy"),
+ 'filter-cut06': ('{{ a|cut:";" }} {{ b|cut:";" }}', {"a": "x&y", "b": mark_safe("x&amp;y")}, "x&amp;y x&amp;ampy"),
# The "escape" filter works the same whether autoescape is on or off,
# but it has no effect on strings already marked as safe.
- 'filter-escape01': ('{{ a|escape }} {{ b|escape }}', {"a": "x&y", "b": mark_safe("x&y")}, u"x&amp;y x&y"),
+ 'filter-escape01': ('{{ a|escape }} {{ b|escape }}', {"a": "x&y", "b": mark_safe("x&y")}, "x&amp;y x&y"),
'filter-escape02': ('{% autoescape off %}{{ a|escape }} {{ b|escape }}{% endautoescape %}', {"a": "x&y", "b": mark_safe("x&y")}, "x&amp;y x&y"),
# It is only applied once, regardless of the number of times it
# appears in a chain.
- 'filter-escape03': ('{% autoescape off %}{{ a|escape|escape }}{% endautoescape %}', {"a": "x&y"}, u"x&amp;y"),
- 'filter-escape04': ('{{ a|escape|escape }}', {"a": "x&y"}, u"x&amp;y"),
+ 'filter-escape03': ('{% autoescape off %}{{ a|escape|escape }}{% endautoescape %}', {"a": "x&y"}, "x&amp;y"),
+ 'filter-escape04': ('{{ a|escape|escape }}', {"a": "x&y"}, "x&amp;y"),
# Force_escape is applied immediately. It can be used to provide
# double-escaping, for example.
- 'filter-force-escape01': ('{% autoescape off %}{{ a|force_escape }}{% endautoescape %}', {"a": "x&y"}, u"x&amp;y"),
- 'filter-force-escape02': ('{{ a|force_escape }}', {"a": "x&y"}, u"x&amp;y"),
- 'filter-force-escape03': ('{% autoescape off %}{{ a|force_escape|force_escape }}{% endautoescape %}', {"a": "x&y"}, u"x&amp;amp;y"),
- 'filter-force-escape04': ('{{ a|force_escape|force_escape }}', {"a": "x&y"}, u"x&amp;amp;y"),
+ 'filter-force-escape01': ('{% autoescape off %}{{ a|force_escape }}{% endautoescape %}', {"a": "x&y"}, "x&amp;y"),
+ 'filter-force-escape02': ('{{ a|force_escape }}', {"a": "x&y"}, "x&amp;y"),
+ 'filter-force-escape03': ('{% autoescape off %}{{ a|force_escape|force_escape }}{% endautoescape %}', {"a": "x&y"}, "x&amp;amp;y"),
+ 'filter-force-escape04': ('{{ a|force_escape|force_escape }}', {"a": "x&y"}, "x&amp;amp;y"),
# Because the result of force_escape is "safe", an additional
# escape filter has no effect.
- 'filter-force-escape05': ('{% autoescape off %}{{ a|force_escape|escape }}{% endautoescape %}', {"a": "x&y"}, u"x&amp;y"),
- 'filter-force-escape06': ('{{ a|force_escape|escape }}', {"a": "x&y"}, u"x&amp;y"),
- 'filter-force-escape07': ('{% autoescape off %}{{ a|escape|force_escape }}{% endautoescape %}', {"a": "x&y"}, u"x&amp;y"),
- 'filter-force-escape08': ('{{ a|escape|force_escape }}', {"a": "x&y"}, u"x&amp;y"),
+ 'filter-force-escape05': ('{% autoescape off %}{{ a|force_escape|escape }}{% endautoescape %}', {"a": "x&y"}, "x&amp;y"),
+ 'filter-force-escape06': ('{{ a|force_escape|escape }}', {"a": "x&y"}, "x&amp;y"),
+ 'filter-force-escape07': ('{% autoescape off %}{{ a|escape|force_escape }}{% endautoescape %}', {"a": "x&y"}, "x&amp;y"),
+ 'filter-force-escape08': ('{{ a|escape|force_escape }}', {"a": "x&y"}, "x&amp;y"),
# The contents in "linebreaks" and "linebreaksbr" are escaped
# according to the current autoescape setting.
- 'filter-linebreaks01': ('{{ a|linebreaks }} {{ b|linebreaks }}', {"a": "x&\ny", "b": mark_safe("x&\ny")}, u"<p>x&amp;<br />y</p> <p>x&<br />y</p>"),
- 'filter-linebreaks02': ('{% autoescape off %}{{ a|linebreaks }} {{ b|linebreaks }}{% endautoescape %}', {"a": "x&\ny", "b": mark_safe("x&\ny")}, u"<p>x&<br />y</p> <p>x&<br />y</p>"),
+ 'filter-linebreaks01': ('{{ a|linebreaks }} {{ b|linebreaks }}', {"a": "x&\ny", "b": mark_safe("x&\ny")}, "<p>x&amp;<br />y</p> <p>x&<br />y</p>"),
+ 'filter-linebreaks02': ('{% autoescape off %}{{ a|linebreaks }} {{ b|linebreaks }}{% endautoescape %}', {"a": "x&\ny", "b": mark_safe("x&\ny")}, "<p>x&<br />y</p> <p>x&<br />y</p>"),
- 'filter-linebreaksbr01': ('{{ a|linebreaksbr }} {{ b|linebreaksbr }}', {"a": "x&\ny", "b": mark_safe("x&\ny")}, u"x&amp;<br />y x&<br />y"),
- 'filter-linebreaksbr02': ('{% autoescape off %}{{ a|linebreaksbr }} {{ b|linebreaksbr }}{% endautoescape %}', {"a": "x&\ny", "b": mark_safe("x&\ny")}, u"x&<br />y x&<br />y"),
+ 'filter-linebreaksbr01': ('{{ a|linebreaksbr }} {{ b|linebreaksbr }}', {"a": "x&\ny", "b": mark_safe("x&\ny")}, "x&amp;<br />y x&<br />y"),
+ 'filter-linebreaksbr02': ('{% autoescape off %}{{ a|linebreaksbr }} {{ b|linebreaksbr }}{% endautoescape %}', {"a": "x&\ny", "b": mark_safe("x&\ny")}, "x&<br />y x&<br />y"),
- 'filter-safe01': ("{{ a }} -- {{ a|safe }}", {"a": u"<b>hello</b>"}, "&lt;b&gt;hello&lt;/b&gt; -- <b>hello</b>"),
- 'filter-safe02': ("{% autoescape off %}{{ a }} -- {{ a|safe }}{% endautoescape %}", {"a": "<b>hello</b>"}, u"<b>hello</b> -- <b>hello</b>"),
+ 'filter-safe01': ("{{ a }} -- {{ a|safe }}", {"a": "<b>hello</b>"}, "&lt;b&gt;hello&lt;/b&gt; -- <b>hello</b>"),
+ 'filter-safe02': ("{% autoescape off %}{{ a }} -- {{ a|safe }}{% endautoescape %}", {"a": "<b>hello</b>"}, "<b>hello</b> -- <b>hello</b>"),
'filter-safeseq01': ('{{ a|join:", " }} -- {{ a|safeseq|join:", " }}', {"a": ["&", "<"]}, "&amp;, &lt; -- &, <"),
'filter-safeseq02': ('{% autoescape off %}{{ a|join:", " }} -- {{ a|safeseq|join:", " }}{% endautoescape %}', {"a": ["&", "<"]}, "&, < -- &, <"),
- 'filter-removetags01': ('{{ a|removetags:"a b" }} {{ b|removetags:"a b" }}', {"a": "<a>x</a> <p><b>y</b></p>", "b": mark_safe("<a>x</a> <p><b>y</b></p>")}, u"x &lt;p&gt;y&lt;/p&gt; x <p>y</p>"),
- 'filter-removetags02': ('{% autoescape off %}{{ a|removetags:"a b" }} {{ b|removetags:"a b" }}{% endautoescape %}', {"a": "<a>x</a> <p><b>y</b></p>", "b": mark_safe("<a>x</a> <p><b>y</b></p>")}, u"x <p>y</p> x <p>y</p>"),
+ 'filter-removetags01': ('{{ a|removetags:"a b" }} {{ b|removetags:"a b" }}', {"a": "<a>x</a> <p><b>y</b></p>", "b": mark_safe("<a>x</a> <p><b>y</b></p>")}, "x &lt;p&gt;y&lt;/p&gt; x <p>y</p>"),
+ 'filter-removetags02': ('{% autoescape off %}{{ a|removetags:"a b" }} {{ b|removetags:"a b" }}{% endautoescape %}', {"a": "<a>x</a> <p><b>y</b></p>", "b": mark_safe("<a>x</a> <p><b>y</b></p>")}, "x <p>y</p> x <p>y</p>"),
'filter-striptags01': ('{{ a|striptags }} {{ b|striptags }}', {"a": "<a>x</a> <p><b>y</b></p>", "b": mark_safe("<a>x</a> <p><b>y</b></p>")}, "x y x y"),
'filter-striptags02': ('{% autoescape off %}{{ a|striptags }} {{ b|striptags }}{% endautoescape %}', {"a": "<a>x</a> <p><b>y</b></p>", "b": mark_safe("<a>x</a> <p><b>y</b></p>")}, "x y x y"),
diff --git a/tests/regressiontests/templates/parser.py b/tests/regressiontests/templates/parser.py
index 1609c67e22..6c9deee9ff 100644
--- a/tests/regressiontests/templates/parser.py
+++ b/tests/regressiontests/templates/parser.py
@@ -1,6 +1,8 @@
"""
Testing some internals of the template processing. These are *not* examples to be copied in user code.
"""
+from __future__ import unicode_literals
+
from django.template import (TokenParser, FilterExpression, Parser, Variable,
TemplateSyntaxError)
from django.utils.unittest import TestCase
@@ -33,23 +35,23 @@ class ParserTests(TestCase):
self.assertFalse(p.more())
def test_filter_parsing(self):
- c = {"article": {"section": u"News"}}
+ c = {"article": {"section": "News"}}
p = Parser("")
def fe_test(s, val):
self.assertEqual(FilterExpression(s, p).resolve(c), val)
- fe_test("article.section", u"News")
- fe_test("article.section|upper", u"NEWS")
- fe_test(u'"News"', u"News")
- fe_test(u"'News'", u"News")
- fe_test(ur'"Some \"Good\" News"', u'Some "Good" News')
- fe_test(ur'"Some \"Good\" News"', u'Some "Good" News')
- fe_test(ur"'Some \'Bad\' News'", u"Some 'Bad' News")
+ fe_test("article.section", "News")
+ fe_test("article.section|upper", "NEWS")
+ fe_test('"News"', "News")
+ fe_test("'News'", "News")
+ fe_test(r'"Some \"Good\" News"', 'Some "Good" News')
+ fe_test(r'"Some \"Good\" News"', 'Some "Good" News')
+ fe_test(r"'Some \'Bad\' News'", "Some 'Bad' News")
- fe = FilterExpression(ur'"Some \"Good\" News"', p)
+ fe = FilterExpression(r'"Some \"Good\" News"', p)
self.assertEqual(fe.filters, [])
- self.assertEqual(fe.var, u'Some "Good" News')
+ self.assertEqual(fe.var, 'Some "Good" News')
# Filtered variables should reject access of attributes beginning with
# underscores.
@@ -58,10 +60,10 @@ class ParserTests(TestCase):
)
def test_variable_parsing(self):
- c = {"article": {"section": u"News"}}
+ c = {"article": {"section": "News"}}
self.assertEqual(Variable("article.section").resolve(c), "News")
- self.assertEqual(Variable(u'"News"').resolve(c), "News")
- self.assertEqual(Variable(u"'News'").resolve(c), "News")
+ self.assertEqual(Variable('"News"').resolve(c), "News")
+ self.assertEqual(Variable("'News'").resolve(c), "News")
# Translated strings are handled correctly.
self.assertEqual(Variable("_(article.section)").resolve(c), "News")
@@ -70,10 +72,10 @@ class ParserTests(TestCase):
# Escaped quotes work correctly as well.
self.assertEqual(
- Variable(ur'"Some \"Good\" News"').resolve(c), 'Some "Good" News'
+ Variable(r'"Some \"Good\" News"').resolve(c), 'Some "Good" News'
)
self.assertEqual(
- Variable(ur"'Some \'Better\' News'").resolve(c), "Some 'Better' News"
+ Variable(r"'Some \'Better\' News'").resolve(c), "Some 'Better' News"
)
# Variables should reject access of attributes beginning with
diff --git a/tests/regressiontests/templates/tests.py b/tests/regressiontests/templates/tests.py
index 957ad2b9ba..989fd72d94 100644
--- a/tests/regressiontests/templates/tests.py
+++ b/tests/regressiontests/templates/tests.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from django.conf import settings
@@ -147,14 +147,14 @@ class SilentAttrClass(object):
class UTF8Class:
"Class whose __str__ returns non-ASCII data"
def __str__(self):
- return u'ŠĐĆŽćžšđ'.encode('utf-8')
+ return 'ŠĐĆŽćžšđ'.encode('utf-8')
class Templates(unittest.TestCase):
def setUp(self):
self.old_static_url = settings.STATIC_URL
self.old_media_url = settings.MEDIA_URL
- settings.STATIC_URL = u"/static/"
- settings.MEDIA_URL = u"/media/"
+ settings.STATIC_URL = "/static/"
+ settings.MEDIA_URL = "/media/"
def tearDown(self):
settings.STATIC_URL = self.old_static_url
@@ -193,13 +193,13 @@ class Templates(unittest.TestCase):
# UTF-8 bytestrings are permitted.
test_template_sources(b'\xc3\x85ngstr\xc3\xb6m', template_dirs,
- [u'/dir1/Ångström', u'/dir2/Ångström'])
+ ['/dir1/Ångström', '/dir2/Ångström'])
# Unicode strings are permitted.
- test_template_sources(u'Ångström', template_dirs,
- [u'/dir1/Ångström', u'/dir2/Ångström'])
- test_template_sources(u'Ångström', [b'/Stra\xc3\x9fe'], [u'/Straße/Ångström'])
+ test_template_sources('Ångström', template_dirs,
+ ['/dir1/Ångström', '/dir2/Ångström'])
+ test_template_sources('Ångström', [b'/Stra\xc3\x9fe'], ['/Straße/Ångström'])
test_template_sources(b'\xc3\x85ngstr\xc3\xb6m', [b'/Stra\xc3\x9fe'],
- [u'/Straße/Ångström'])
+ ['/Straße/Ångström'])
# Invalid UTF-8 encoding in bytestrings is not. Should raise a
# semi-useful error message.
test_template_sources(b'\xc3\xc3', template_dirs, UnicodeDecodeError)
@@ -684,7 +684,7 @@ class Templates(unittest.TestCase):
# Make sure that any unicode strings are converted to bytestrings
# in the final output.
- 'filter-syntax18': (r'{{ var }}', {'var': UTF8Class()}, u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111'),
+ 'filter-syntax18': (r'{{ var }}', {'var': UTF8Class()}, '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111'),
# Numbers as filter arguments should work
'filter-syntax19': ('{{ var|truncatewords:1 }}', {"var": "hello world"}, "hello ..."),
@@ -1239,11 +1239,11 @@ class Templates(unittest.TestCase):
'i18n02': ('{% load i18n %}{% trans "xxxyyyxxx" %}', {}, "xxxyyyxxx"),
# simple translation of a variable
- 'i18n03': ('{% load i18n %}{% blocktrans %}{{ anton }}{% endblocktrans %}', {'anton': b'\xc3\x85'}, u"Å"),
+ 'i18n03': ('{% load i18n %}{% blocktrans %}{{ anton }}{% endblocktrans %}', {'anton': b'\xc3\x85'}, "Å"),
# simple translation of a variable and filter
- 'i18n04': ('{% load i18n %}{% blocktrans with berta=anton|lower %}{{ berta }}{% endblocktrans %}', {'anton': b'\xc3\x85'}, u'å'),
- 'legacyi18n04': ('{% load i18n %}{% blocktrans with anton|lower as berta %}{{ berta }}{% endblocktrans %}', {'anton': b'\xc3\x85'}, u'å'),
+ 'i18n04': ('{% load i18n %}{% blocktrans with berta=anton|lower %}{{ berta }}{% endblocktrans %}', {'anton': b'\xc3\x85'}, 'å'),
+ 'legacyi18n04': ('{% load i18n %}{% blocktrans with anton|lower as berta %}{{ berta }}{% endblocktrans %}', {'anton': b'\xc3\x85'}, 'å'),
# simple translation of a string with interpolation
'i18n05': ('{% load i18n %}{% blocktrans %}xxx{{ anton }}xxx{% endblocktrans %}', {'anton': 'yyy'}, "xxxyyyxxx"),
@@ -1279,42 +1279,42 @@ class Templates(unittest.TestCase):
# Escaping inside blocktrans and trans works as if it was directly in the
# template.
- 'i18n17': ('{% load i18n %}{% blocktrans with berta=anton|escape %}{{ berta }}{% endblocktrans %}', {'anton': 'α & β'}, u'α &amp; β'),
- 'i18n18': ('{% load i18n %}{% blocktrans with berta=anton|force_escape %}{{ berta }}{% endblocktrans %}', {'anton': 'α & β'}, u'α &amp; β'),
- 'i18n19': ('{% load i18n %}{% blocktrans %}{{ andrew }}{% endblocktrans %}', {'andrew': 'a & b'}, u'a &amp; b'),
- 'i18n20': ('{% load i18n %}{% trans andrew %}', {'andrew': 'a & b'}, u'a &amp; b'),
- 'i18n21': ('{% load i18n %}{% blocktrans %}{{ andrew }}{% endblocktrans %}', {'andrew': mark_safe('a & b')}, u'a & b'),
- 'i18n22': ('{% load i18n %}{% trans andrew %}', {'andrew': mark_safe('a & b')}, u'a & b'),
- 'legacyi18n17': ('{% load i18n %}{% blocktrans with anton|escape as berta %}{{ berta }}{% endblocktrans %}', {'anton': 'α & β'}, u'α &amp; β'),
- 'legacyi18n18': ('{% load i18n %}{% blocktrans with anton|force_escape as berta %}{{ berta }}{% endblocktrans %}', {'anton': 'α & β'}, u'α &amp; β'),
+ 'i18n17': ('{% load i18n %}{% blocktrans with berta=anton|escape %}{{ berta }}{% endblocktrans %}', {'anton': 'α & β'}, 'α &amp; β'),
+ 'i18n18': ('{% load i18n %}{% blocktrans with berta=anton|force_escape %}{{ berta }}{% endblocktrans %}', {'anton': 'α & β'}, 'α &amp; β'),
+ 'i18n19': ('{% load i18n %}{% blocktrans %}{{ andrew }}{% endblocktrans %}', {'andrew': 'a & b'}, 'a &amp; b'),
+ 'i18n20': ('{% load i18n %}{% trans andrew %}', {'andrew': 'a & b'}, 'a &amp; b'),
+ 'i18n21': ('{% load i18n %}{% blocktrans %}{{ andrew }}{% endblocktrans %}', {'andrew': mark_safe('a & b')}, 'a & b'),
+ 'i18n22': ('{% load i18n %}{% trans andrew %}', {'andrew': mark_safe('a & b')}, 'a & b'),
+ 'legacyi18n17': ('{% load i18n %}{% blocktrans with anton|escape as berta %}{{ berta }}{% endblocktrans %}', {'anton': 'α & β'}, 'α &amp; β'),
+ 'legacyi18n18': ('{% load i18n %}{% blocktrans with anton|force_escape as berta %}{{ berta }}{% endblocktrans %}', {'anton': 'α & β'}, 'α &amp; β'),
# Use filters with the {% trans %} tag, #5972
- 'i18n23': ('{% load i18n %}{% trans "Page not found"|capfirst|slice:"6:" %}', {'LANGUAGE_CODE': 'de'}, u'nicht gefunden'),
- 'i18n24': ("{% load i18n %}{% trans 'Page not found'|upper %}", {'LANGUAGE_CODE': 'de'}, u'SEITE NICHT GEFUNDEN'),
- 'i18n25': ('{% load i18n %}{% trans somevar|upper %}', {'somevar': 'Page not found', 'LANGUAGE_CODE': 'de'}, u'SEITE NICHT GEFUNDEN'),
+ 'i18n23': ('{% load i18n %}{% trans "Page not found"|capfirst|slice:"6:" %}', {'LANGUAGE_CODE': 'de'}, 'nicht gefunden'),
+ 'i18n24': ("{% load i18n %}{% trans 'Page not found'|upper %}", {'LANGUAGE_CODE': 'de'}, 'SEITE NICHT GEFUNDEN'),
+ 'i18n25': ('{% load i18n %}{% trans somevar|upper %}', {'somevar': 'Page not found', 'LANGUAGE_CODE': 'de'}, 'SEITE NICHT GEFUNDEN'),
# translation of plural form with extra field in singular form (#13568)
'i18n26': ('{% load i18n %}{% blocktrans with extra_field=myextra_field count counter=number %}singular {{ extra_field }}{% plural %}plural{% endblocktrans %}', {'number': 1, 'myextra_field': 'test'}, "singular test"),
'legacyi18n26': ('{% load i18n %}{% blocktrans with myextra_field as extra_field count number as counter %}singular {{ extra_field }}{% plural %}plural{% endblocktrans %}', {'number': 1, 'myextra_field': 'test'}, "singular test"),
# translation of singular form in russian (#14126)
- 'i18n27': ('{% load i18n %}{% blocktrans count counter=number %}{{ counter }} result{% plural %}{{ counter }} results{% endblocktrans %}', {'number': 1, 'LANGUAGE_CODE': 'ru'}, u'1 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442'),
- 'legacyi18n27': ('{% load i18n %}{% blocktrans count number as counter %}{{ counter }} result{% plural %}{{ counter }} results{% endblocktrans %}', {'number': 1, 'LANGUAGE_CODE': 'ru'}, u'1 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442'),
+ 'i18n27': ('{% load i18n %}{% blocktrans count counter=number %}{{ counter }} result{% plural %}{{ counter }} results{% endblocktrans %}', {'number': 1, 'LANGUAGE_CODE': 'ru'}, '1 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442'),
+ 'legacyi18n27': ('{% load i18n %}{% blocktrans count number as counter %}{{ counter }} result{% plural %}{{ counter }} results{% endblocktrans %}', {'number': 1, 'LANGUAGE_CODE': 'ru'}, '1 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442'),
# simple translation of multiple variables
- 'i18n28': ('{% load i18n %}{% blocktrans with a=anton b=berta %}{{ a }} + {{ b }}{% endblocktrans %}', {'anton': 'α', 'berta': 'β'}, u'α + β'),
- 'legacyi18n28': ('{% load i18n %}{% blocktrans with anton as a and berta as b %}{{ a }} + {{ b }}{% endblocktrans %}', {'anton': 'α', 'berta': 'β'}, u'α + β'),
+ 'i18n28': ('{% load i18n %}{% blocktrans with a=anton b=berta %}{{ a }} + {{ b }}{% endblocktrans %}', {'anton': 'α', 'berta': 'β'}, 'α + β'),
+ 'legacyi18n28': ('{% load i18n %}{% blocktrans with anton as a and berta as b %}{{ a }} + {{ b }}{% endblocktrans %}', {'anton': 'α', 'berta': 'β'}, 'α + β'),
# retrieving language information
'i18n28_2': ('{% load i18n %}{% get_language_info for "de" as l %}{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}', {}, 'de: German/Deutsch bidi=False'),
'i18n29': ('{% load i18n %}{% get_language_info for LANGUAGE_CODE as l %}{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}', {'LANGUAGE_CODE': 'fi'}, 'fi: Finnish/suomi bidi=False'),
- 'i18n30': ('{% load i18n %}{% get_language_info_list for langcodes as langs %}{% for l in langs %}{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}', {'langcodes': ['it', 'no']}, u'it: Italian/italiano bidi=False; no: Norwegian/Norsk bidi=False; '),
- 'i18n31': ('{% load i18n %}{% get_language_info_list for langcodes as langs %}{% for l in langs %}{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}', {'langcodes': (('sl', 'Slovenian'), ('fa', 'Persian'))}, u'sl: Slovenian/Sloven\u0161\u010dina bidi=False; fa: Persian/\u0641\u0627\u0631\u0633\u06cc bidi=True; '),
- 'i18n32': ('{% load i18n %}{{ "hu"|language_name }} {{ "hu"|language_name_local }} {{ "hu"|language_bidi }}', {}, u'Hungarian Magyar False'),
- 'i18n33': ('{% load i18n %}{{ langcode|language_name }} {{ langcode|language_name_local }} {{ langcode|language_bidi }}', {'langcode': 'nl'}, u'Dutch Nederlands False'),
+ 'i18n30': ('{% load i18n %}{% get_language_info_list for langcodes as langs %}{% for l in langs %}{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}', {'langcodes': ['it', 'no']}, 'it: Italian/italiano bidi=False; no: Norwegian/Norsk bidi=False; '),
+ 'i18n31': ('{% load i18n %}{% get_language_info_list for langcodes as langs %}{% for l in langs %}{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}', {'langcodes': (('sl', 'Slovenian'), ('fa', 'Persian'))}, 'sl: Slovenian/Sloven\u0161\u010dina bidi=False; fa: Persian/\u0641\u0627\u0631\u0633\u06cc bidi=True; '),
+ 'i18n32': ('{% load i18n %}{{ "hu"|language_name }} {{ "hu"|language_name_local }} {{ "hu"|language_bidi }}', {}, 'Hungarian Magyar False'),
+ 'i18n33': ('{% load i18n %}{{ langcode|language_name }} {{ langcode|language_name_local }} {{ langcode|language_bidi }}', {'langcode': 'nl'}, 'Dutch Nederlands False'),
# blocktrans handling of variables which are not in the context.
- 'i18n34': ('{% load i18n %}{% blocktrans %}{{ missing }}{% endblocktrans %}', {}, u''),
+ 'i18n34': ('{% load i18n %}{% blocktrans %}{{ missing }}{% endblocktrans %}', {}, ''),
# trans tag with as var
'i18n35': ('{% load i18n %}{% trans "Page not found" as page_not_found %}{{ page_not_found }}', {'LANGUAGE_CODE': 'de'}, "Seite nicht gefunden"),
@@ -1498,11 +1498,11 @@ class Templates(unittest.TestCase):
'url02c': ("{% url 'regressiontests.templates.views.client_action' client.id 'update' %}", {'client': {'id': 1}}, '/url_tag/client/1/update/'),
'url03': ('{% url "regressiontests.templates.views.index" %}', {}, '/url_tag/'),
'url04': ('{% url "named.client" client.id %}', {'client': {'id': 1}}, '/url_tag/named-client/1/'),
- 'url05': (u'{% url "метка_оператора" v %}', {'v': u'Ω'}, '/url_tag/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'),
- 'url06': (u'{% url "метка_оператора_2" tag=v %}', {'v': u'Ω'}, '/url_tag/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'),
- 'url07': (u'{% url "regressiontests.templates.views.client2" tag=v %}', {'v': u'Ω'}, '/url_tag/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'),
- 'url08': (u'{% url "метка_оператора" v %}', {'v': 'Ω'}, '/url_tag/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'),
- 'url09': (u'{% url "метка_оператора_2" tag=v %}', {'v': 'Ω'}, '/url_tag/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'),
+ 'url05': ('{% url "метка_оператора" v %}', {'v': 'Ω'}, '/url_tag/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'),
+ 'url06': ('{% url "метка_оператора_2" tag=v %}', {'v': 'Ω'}, '/url_tag/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'),
+ 'url07': ('{% url "regressiontests.templates.views.client2" tag=v %}', {'v': 'Ω'}, '/url_tag/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'),
+ 'url08': ('{% url "метка_оператора" v %}', {'v': 'Ω'}, '/url_tag/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'),
+ 'url09': ('{% url "метка_оператора_2" tag=v %}', {'v': 'Ω'}, '/url_tag/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'),
'url10': ('{% url "regressiontests.templates.views.client_action" id=client.id action="two words" %}', {'client': {'id': 1}}, '/url_tag/client/1/two%20words/'),
'url11': ('{% url "regressiontests.templates.views.client_action" id=client.id action="==" %}', {'client': {'id': 1}}, '/url_tag/client/1/==/'),
'url12': ('{% url "regressiontests.templates.views.client_action" id=client.id action="," %}', {'client': {'id': 1}}, '/url_tag/client/1/,/'),
@@ -1577,7 +1577,7 @@ class Templates(unittest.TestCase):
# Strings (ASCII or unicode) already marked as "safe" are not
# auto-escaped
'autoescape-tag06': ("{{ first }}", {"first": mark_safe("<b>first</b>")}, "<b>first</b>"),
- 'autoescape-tag07': ("{% autoescape on %}{{ first }}{% endautoescape %}", {"first": mark_safe(u"<b>Apple</b>")}, u"<b>Apple</b>"),
+ 'autoescape-tag07': ("{% autoescape on %}{{ first }}{% endautoescape %}", {"first": mark_safe("<b>Apple</b>")}, "<b>Apple</b>"),
# Literal string arguments to filters, if used in the result, are
# safe.
diff --git a/tests/regressiontests/templates/unicode.py b/tests/regressiontests/templates/unicode.py
index 0e0cefeb8e..2c41176b01 100644
--- a/tests/regressiontests/templates/unicode.py
+++ b/tests/regressiontests/templates/unicode.py
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
from django.template import Template, TemplateEncodingError, Context
from django.utils.safestring import SafeData
from django.utils.unittest import TestCase
@@ -7,7 +9,7 @@ from django.utils.unittest import TestCase
class UnicodeTests(TestCase):
def test_template(self):
# Templates can be created from unicode strings.
- t1 = Template(u'ŠĐĆŽćžšđ {{ var }}')
+ t1 = Template('ŠĐĆŽćžšđ {{ var }}')
# Templates can also be created from bytestrings. These are assumed to
# be encoded using UTF-8.
s = b'\xc5\xa0\xc4\x90\xc4\x86\xc5\xbd\xc4\x87\xc5\xbe\xc5\xa1\xc4\x91 {{ var }}'
@@ -17,9 +19,9 @@ class UnicodeTests(TestCase):
# Contexts can be constructed from unicode or UTF-8 bytestrings.
c1 = Context({b"var": b"foo"})
- c2 = Context({u"var": b"foo"})
- c3 = Context({b"var": u"Đđ"})
- c4 = Context({u"var": b"\xc4\x90\xc4\x91"})
+ c2 = Context({"var": b"foo"})
+ c3 = Context({b"var": "Đđ"})
+ c4 = Context({"var": b"\xc4\x90\xc4\x91"})
# Since both templates and all four contexts represent the same thing,
# they all render the same (and are returned as unicode objects and
diff --git a/tests/regressiontests/templates/urls.py b/tests/regressiontests/templates/urls.py
index b977698350..fe7f9c1f30 100644
--- a/tests/regressiontests/templates/urls.py
+++ b/tests/regressiontests/templates/urls.py
@@ -1,5 +1,5 @@
# coding: utf-8
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from django.conf.urls import patterns, url
from . import views
@@ -15,6 +15,6 @@ urlpatterns = patterns('',
url(r'^named-client/(\d+)/$', views.client2, name="named.client"),
# Unicode strings are permitted everywhere.
- url(ur'^Юникод/(\w+)/$', views.client2, name=u"метка_оператора"),
- url(ur'^Юникод/(?P<tag>\S+)/$', 'regressiontests.templates.views.client2', name=u"метка_оператора_2"),
+ url(r'^Юникод/(\w+)/$', views.client2, name="метка_оператора"),
+ url(r'^Юникод/(?P<tag>\S+)/$', 'regressiontests.templates.views.client2', name="метка_оператора_2"),
)
diff --git a/tests/regressiontests/test_client_regress/tests.py b/tests/regressiontests/test_client_regress/tests.py
index ece487a211..59f8f423dd 100644
--- a/tests/regressiontests/test_client_regress/tests.py
+++ b/tests/regressiontests/test_client_regress/tests.py
@@ -2,6 +2,8 @@
"""
Regression tests for the Test Client, especially the customized assertions.
"""
+from __future__ import unicode_literals
+
import os
from django.conf import settings
@@ -12,7 +14,7 @@ from django.template import (TemplateDoesNotExist, TemplateSyntaxError,
import django.template.context
from django.test import Client, TestCase
from django.test.client import encode_file, RequestFactory
-from django.test.utils import ContextList, override_settings
+from django.test.utils import ContextList, override_settings, str_prefix
from django.template.response import SimpleTemplateResponse
from django.http import HttpResponse
@@ -117,14 +119,14 @@ class AssertContainsTests(TestCase):
"Unicode characters can be found in template context"
#Regression test for #10183
r = self.client.get('/test_client_regress/check_unicode/')
- self.assertContains(r, u'さかき')
+ self.assertContains(r, 'さかき')
self.assertContains(r, b'\xe5\xb3\xa0'.decode('utf-8'))
def test_unicode_not_contains(self):
"Unicode characters can be searched for, and not found in template context"
#Regression test for #10183
r = self.client.get('/test_client_regress/check_unicode/')
- self.assertNotContains(r, u'はたけ')
+ self.assertNotContains(r, 'はたけ')
self.assertNotContains(r, b'\xe3\x81\xaf\xe3\x81\x9f\xe3\x81\x91'.decode('utf-8'))
def test_assert_contains_renders_template_response(self):
@@ -488,11 +490,11 @@ class AssertFormErrorTests(TestCase):
try:
self.assertFormError(response, 'form', 'email', 'Some error.')
except AssertionError as e:
- self.assertIn("The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [u'Enter a valid e-mail address.'])", str(e))
+ self.assertIn(str_prefix("The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [%(_)s'Enter a valid e-mail address.'])"), str(e))
try:
self.assertFormError(response, 'form', 'email', 'Some error.', msg_prefix='abc')
except AssertionError as e:
- self.assertIn("abc: The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [u'Enter a valid e-mail address.'])", str(e))
+ self.assertIn(str_prefix("abc: The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [%(_)s'Enter a valid e-mail address.'])"), str(e))
def test_unknown_nonfield_error(self):
"""
@@ -784,7 +786,7 @@ class RequestMethodStringDataTests(TestCase):
def test_post(self):
"Request a view with string data via request method POST"
# Regression test for #11371
- data = u'{"test": "json"}'
+ data = '{"test": "json"}'
response = self.client.post('/test_client_regress/request_methods/', data=data, content_type='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'request method: POST')
@@ -792,7 +794,7 @@ class RequestMethodStringDataTests(TestCase):
def test_put(self):
"Request a view with string data via request method PUT"
# Regression test for #11371
- data = u'{"test": "json"}'
+ data = '{"test": "json"}'
response = self.client.put('/test_client_regress/request_methods/', data=data, content_type='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'request method: PUT')
@@ -853,7 +855,7 @@ class UnicodePayloadTests(TestCase):
def test_simple_unicode_payload(self):
"A simple ASCII-only unicode JSON document can be POSTed"
# Regression test for #10571
- json = u'{"english": "mountain pass"}'
+ json = '{"english": "mountain pass"}'
response = self.client.post("/test_client_regress/parse_unicode_json/", json,
content_type="application/json")
self.assertEqual(response.content, json)
@@ -861,7 +863,7 @@ class UnicodePayloadTests(TestCase):
def test_unicode_payload_utf8(self):
"A non-ASCII unicode data encoded as UTF-8 can be POSTed"
# Regression test for #10571
- json = u'{"dog": "собака"}'
+ json = '{"dog": "собака"}'
response = self.client.post("/test_client_regress/parse_unicode_json/", json,
content_type="application/json; charset=utf-8")
self.assertEqual(response.content, json.encode('utf-8'))
@@ -869,7 +871,7 @@ class UnicodePayloadTests(TestCase):
def test_unicode_payload_utf16(self):
"A non-ASCII unicode data encoded as UTF-16 can be POSTed"
# Regression test for #10571
- json = u'{"dog": "собака"}'
+ json = '{"dog": "собака"}'
response = self.client.post("/test_client_regress/parse_unicode_json/", json,
content_type="application/json; charset=utf-16")
self.assertEqual(response.content, json.encode('utf-16'))
@@ -877,7 +879,7 @@ class UnicodePayloadTests(TestCase):
def test_unicode_payload_non_utf(self):
"A non-ASCII unicode data as a non-UTF based encoding can be POSTed"
#Regression test for #10571
- json = u'{"dog": "собака"}'
+ json = '{"dog": "собака"}'
response = self.client.post("/test_client_regress/parse_unicode_json/", json,
content_type="application/json; charset=koi8-r")
self.assertEqual(response.content, json.encode('koi8-r'))
diff --git a/tests/regressiontests/test_utils/tests.py b/tests/regressiontests/test_utils/tests.py
index a277bc999b..46479ebe8b 100644
--- a/tests/regressiontests/test_utils/tests.py
+++ b/tests/regressiontests/test_utils/tests.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from django.forms import EmailField, IntegerField
from django.http import HttpResponse
@@ -475,16 +475,16 @@ class AssertRaisesMsgTest(SimpleTestCase):
class AssertFieldOutputTests(SimpleTestCase):
def test_assert_field_output(self):
- error_invalid = [u'Enter a valid e-mail address.']
+ error_invalid = ['Enter a valid e-mail address.']
self.assertFieldOutput(EmailField, {'a@a.com': 'a@a.com'}, {'aaa': error_invalid})
- self.assertRaises(AssertionError, self.assertFieldOutput, EmailField, {'a@a.com': 'a@a.com'}, {'aaa': error_invalid + [u'Another error']})
+ self.assertRaises(AssertionError, self.assertFieldOutput, EmailField, {'a@a.com': 'a@a.com'}, {'aaa': error_invalid + ['Another error']})
self.assertRaises(AssertionError, self.assertFieldOutput, EmailField, {'a@a.com': 'Wrong output'}, {'aaa': error_invalid})
- self.assertRaises(AssertionError, self.assertFieldOutput, EmailField, {'a@a.com': 'a@a.com'}, {'aaa': [u'Come on, gimme some well formatted data, dude.']})
+ self.assertRaises(AssertionError, self.assertFieldOutput, EmailField, {'a@a.com': 'a@a.com'}, {'aaa': ['Come on, gimme some well formatted data, dude.']})
def test_custom_required_message(self):
class MyCustomField(IntegerField):
default_error_messages = {
- 'required': u'This is really required.',
+ 'required': 'This is really required.',
}
self.assertFieldOutput(MyCustomField, {}, {}, empty_value=None)
diff --git a/tests/regressiontests/text/tests.py b/tests/regressiontests/text/tests.py
index e4c4c00938..e61c14d103 100644
--- a/tests/regressiontests/text/tests.py
+++ b/tests/regressiontests/text/tests.py
@@ -1,4 +1,5 @@
# coding: utf-8
+from __future__ import unicode_literals
from django.test import TestCase
from django.utils.encoding import iri_to_uri
@@ -14,72 +15,72 @@ class TextTests(TestCase):
"""
def test_get_text_list(self):
- self.assertEqual(get_text_list(['a', 'b', 'c', 'd']), u'a, b, c or d')
- self.assertEqual(get_text_list(['a', 'b', 'c'], 'and'), u'a, b and c')
- self.assertEqual(get_text_list(['a', 'b'], 'and'), u'a and b')
- self.assertEqual(get_text_list(['a']), u'a')
- self.assertEqual(get_text_list([]), u'')
+ self.assertEqual(get_text_list(['a', 'b', 'c', 'd']), 'a, b, c or d')
+ self.assertEqual(get_text_list(['a', 'b', 'c'], 'and'), 'a, b and c')
+ self.assertEqual(get_text_list(['a', 'b'], 'and'), 'a and b')
+ self.assertEqual(get_text_list(['a']), 'a')
+ self.assertEqual(get_text_list([]), '')
with override('ar'):
- self.assertEqual(get_text_list(['a', 'b', 'c']), u"a، b أو c")
+ self.assertEqual(get_text_list(['a', 'b', 'c']), "a، b أو c")
def test_smart_split(self):
self.assertEqual(list(smart_split(r'''This is "a person" test.''')),
- [u'This', u'is', u'"a person"', u'test.'])
+ ['This', 'is', '"a person"', 'test.'])
self.assertEqual(list(smart_split(r'''This is "a person's" test.'''))[2],
- u'"a person\'s"')
+ '"a person\'s"')
self.assertEqual(list(smart_split(r'''This is "a person\"s" test.'''))[2],
- u'"a person\\"s"')
+ '"a person\\"s"')
- self.assertEqual(list(smart_split('''"a 'one''')), [u'"a', u"'one"])
+ self.assertEqual(list(smart_split('''"a 'one''')), ['"a', "'one"])
self.assertEqual(list(smart_split(r'''all friends' tests'''))[1],
"friends'")
- self.assertEqual(list(smart_split(u'url search_page words="something else"')),
- [u'url', u'search_page', u'words="something else"'])
+ self.assertEqual(list(smart_split('url search_page words="something else"')),
+ ['url', 'search_page', 'words="something else"'])
- self.assertEqual(list(smart_split(u"url search_page words='something else'")),
- [u'url', u'search_page', u"words='something else'"])
+ self.assertEqual(list(smart_split("url search_page words='something else'")),
+ ['url', 'search_page', "words='something else'"])
- self.assertEqual(list(smart_split(u'url search_page words "something else"')),
- [u'url', u'search_page', u'words', u'"something else"'])
+ self.assertEqual(list(smart_split('url search_page words "something else"')),
+ ['url', 'search_page', 'words', '"something else"'])
- self.assertEqual(list(smart_split(u'url search_page words-"something else"')),
- [u'url', u'search_page', u'words-"something else"'])
+ self.assertEqual(list(smart_split('url search_page words-"something else"')),
+ ['url', 'search_page', 'words-"something else"'])
- self.assertEqual(list(smart_split(u'url search_page words=hello')),
- [u'url', u'search_page', u'words=hello'])
+ self.assertEqual(list(smart_split('url search_page words=hello')),
+ ['url', 'search_page', 'words=hello'])
- self.assertEqual(list(smart_split(u'url search_page words="something else')),
- [u'url', u'search_page', u'words="something', u'else'])
+ self.assertEqual(list(smart_split('url search_page words="something else')),
+ ['url', 'search_page', 'words="something', 'else'])
self.assertEqual(list(smart_split("cut:','|cut:' '")),
- [u"cut:','|cut:' '"])
+ ["cut:','|cut:' '"])
def test_urlquote(self):
- self.assertEqual(urlquote(u'Paris & Orl\xe9ans'),
- u'Paris%20%26%20Orl%C3%A9ans')
- self.assertEqual(urlquote(u'Paris & Orl\xe9ans', safe="&"),
- u'Paris%20&%20Orl%C3%A9ans')
+ self.assertEqual(urlquote('Paris & Orl\xe9ans'),
+ 'Paris%20%26%20Orl%C3%A9ans')
+ self.assertEqual(urlquote('Paris & Orl\xe9ans', safe="&"),
+ 'Paris%20&%20Orl%C3%A9ans')
self.assertEqual(
- urlunquote(u'Paris%20%26%20Orl%C3%A9ans'),
- u'Paris & Orl\xe9ans')
+ urlunquote('Paris%20%26%20Orl%C3%A9ans'),
+ 'Paris & Orl\xe9ans')
self.assertEqual(
- urlunquote(u'Paris%20&%20Orl%C3%A9ans'),
- u'Paris & Orl\xe9ans')
- self.assertEqual(urlquote_plus(u'Paris & Orl\xe9ans'),
- u'Paris+%26+Orl%C3%A9ans')
- self.assertEqual(urlquote_plus(u'Paris & Orl\xe9ans', safe="&"),
- u'Paris+&+Orl%C3%A9ans')
+ urlunquote('Paris%20&%20Orl%C3%A9ans'),
+ 'Paris & Orl\xe9ans')
+ self.assertEqual(urlquote_plus('Paris & Orl\xe9ans'),
+ 'Paris+%26+Orl%C3%A9ans')
+ self.assertEqual(urlquote_plus('Paris & Orl\xe9ans', safe="&"),
+ 'Paris+&+Orl%C3%A9ans')
self.assertEqual(
- urlunquote_plus(u'Paris+%26+Orl%C3%A9ans'),
- u'Paris & Orl\xe9ans')
+ urlunquote_plus('Paris+%26+Orl%C3%A9ans'),
+ 'Paris & Orl\xe9ans')
self.assertEqual(
- urlunquote_plus(u'Paris+&+Orl%C3%A9ans'),
- u'Paris & Orl\xe9ans')
+ urlunquote_plus('Paris+&+Orl%C3%A9ans'),
+ 'Paris & Orl\xe9ans')
def test_cookie_date(self):
t = 1167616461.0
@@ -90,15 +91,15 @@ class TextTests(TestCase):
self.assertEqual(http_date(t), 'Mon, 01 Jan 2007 01:54:21 GMT')
def test_iri_to_uri(self):
- self.assertEqual(iri_to_uri(u'red%09ros\xe9#red'),
+ self.assertEqual(iri_to_uri('red%09ros\xe9#red'),
'red%09ros%C3%A9#red')
- self.assertEqual(iri_to_uri(u'/blog/for/J\xfcrgen M\xfcnster/'),
+ self.assertEqual(iri_to_uri('/blog/for/J\xfcrgen M\xfcnster/'),
'/blog/for/J%C3%BCrgen%20M%C3%BCnster/')
- self.assertEqual(iri_to_uri(u'locations/%s' % urlquote_plus(u'Paris & Orl\xe9ans')),
+ self.assertEqual(iri_to_uri('locations/%s' % urlquote_plus('Paris & Orl\xe9ans')),
'locations/Paris+%26+Orl%C3%A9ans')
def test_iri_to_uri_idempotent(self):
- self.assertEqual(iri_to_uri(iri_to_uri(u'red%09ros\xe9#red')),
+ self.assertEqual(iri_to_uri(iri_to_uri('red%09ros\xe9#red')),
'red%09ros%C3%A9#red')
diff --git a/tests/regressiontests/utils/dateformat.py b/tests/regressiontests/utils/dateformat.py
index c1910b0f33..0f18bb2a4d 100644
--- a/tests/regressiontests/utils/dateformat.py
+++ b/tests/regressiontests/utils/dateformat.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from datetime import datetime, date
import os
import time
@@ -58,57 +60,57 @@ class DateFormatTests(unittest.TestCase):
def test_epoch(self):
udt = datetime(1970, 1, 1, tzinfo=utc)
- self.assertEqual(format(udt, 'U'), u'0')
+ self.assertEqual(format(udt, 'U'), '0')
def test_empty_format(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
- self.assertEqual(dateformat.format(my_birthday, ''), u'')
+ self.assertEqual(dateformat.format(my_birthday, ''), '')
def test_am_pm(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
- self.assertEqual(dateformat.format(my_birthday, 'a'), u'p.m.')
+ self.assertEqual(dateformat.format(my_birthday, 'a'), 'p.m.')
def test_date_formats(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
timestamp = datetime(2008, 5, 19, 11, 45, 23, 123456)
- self.assertEqual(dateformat.format(my_birthday, 'A'), u'PM')
- self.assertEqual(dateformat.format(timestamp, 'c'), u'2008-05-19T11:45:23.123456')
- self.assertEqual(dateformat.format(my_birthday, 'd'), u'08')
- self.assertEqual(dateformat.format(my_birthday, 'j'), u'8')
- self.assertEqual(dateformat.format(my_birthday, 'l'), u'Sunday')
- self.assertEqual(dateformat.format(my_birthday, 'L'), u'False')
- self.assertEqual(dateformat.format(my_birthday, 'm'), u'07')
- self.assertEqual(dateformat.format(my_birthday, 'M'), u'Jul')
- self.assertEqual(dateformat.format(my_birthday, 'b'), u'jul')
- self.assertEqual(dateformat.format(my_birthday, 'n'), u'7')
- self.assertEqual(dateformat.format(my_birthday, 'N'), u'July')
+ self.assertEqual(dateformat.format(my_birthday, 'A'), 'PM')
+ self.assertEqual(dateformat.format(timestamp, 'c'), '2008-05-19T11:45:23.123456')
+ self.assertEqual(dateformat.format(my_birthday, 'd'), '08')
+ self.assertEqual(dateformat.format(my_birthday, 'j'), '8')
+ self.assertEqual(dateformat.format(my_birthday, 'l'), 'Sunday')
+ self.assertEqual(dateformat.format(my_birthday, 'L'), 'False')
+ self.assertEqual(dateformat.format(my_birthday, 'm'), '07')
+ self.assertEqual(dateformat.format(my_birthday, 'M'), 'Jul')
+ self.assertEqual(dateformat.format(my_birthday, 'b'), 'jul')
+ self.assertEqual(dateformat.format(my_birthday, 'n'), '7')
+ self.assertEqual(dateformat.format(my_birthday, 'N'), 'July')
def test_time_formats(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
- self.assertEqual(dateformat.format(my_birthday, 'P'), u'10 p.m.')
- self.assertEqual(dateformat.format(my_birthday, 's'), u'00')
- self.assertEqual(dateformat.format(my_birthday, 'S'), u'th')
- self.assertEqual(dateformat.format(my_birthday, 't'), u'31')
- self.assertEqual(dateformat.format(my_birthday, 'w'), u'0')
- self.assertEqual(dateformat.format(my_birthday, 'W'), u'27')
- self.assertEqual(dateformat.format(my_birthday, 'y'), u'79')
- self.assertEqual(dateformat.format(my_birthday, 'Y'), u'1979')
- self.assertEqual(dateformat.format(my_birthday, 'z'), u'189')
+ self.assertEqual(dateformat.format(my_birthday, 'P'), '10 p.m.')
+ self.assertEqual(dateformat.format(my_birthday, 's'), '00')
+ self.assertEqual(dateformat.format(my_birthday, 'S'), 'th')
+ self.assertEqual(dateformat.format(my_birthday, 't'), '31')
+ self.assertEqual(dateformat.format(my_birthday, 'w'), '0')
+ self.assertEqual(dateformat.format(my_birthday, 'W'), '27')
+ self.assertEqual(dateformat.format(my_birthday, 'y'), '79')
+ self.assertEqual(dateformat.format(my_birthday, 'Y'), '1979')
+ self.assertEqual(dateformat.format(my_birthday, 'z'), '189')
def test_dateformat(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
- self.assertEqual(dateformat.format(my_birthday, r'Y z \C\E\T'), u'1979 189 CET')
+ self.assertEqual(dateformat.format(my_birthday, r'Y z \C\E\T'), '1979 189 CET')
- self.assertEqual(dateformat.format(my_birthday, r'jS \o\f F'), u'8th of July')
+ self.assertEqual(dateformat.format(my_birthday, r'jS \o\f F'), '8th of July')
def test_futuredates(self):
the_future = datetime(2100, 10, 25, 0, 00)
- self.assertEqual(dateformat.format(the_future, r'Y'), u'2100')
+ self.assertEqual(dateformat.format(the_future, r'Y'), '2100')
def test_timezones(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
@@ -117,19 +119,19 @@ class DateFormatTests(unittest.TestCase):
timestamp = datetime(2008, 5, 19, 11, 45, 23, 123456)
if self.tz_tests:
- self.assertEqual(dateformat.format(my_birthday, 'O'), u'+0100')
- self.assertEqual(dateformat.format(my_birthday, 'r'), u'Sun, 8 Jul 1979 22:00:00 +0100')
- self.assertEqual(dateformat.format(my_birthday, 'T'), u'CET')
- self.assertEqual(dateformat.format(my_birthday, 'U'), u'300315600')
- self.assertEqual(dateformat.format(timestamp, 'u'), u'123456')
- self.assertEqual(dateformat.format(my_birthday, 'Z'), u'3600')
- self.assertEqual(dateformat.format(summertime, 'I'), u'1')
- self.assertEqual(dateformat.format(summertime, 'O'), u'+0200')
- self.assertEqual(dateformat.format(wintertime, 'I'), u'0')
- self.assertEqual(dateformat.format(wintertime, 'O'), u'+0100')
+ self.assertEqual(dateformat.format(my_birthday, 'O'), '+0100')
+ self.assertEqual(dateformat.format(my_birthday, 'r'), 'Sun, 8 Jul 1979 22:00:00 +0100')
+ self.assertEqual(dateformat.format(my_birthday, 'T'), 'CET')
+ self.assertEqual(dateformat.format(my_birthday, 'U'), '300315600')
+ self.assertEqual(dateformat.format(timestamp, 'u'), '123456')
+ self.assertEqual(dateformat.format(my_birthday, 'Z'), '3600')
+ self.assertEqual(dateformat.format(summertime, 'I'), '1')
+ self.assertEqual(dateformat.format(summertime, 'O'), '+0200')
+ self.assertEqual(dateformat.format(wintertime, 'I'), '0')
+ self.assertEqual(dateformat.format(wintertime, 'O'), '+0100')
# Ticket #16924 -- We don't need timezone support to test this
# 3h30m to the west of UTC
tz = FixedOffset(-3*60 - 30)
dt = datetime(2009, 5, 16, 5, 30, 30, tzinfo=tz)
- self.assertEqual(dateformat.format(dt, 'O'), u'-0330')
+ self.assertEqual(dateformat.format(dt, 'O'), '-0330')
diff --git a/tests/regressiontests/utils/feedgenerator.py b/tests/regressiontests/utils/feedgenerator.py
index 4f1d07852c..b646a5997d 100644
--- a/tests/regressiontests/utils/feedgenerator.py
+++ b/tests/regressiontests/utils/feedgenerator.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import datetime
from django.utils import feedgenerator, tzinfo, unittest
@@ -13,7 +15,7 @@ class FeedgeneratorTest(unittest.TestCase):
"""
self.assertEqual(
feedgenerator.get_tag_uri('http://example.org/foo/bar#headline', datetime.date(2004, 10, 25)),
- u'tag:example.org,2004-10-25:/foo/bar/headline')
+ 'tag:example.org,2004-10-25:/foo/bar/headline')
def test_get_tag_uri_with_port(self):
"""
@@ -22,7 +24,7 @@ class FeedgeneratorTest(unittest.TestCase):
"""
self.assertEqual(
feedgenerator.get_tag_uri('http://www.example.org:8000/2008/11/14/django#headline', datetime.datetime(2008, 11, 14, 13, 37, 0)),
- u'tag:www.example.org,2008-11-14:/2008/11/14/django/headline')
+ 'tag:www.example.org,2008-11-14:/2008/11/14/django/headline')
def test_rfc2822_date(self):
"""
diff --git a/tests/regressiontests/utils/html.py b/tests/regressiontests/utils/html.py
index d8b9bde8bf..434873b9e0 100644
--- a/tests/regressiontests/utils/html.py
+++ b/tests/regressiontests/utils/html.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import unittest
from django.utils import html
@@ -113,11 +115,11 @@ class TestUtilsHtml(unittest.TestCase):
def test_escapejs(self):
f = html.escapejs
items = (
- (u'"double quotes" and \'single quotes\'', u'\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027'),
- (ur'\ : backslashes, too', u'\\u005C : backslashes, too'),
- (u'and lots of whitespace: \r\n\t\v\f\b', u'and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008'),
- (ur'<script>and this</script>', u'\\u003Cscript\\u003Eand this\\u003C/script\\u003E'),
- (u'paragraph separator:\u2029and line separator:\u2028', u'paragraph separator:\\u2029and line separator:\\u2028'),
+ ('"double quotes" and \'single quotes\'', '\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027'),
+ (r'\ : backslashes, too', '\\u005C : backslashes, too'),
+ ('and lots of whitespace: \r\n\t\v\f\b', 'and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008'),
+ (r'<script>and this</script>', '\\u003Cscript\\u003Eand this\\u003C/script\\u003E'),
+ ('paragraph separator:\u2029and line separator:\u2028', 'paragraph separator:\\u2029and line separator:\\u2028'),
)
for value, output in items:
self.check_output(f, value, output)
@@ -125,11 +127,11 @@ class TestUtilsHtml(unittest.TestCase):
def test_clean_html(self):
f = html.clean_html
items = (
- (u'<p>I <i>believe</i> in <b>semantic markup</b>!</p>', u'<p>I <em>believe</em> in <strong>semantic markup</strong>!</p>'),
- (u'I escape & I don\'t <a href="#" target="_blank">target</a>', u'I escape &amp; I don\'t <a href="#" >target</a>'),
- (u'<p>I kill whitespace</p><br clear="all"><p>&nbsp;</p>', u'<p>I kill whitespace</p>'),
+ ('<p>I <i>believe</i> in <b>semantic markup</b>!</p>', '<p>I <em>believe</em> in <strong>semantic markup</strong>!</p>'),
+ ('I escape & I don\'t <a href="#" target="_blank">target</a>', 'I escape &amp; I don\'t <a href="#" >target</a>'),
+ ('<p>I kill whitespace</p><br clear="all"><p>&nbsp;</p>', '<p>I kill whitespace</p>'),
# also a regression test for #7267: this used to raise an UnicodeDecodeError
- (u'<p>* foo</p><p>* bar</p>', u'<ul>\n<li> foo</li><li> bar</li>\n</ul>'),
+ ('<p>* foo</p><p>* bar</p>', '<ul>\n<li> foo</li><li> bar</li>\n</ul>'),
)
for value, output in items:
self.check_output(f, value, output)
diff --git a/tests/regressiontests/utils/ipv6.py b/tests/regressiontests/utils/ipv6.py
index 86d1ad1573..1713de82b8 100644
--- a/tests/regressiontests/utils/ipv6.py
+++ b/tests/regressiontests/utils/ipv6.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.utils import unittest
from django.utils.ipv6 import is_valid_ipv6_address, clean_ipv6_address
@@ -36,16 +38,16 @@ class TestUtilsIPv6(unittest.TestCase):
self.assertFalse(is_valid_ipv6_address('::zzzz:0a0a'))
def test_cleanes_plain_address(self):
- self.assertEqual(clean_ipv6_address('DEAD::0:BEEF'), u'dead::beef')
- self.assertEqual(clean_ipv6_address('2001:000:a:0000:0:fe:fe:beef'), u'2001:0:a::fe:fe:beef')
- self.assertEqual(clean_ipv6_address('2001::a:0000:0:fe:fe:beef'), u'2001:0:a::fe:fe:beef')
+ self.assertEqual(clean_ipv6_address('DEAD::0:BEEF'), 'dead::beef')
+ self.assertEqual(clean_ipv6_address('2001:000:a:0000:0:fe:fe:beef'), '2001:0:a::fe:fe:beef')
+ self.assertEqual(clean_ipv6_address('2001::a:0000:0:fe:fe:beef'), '2001:0:a::fe:fe:beef')
def test_cleanes_with_v4_mapping(self):
- self.assertEqual(clean_ipv6_address('::ffff:0a0a:0a0a'), u'::ffff:10.10.10.10')
- self.assertEqual(clean_ipv6_address('::ffff:1234:1234'), u'::ffff:18.52.18.52')
- self.assertEqual(clean_ipv6_address('::ffff:18.52.18.52'), u'::ffff:18.52.18.52')
+ self.assertEqual(clean_ipv6_address('::ffff:0a0a:0a0a'), '::ffff:10.10.10.10')
+ self.assertEqual(clean_ipv6_address('::ffff:1234:1234'), '::ffff:18.52.18.52')
+ self.assertEqual(clean_ipv6_address('::ffff:18.52.18.52'), '::ffff:18.52.18.52')
def test_unpacks_ipv4(self):
- self.assertEqual(clean_ipv6_address('::ffff:0a0a:0a0a', unpack_ipv4=True), u'10.10.10.10')
- self.assertEqual(clean_ipv6_address('::ffff:1234:1234', unpack_ipv4=True), u'18.52.18.52')
- self.assertEqual(clean_ipv6_address('::ffff:18.52.18.52', unpack_ipv4=True), u'18.52.18.52')
+ self.assertEqual(clean_ipv6_address('::ffff:0a0a:0a0a', unpack_ipv4=True), '10.10.10.10')
+ self.assertEqual(clean_ipv6_address('::ffff:1234:1234', unpack_ipv4=True), '18.52.18.52')
+ self.assertEqual(clean_ipv6_address('::ffff:18.52.18.52', unpack_ipv4=True), '18.52.18.52')
diff --git a/tests/regressiontests/utils/jslex.py b/tests/regressiontests/utils/jslex.py
index 7cd93ca36d..a2af7b4bcf 100644
--- a/tests/regressiontests/utils/jslex.py
+++ b/tests/regressiontests/utils/jslex.py
@@ -23,7 +23,7 @@ class JsTokensTest(TestCase):
(''' 'hello' "hello" ''', ["string 'hello'", 'string "hello"']),
(r""" 'don\'t' "don\"t" '"' "'" '\'' "\"" """,
[r"""string 'don\'t'""", r'''string "don\"t"''', r"""string '"'""", r'''string "'"''', r"""string '\''""", r'''string "\""''']),
- (ur'"ƃuıxǝ⅂ ʇdıɹɔsɐʌɐſ\""', [ur'string "ƃuıxǝ⅂ ʇdıɹɔsɐʌɐſ\""']),
+ (r'"ƃuıxǝ⅂ ʇdıɹɔsɐʌɐſ\""', [r'string "ƃuıxǝ⅂ ʇdıɹɔsɐʌɐſ\""']),
# comments
("a//b", ["id a", "linecomment //b"]),
("/****/a/=2//hello", ["comment /****/", "id a", "punct /=", "dnum 2", "linecomment //hello"]),
diff --git a/tests/regressiontests/utils/regex_helper.py b/tests/regressiontests/utils/regex_helper.py
index 8dc712f5b9..41f4a4f85d 100644
--- a/tests/regressiontests/utils/regex_helper.py
+++ b/tests/regressiontests/utils/regex_helper.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.utils import regex_helper
from django.utils import unittest
@@ -5,44 +7,44 @@ from django.utils import unittest
class NormalizeTests(unittest.TestCase):
def test_empty(self):
pattern = r""
- expected = [(u'', [])]
+ expected = [('', [])]
result = regex_helper.normalize(pattern)
self.assertEqual(result, expected)
def test_escape(self):
pattern = r"\\\^\$\.\|\?\*\+\(\)\["
- expected = [(u'\\^$.|?*+()[', [])]
+ expected = [('\\^$.|?*+()[', [])]
result = regex_helper.normalize(pattern)
self.assertEqual(result, expected)
def test_group_positional(self):
pattern = r"(.*)-(.+)"
- expected = [(u'%(_0)s-%(_1)s', ['_0', '_1'])]
+ expected = [('%(_0)s-%(_1)s', ['_0', '_1'])]
result = regex_helper.normalize(pattern)
self.assertEqual(result, expected)
def test_group_ignored(self):
pattern = r"(?i)(?L)(?m)(?s)(?u)(?#)"
- expected = [(u'', [])]
+ expected = [('', [])]
result = regex_helper.normalize(pattern)
self.assertEqual(result, expected)
def test_group_noncapturing(self):
pattern = r"(?:non-capturing)"
- expected = [(u'non-capturing', [])]
+ expected = [('non-capturing', [])]
result = regex_helper.normalize(pattern)
self.assertEqual(result, expected)
def test_group_named(self):
pattern = r"(?P<first_group_name>.*)-(?P<second_group_name>.*)"
- expected = [(u'%(first_group_name)s-%(second_group_name)s',
+ expected = [('%(first_group_name)s-%(second_group_name)s',
['first_group_name', 'second_group_name'])]
result = regex_helper.normalize(pattern)
self.assertEqual(result, expected)
def test_group_backreference(self):
pattern = r"(?P<first_group_name>.*)-(?P=first_group_name)"
- expected = [(u'%(first_group_name)s-%(first_group_name)s',
+ expected = [('%(first_group_name)s-%(first_group_name)s',
['first_group_name'])]
result = regex_helper.normalize(pattern)
self.assertEqual(result, expected)
diff --git a/tests/regressiontests/utils/simplelazyobject.py b/tests/regressiontests/utils/simplelazyobject.py
index 4ee822563e..982d2226e6 100644
--- a/tests/regressiontests/utils/simplelazyobject.py
+++ b/tests/regressiontests/utils/simplelazyobject.py
@@ -1,6 +1,9 @@
+from __future__ import unicode_literals
+
import copy
import pickle
+from django.test.utils import str_prefix
from django.utils.unittest import TestCase
from django.utils.functional import SimpleLazyObject, empty
@@ -51,10 +54,11 @@ class TestUtilsSimpleLazyObject(TestCase):
self.assertTrue("SimpleLazyObject" in repr(SimpleLazyObject(complex_object)))
def test_str(self):
- self.assertEqual("I am _ComplexObject('joe')", str(SimpleLazyObject(complex_object)))
+ self.assertEqual(str_prefix("I am _ComplexObject(%(_)s'joe')"),
+ str(SimpleLazyObject(complex_object)))
def test_unicode(self):
- self.assertEqual(u"joe", unicode(SimpleLazyObject(complex_object)))
+ self.assertEqual("joe", unicode(SimpleLazyObject(complex_object)))
def test_class(self):
# This is important for classes that use __class__ in things like
diff --git a/tests/regressiontests/utils/text.py b/tests/regressiontests/utils/text.py
index ad65ec89ee..dd6de63841 100644
--- a/tests/regressiontests/utils/text.py
+++ b/tests/regressiontests/utils/text.py
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
import warnings
from django.test import SimpleTestCase
@@ -10,104 +12,104 @@ class TestUtilsText(SimpleTestCase):
# so these tests will need to be adapted accordingly
def test_truncate_chars(self):
truncator = text.Truncator(
- u'The quick brown fox jumped over the lazy dog.'
+ 'The quick brown fox jumped over the lazy dog.'
)
- self.assertEqual(u'The quick brown fox jumped over the lazy dog.',
+ self.assertEqual('The quick brown fox jumped over the lazy dog.',
truncator.chars(100)),
- self.assertEqual(u'The quick brown fox ...',
+ self.assertEqual('The quick brown fox ...',
truncator.chars(23)),
- self.assertEqual(u'The quick brown fo.....',
+ self.assertEqual('The quick brown fo.....',
truncator.chars(23, '.....')),
# Ensure that we normalize our unicode data first
- nfc = text.Truncator(u'o\xfco\xfco\xfco\xfc')
- nfd = text.Truncator(u'ou\u0308ou\u0308ou\u0308ou\u0308')
- self.assertEqual(u'oüoüoüoü', nfc.chars(8))
- self.assertEqual(u'oüoüoüoü', nfd.chars(8))
- self.assertEqual(u'oü...', nfc.chars(5))
- self.assertEqual(u'oü...', nfd.chars(5))
+ nfc = text.Truncator('o\xfco\xfco\xfco\xfc')
+ nfd = text.Truncator('ou\u0308ou\u0308ou\u0308ou\u0308')
+ self.assertEqual('oüoüoüoü', nfc.chars(8))
+ self.assertEqual('oüoüoüoü', nfd.chars(8))
+ self.assertEqual('oü...', nfc.chars(5))
+ self.assertEqual('oü...', nfd.chars(5))
# Ensure the final length is calculated correctly when there are
# combining characters with no precomposed form, and that combining
# characters are not split up.
- truncator = text.Truncator(u'-B\u030AB\u030A----8')
- self.assertEqual(u'-B\u030A...', truncator.chars(5))
- self.assertEqual(u'-B\u030AB\u030A-...', truncator.chars(7))
- self.assertEqual(u'-B\u030AB\u030A----8', truncator.chars(8))
+ truncator = text.Truncator('-B\u030AB\u030A----8')
+ self.assertEqual('-B\u030A...', truncator.chars(5))
+ self.assertEqual('-B\u030AB\u030A-...', truncator.chars(7))
+ self.assertEqual('-B\u030AB\u030A----8', truncator.chars(8))
# Ensure the length of the end text is correctly calculated when it
# contains combining characters with no precomposed form.
- truncator = text.Truncator(u'-----')
- self.assertEqual(u'---B\u030A', truncator.chars(4, u'B\u030A'))
- self.assertEqual(u'-----', truncator.chars(5, u'B\u030A'))
+ truncator = text.Truncator('-----')
+ self.assertEqual('---B\u030A', truncator.chars(4, 'B\u030A'))
+ self.assertEqual('-----', truncator.chars(5, 'B\u030A'))
# Make a best effort to shorten to the desired length, but requesting
# a length shorter than the ellipsis shouldn't break
- self.assertEqual(u'...', text.Truncator(u'asdf').chars(1))
+ self.assertEqual('...', text.Truncator('asdf').chars(1))
def test_truncate_words(self):
- truncator = text.Truncator(u'The quick brown fox jumped over the lazy '
+ truncator = text.Truncator('The quick brown fox jumped over the lazy '
'dog.')
- self.assertEqual(u'The quick brown fox jumped over the lazy dog.',
+ self.assertEqual('The quick brown fox jumped over the lazy dog.',
truncator.words(10))
- self.assertEqual(u'The quick brown fox...', truncator.words(4))
- self.assertEqual(u'The quick brown fox[snip]',
+ self.assertEqual('The quick brown fox...', truncator.words(4))
+ self.assertEqual('The quick brown fox[snip]',
truncator.words(4, '[snip]'))
def test_truncate_html_words(self):
truncator = text.Truncator('<p><strong><em>The quick brown fox jumped '
'over the lazy dog.</em></strong></p>')
- self.assertEqual(u'<p><strong><em>The quick brown fox jumped over the '
+ self.assertEqual('<p><strong><em>The quick brown fox jumped over the '
'lazy dog.</em></strong></p>', truncator.words(10, html=True))
- self.assertEqual(u'<p><strong><em>The quick brown fox...</em>'
+ self.assertEqual('<p><strong><em>The quick brown fox...</em>'
'</strong></p>', truncator.words(4, html=True))
- self.assertEqual(u'<p><strong><em>The quick brown fox....</em>'
+ self.assertEqual('<p><strong><em>The quick brown fox....</em>'
'</strong></p>', truncator.words(4, '....', html=True))
- self.assertEqual(u'<p><strong><em>The quick brown fox</em></strong>'
+ self.assertEqual('<p><strong><em>The quick brown fox</em></strong>'
'</p>', truncator.words(4, '', html=True))
# Test with new line inside tag
truncator = text.Truncator('<p>The quick <a href="xyz.html"\n'
'id="mylink">brown fox</a> jumped over the lazy dog.</p>')
- self.assertEqual(u'<p>The quick <a href="xyz.html"\n'
+ self.assertEqual('<p>The quick <a href="xyz.html"\n'
'id="mylink">brown...</a></p>', truncator.words(3, '...', html=True))
def test_old_truncate_words(self):
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
- self.assertEqual(u'The quick brown fox jumped over the lazy dog.',
- text.truncate_words(u'The quick brown fox jumped over the lazy dog.', 10))
- self.assertEqual(u'The quick brown fox ...',
+ self.assertEqual('The quick brown fox jumped over the lazy dog.',
+ text.truncate_words('The quick brown fox jumped over the lazy dog.', 10))
+ self.assertEqual('The quick brown fox ...',
text.truncate_words('The quick brown fox jumped over the lazy dog.', 4))
- self.assertEqual(u'The quick brown fox ....',
+ self.assertEqual('The quick brown fox ....',
text.truncate_words('The quick brown fox jumped over the lazy dog.', 4, '....'))
self.assertGreater(len(w), 0)
def test_old_truncate_html_words(self):
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
- self.assertEqual(u'<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>',
+ self.assertEqual('<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>',
text.truncate_html_words('<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>', 10))
- self.assertEqual(u'<p><strong><em>The quick brown fox ...</em></strong></p>',
+ self.assertEqual('<p><strong><em>The quick brown fox ...</em></strong></p>',
text.truncate_html_words('<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>', 4))
- self.assertEqual(u'<p><strong><em>The quick brown fox ....</em></strong></p>',
+ self.assertEqual('<p><strong><em>The quick brown fox ....</em></strong></p>',
text.truncate_html_words('<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>', 4, '....'))
- self.assertEqual(u'<p><strong><em>The quick brown fox</em></strong></p>',
+ self.assertEqual('<p><strong><em>The quick brown fox</em></strong></p>',
text.truncate_html_words('<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>', 4, None))
self.assertGreater(len(w), 0)
def test_wrap(self):
digits = '1234 67 9'
- self.assertEqual(text.wrap(digits, 100), u'1234 67 9')
- self.assertEqual(text.wrap(digits, 9), u'1234 67 9')
- self.assertEqual(text.wrap(digits, 8), u'1234 67\n9')
+ self.assertEqual(text.wrap(digits, 100), '1234 67 9')
+ self.assertEqual(text.wrap(digits, 9), '1234 67 9')
+ self.assertEqual(text.wrap(digits, 8), '1234 67\n9')
self.assertEqual(text.wrap('short\na long line', 7),
- u'short\na long\nline')
+ 'short\na long\nline')
self.assertEqual(text.wrap('do-not-break-long-words please? ok', 8),
- u'do-not-break-long-words\nplease?\nok')
+ 'do-not-break-long-words\nplease?\nok')
long_word = 'l%sng' % ('o' * 20)
self.assertEqual(text.wrap(long_word, 20), long_word)
self.assertEqual(text.wrap('a %s word' % long_word, 10),
- u'a\n%s\nword' % long_word)
+ 'a\n%s\nword' % long_word)
diff --git a/tests/regressiontests/utils/timesince.py b/tests/regressiontests/utils/timesince.py
index a4d479ad3e..5e641a42c4 100644
--- a/tests/regressiontests/utils/timesince.py
+++ b/tests/regressiontests/utils/timesince.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import datetime
import unittest
@@ -19,32 +21,32 @@ class TimesinceTests(unittest.TestCase):
def test_equal_datetimes(self):
""" equal datetimes. """
- self.assertEqual(timesince(self.t, self.t), u'0 minutes')
+ self.assertEqual(timesince(self.t, self.t), '0 minutes')
def test_ignore_microseconds_and_seconds(self):
""" Microseconds and seconds are ignored. """
self.assertEqual(timesince(self.t, self.t+self.onemicrosecond),
- u'0 minutes')
+ '0 minutes')
self.assertEqual(timesince(self.t, self.t+self.onesecond),
- u'0 minutes')
+ '0 minutes')
def test_other_units(self):
""" Test other units. """
self.assertEqual(timesince(self.t, self.t+self.oneminute),
- u'1 minute')
- self.assertEqual(timesince(self.t, self.t+self.onehour), u'1 hour')
- self.assertEqual(timesince(self.t, self.t+self.oneday), u'1 day')
- self.assertEqual(timesince(self.t, self.t+self.oneweek), u'1 week')
+ '1 minute')
+ self.assertEqual(timesince(self.t, self.t+self.onehour), '1 hour')
+ self.assertEqual(timesince(self.t, self.t+self.oneday), '1 day')
+ self.assertEqual(timesince(self.t, self.t+self.oneweek), '1 week')
self.assertEqual(timesince(self.t, self.t+self.onemonth),
- u'1 month')
- self.assertEqual(timesince(self.t, self.t+self.oneyear), u'1 year')
+ '1 month')
+ self.assertEqual(timesince(self.t, self.t+self.oneyear), '1 year')
def test_multiple_units(self):
""" Test multiple units. """
self.assertEqual(timesince(self.t,
- self.t+2*self.oneday+6*self.onehour), u'2 days, 6 hours')
+ self.t+2*self.oneday+6*self.onehour), '2 days, 6 hours')
self.assertEqual(timesince(self.t,
- self.t+2*self.oneweek+2*self.oneday), u'2 weeks, 2 days')
+ self.t+2*self.oneweek+2*self.oneday), '2 weeks, 2 days')
def test_display_first_unit(self):
"""
@@ -53,10 +55,10 @@ class TimesinceTests(unittest.TestCase):
"""
self.assertEqual(timesince(self.t,
self.t+2*self.oneweek+3*self.onehour+4*self.oneminute),
- u'2 weeks')
+ '2 weeks')
self.assertEqual(timesince(self.t,
- self.t+4*self.oneday+5*self.oneminute), u'4 days')
+ self.t+4*self.oneday+5*self.oneminute), '4 days')
def test_display_second_before_first(self):
"""
@@ -64,30 +66,30 @@ class TimesinceTests(unittest.TestCase):
get 0 minutes.
"""
self.assertEqual(timesince(self.t, self.t-self.onemicrosecond),
- u'0 minutes')
+ '0 minutes')
self.assertEqual(timesince(self.t, self.t-self.onesecond),
- u'0 minutes')
+ '0 minutes')
self.assertEqual(timesince(self.t, self.t-self.oneminute),
- u'0 minutes')
+ '0 minutes')
self.assertEqual(timesince(self.t, self.t-self.onehour),
- u'0 minutes')
+ '0 minutes')
self.assertEqual(timesince(self.t, self.t-self.oneday),
- u'0 minutes')
+ '0 minutes')
self.assertEqual(timesince(self.t, self.t-self.oneweek),
- u'0 minutes')
+ '0 minutes')
self.assertEqual(timesince(self.t, self.t-self.onemonth),
- u'0 minutes')
+ '0 minutes')
self.assertEqual(timesince(self.t, self.t-self.oneyear),
- u'0 minutes')
+ '0 minutes')
self.assertEqual(timesince(self.t,
- self.t-2*self.oneday-6*self.onehour), u'0 minutes')
+ self.t-2*self.oneday-6*self.onehour), '0 minutes')
self.assertEqual(timesince(self.t,
- self.t-2*self.oneweek-2*self.oneday), u'0 minutes')
+ self.t-2*self.oneweek-2*self.oneday), '0 minutes')
self.assertEqual(timesince(self.t,
self.t-2*self.oneweek-3*self.onehour-4*self.oneminute),
- u'0 minutes')
+ '0 minutes')
self.assertEqual(timesince(self.t,
- self.t-4*self.oneday-5*self.oneminute), u'0 minutes')
+ self.t-4*self.oneday-5*self.oneminute), '0 minutes')
def test_different_timezones(self):
""" When using two different timezones. """
@@ -95,28 +97,28 @@ class TimesinceTests(unittest.TestCase):
now_tz = datetime.datetime.now(LocalTimezone(now))
now_tz_i = datetime.datetime.now(FixedOffset((3 * 60) + 15))
- self.assertEqual(timesince(now), u'0 minutes')
- self.assertEqual(timesince(now_tz), u'0 minutes')
- self.assertEqual(timeuntil(now_tz, now_tz_i), u'0 minutes')
+ self.assertEqual(timesince(now), '0 minutes')
+ self.assertEqual(timesince(now_tz), '0 minutes')
+ self.assertEqual(timeuntil(now_tz, now_tz_i), '0 minutes')
def test_date_objects(self):
""" Both timesince and timeuntil should work on date objects (#17937). """
today = datetime.date.today()
- self.assertEqual(timesince(today + self.oneday), u'0 minutes')
- self.assertEqual(timeuntil(today - self.oneday), u'0 minutes')
+ self.assertEqual(timesince(today + self.oneday), '0 minutes')
+ self.assertEqual(timeuntil(today - self.oneday), '0 minutes')
def test_both_date_objects(self):
""" Timesince should work with both date objects (#9672) """
today = datetime.date.today()
- self.assertEqual(timeuntil(today + self.oneday, today), u'1 day')
- self.assertEqual(timeuntil(today - self.oneday, today), u'0 minutes')
- self.assertEqual(timeuntil(today + self.oneweek, today), u'1 week')
+ self.assertEqual(timeuntil(today + self.oneday, today), '1 day')
+ self.assertEqual(timeuntil(today - self.oneday, today), '0 minutes')
+ self.assertEqual(timeuntil(today + self.oneweek, today), '1 week')
def test_naive_datetime_with_tzinfo_attribute(self):
class naive(datetime.tzinfo):
def utcoffset(self, dt):
return None
future = datetime.datetime(2080, 1, 1, tzinfo=naive())
- self.assertEqual(timesince(future), u'0 minutes')
+ self.assertEqual(timesince(future), '0 minutes')
past = datetime.datetime(1980, 1, 1, tzinfo=naive())
- self.assertEqual(timeuntil(past), u'0 minutes')
+ self.assertEqual(timeuntil(past), '0 minutes')
diff --git a/tests/regressiontests/views/__init__.py b/tests/regressiontests/views/__init__.py
index 1e12679af2..1193ffe010 100644
--- a/tests/regressiontests/views/__init__.py
+++ b/tests/regressiontests/views/__init__.py
@@ -1,10 +1,11 @@
# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
class BrokenException(Exception):
pass
-except_args = (b'Broken!', # plain exception with ASCII text
- u'¡Broken!', # non-ASCII unicode data
- u'¡Broken!'.encode('utf-8'), # non-ASCII, utf-8 encoded bytestring
- b'\xa1Broken!', ) # non-ASCII, latin1 bytestring
+except_args = (b'Broken!', # plain exception with ASCII text
+ '¡Broken!', # non-ASCII unicode data
+ '¡Broken!'.encode('utf-8'), # non-ASCII, utf-8 encoded bytestring
+ b'\xa1Broken!', ) # non-ASCII, latin1 bytestring
diff --git a/tests/regressiontests/views/generic_urls.py b/tests/regressiontests/views/generic_urls.py
index 5bf929eb55..0f214d12d5 100644
--- a/tests/regressiontests/views/generic_urls.py
+++ b/tests/regressiontests/views/generic_urls.py
@@ -1,5 +1,5 @@
# -*- coding:utf-8 -*-
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from django.conf.urls import patterns, url
from django.views.generic import RedirectView
@@ -32,16 +32,16 @@ urlpatterns = patterns('',
(r'^accounts/logout/$', 'django.contrib.auth.views.logout'),
# Special URLs for particular regression cases.
- url(u'^中文/$', 'regressiontests.views.views.redirect'),
- url(u'^中文/target/$', 'regressiontests.views.views.index_page'),
+ url('^中文/$', 'regressiontests.views.views.redirect'),
+ url('^中文/target/$', 'regressiontests.views.views.index_page'),
)
# rediriects, both temporary and permanent, with non-ASCII targets
urlpatterns += patterns('',
('^nonascii_redirect/$', RedirectView.as_view(
- url=u'/中文/target/', permanent=False)),
+ url='/中文/target/', permanent=False)),
('^permanent_nonascii_redirect/$', RedirectView.as_view(
- url=u'/中文/target/', permanent=True)),
+ url='/中文/target/', permanent=True)),
)
urlpatterns += patterns('regressiontests.views.views',
diff --git a/tests/regressiontests/views/tests/specials.py b/tests/regressiontests/views/tests/specials.py
index cd8ac5bb6a..7d652841f8 100644
--- a/tests/regressiontests/views/tests/specials.py
+++ b/tests/regressiontests/views/tests/specials.py
@@ -1,4 +1,6 @@
# coding: utf-8
+from __future__ import unicode_literals
+
from django.test import TestCase
@@ -17,7 +19,7 @@ class URLHandling(TestCase):
characters so this test ensures the creation of the full path with a
base non-ASCII part is handled correctly.
"""
- response = self.client.get(u'/中文/')
+ response = self.client.get('/中文/')
self.assertRedirects(response, self.redirect_target)
def test_nonascii_redirect(self):
diff --git a/tests/regressiontests/wsgi/tests.py b/tests/regressiontests/wsgi/tests.py
index 0e8d7f2ada..9614a81c67 100644
--- a/tests/regressiontests/wsgi/tests.py
+++ b/tests/regressiontests/wsgi/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.core.exceptions import ImproperlyConfigured
from django.core.servers.basehttp import get_internal_wsgi_application
from django.core.wsgi import get_wsgi_application
@@ -38,7 +40,7 @@ class WSGITest(TestCase):
[('Content-Type', 'text/html; charset=utf-8')])
self.assertEqual(
unicode(response),
- u"Content-Type: text/html; charset=utf-8\n\nHello World!")
+ "Content-Type: text/html; charset=utf-8\n\nHello World!")
class GetInternalWSGIApplicationTest(unittest.TestCase):