' % force_unicode(form[cl.model._meta.pk.name]))
class ResultList(list):
# Wrapper class used to return items in a list_editable
diff --git a/django/contrib/admin/util.py b/django/contrib/admin/util.py
index 9611b000501..18b10f3cfa5 100644
--- a/django/contrib/admin/util.py
+++ b/django/contrib/admin/util.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import datetime
import decimal
@@ -122,14 +124,14 @@ def get_deleted_objects(objs, opts, user, admin_site, using):
if not user.has_perm(p):
perms_needed.add(opts.verbose_name)
# Display a link to the admin page.
- return mark_safe(u'%s: %s' %
+ return mark_safe('%s: %s' %
(escape(capfirst(opts.verbose_name)),
admin_url,
escape(obj)))
else:
# Don't display link to edit, because it either has no
# admin or is edited inline.
- return u'%s: %s' % (capfirst(opts.verbose_name),
+ return '%s: %s' % (capfirst(opts.verbose_name),
force_unicode(obj))
to_delete = collector.nested(format_callback)
diff --git a/django/contrib/admin/widgets.py b/django/contrib/admin/widgets.py
index 980863ed840..18897bdeb19 100644
--- a/django/contrib/admin/widgets.py
+++ b/django/contrib/admin/widgets.py
@@ -1,8 +1,10 @@
"""
Form Widget classes specific to the Django admin site.
"""
+from __future__ import unicode_literals
import copy
+
from django import forms
from django.contrib.admin.templatetags.admin_static import static
from django.core.urlresolvers import reverse
@@ -39,12 +41,12 @@ class FilteredSelectMultiple(forms.SelectMultiple):
if self.is_stacked:
attrs['class'] += 'stacked'
output = [super(FilteredSelectMultiple, self).render(name, value, attrs, choices)]
- output.append(u'\n'
+ output.append('SelectFilter.init("id_%s", "%s", %s, "%s"); });\n'
% (name, self.verbose_name.replace('"', '\\"'), int(self.is_stacked), static('admin/')))
- return mark_safe(u''.join(output))
+ return mark_safe(''.join(output))
class AdminDateWidget(forms.DateInput):
@@ -83,24 +85,24 @@ class AdminSplitDateTime(forms.SplitDateTimeWidget):
forms.MultiWidget.__init__(self, widgets, attrs)
def format_output(self, rendered_widgets):
- return mark_safe(u'
%s %s %s %s
' % \
+ return mark_safe('
%s %s %s %s
' % \
(_('Date:'), rendered_widgets[0], _('Time:'), rendered_widgets[1]))
class AdminRadioFieldRenderer(RadioFieldRenderer):
def render(self):
"""Outputs a
for this set of radio fields."""
- return mark_safe(u'
\n%s\n
' % (
+ return mark_safe('
\n%s\n
' % (
flatatt(self.attrs),
- u'\n'.join([u'
%s
' % force_unicode(w) for w in self]))
+ '\n'.join(['
%s
' % force_unicode(w) for w in self]))
)
class AdminRadioSelect(forms.RadioSelect):
renderer = AdminRadioFieldRenderer
class AdminFileWidget(forms.ClearableFileInput):
- template_with_initial = (u'
%s
'
+ template_with_initial = ('
%s
'
% forms.ClearableFileInput.template_with_initial)
- template_with_clear = (u'%s'
+ template_with_clear = ('%s'
% forms.ClearableFileInput.template_with_clear)
def url_params_from_lookup_dict(lookups):
@@ -113,7 +115,7 @@ def url_params_from_lookup_dict(lookups):
items = []
for k, v in lookups.items():
if isinstance(v, (tuple, list)):
- v = u','.join([str(x) for x in v])
+ v = ','.join([str(x) for x in v])
elif isinstance(v, bool):
# See django.db.fields.BooleanField.get_prep_lookup
v = ('0', '1')[v]
@@ -148,21 +150,21 @@ class ForeignKeyRawIdWidget(forms.TextInput):
params = self.url_parameters()
if params:
- url = u'?' + u'&'.join([u'%s=%s' % (k, v) for k, v in params.items()])
+ url = '?' + '&'.join(['%s=%s' % (k, v) for k, v in params.items()])
else:
- url = u''
+ url = ''
if "class" not in attrs:
attrs['class'] = 'vForeignKeyRawIdAdminField' # The JavaScript code looks for this hook.
# TODO: "lookup_id_" is hard-coded here. This should instead use
# the correct API to determine the ID dynamically.
- extra.append(u' '
+ extra.append(' '
% (related_url, url, name))
- extra.append(u''
+ extra.append(''
% (static('admin/img/selector-search.gif'), _('Lookup')))
output = [super(ForeignKeyRawIdWidget, self).render(name, value, attrs)] + extra
if value:
output.append(self.label_for_value(value))
- return mark_safe(u''.join(output))
+ return mark_safe(''.join(output))
def base_url_parameters(self):
return url_params_from_lookup_dict(self.rel.limit_choices_to)
@@ -261,11 +263,11 @@ class RelatedFieldWidgetWrapper(forms.Widget):
related_url = reverse('admin:%s_%s_add' % info, current_app=self.admin_site.name)
# TODO: "add_id_" is hard-coded here. This should instead use the
# correct API to determine the ID dynamically.
- output.append(u' '
+ output.append(' '
% (related_url, name))
- output.append(u''
+ output.append(''
% (static('admin/img/icon_addlink.gif'), _('Add Another')))
- return mark_safe(u''.join(output))
+ return mark_safe(''.join(output))
def build_attrs(self, extra_attrs=None, **kwargs):
"Helper function for building an attribute dictionary."
diff --git a/django/contrib/admindocs/tests/__init__.py b/django/contrib/admindocs/tests/__init__.py
index 49a925a4530..306475beb1f 100644
--- a/django/contrib/admindocs/tests/__init__.py
+++ b/django/contrib/admindocs/tests/__init__.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from django.contrib.admindocs import views
from django.db.models import fields as builtin_fields
@@ -20,17 +20,17 @@ class TestFieldType(unittest.TestCase):
def test_builtin_fields(self):
self.assertEqual(
views.get_readable_field_data_type(builtin_fields.BooleanField()),
- _(u'Boolean (Either True or False)')
+ _('Boolean (Either True or False)')
)
def test_custom_fields(self):
self.assertEqual(
views.get_readable_field_data_type(fields.CustomField()),
- _(u'A custom field type')
+ _('A custom field type')
)
self.assertEqual(
views.get_readable_field_data_type(fields.DescriptionLackingField()),
- _(u'Field of type: %(field_type)s') % {
+ _('Field of type: %(field_type)s') % {
'field_type': 'DescriptionLackingField'
}
)
diff --git a/django/contrib/auth/backends.py b/django/contrib/auth/backends.py
index 04fbef4788e..9088e2fbf63 100644
--- a/django/contrib/auth/backends.py
+++ b/django/contrib/auth/backends.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.auth.models import User, Permission
@@ -36,7 +38,7 @@ class ModelBackend(object):
if user_obj.is_anonymous() or obj is not None:
return set()
if not hasattr(user_obj, '_perm_cache'):
- user_obj._perm_cache = set([u"%s.%s" % (p.content_type.app_label, p.codename) for p in user_obj.user_permissions.select_related()])
+ user_obj._perm_cache = set(["%s.%s" % (p.content_type.app_label, p.codename) for p in user_obj.user_permissions.select_related()])
user_obj._perm_cache.update(self.get_group_permissions(user_obj))
return user_obj._perm_cache
diff --git a/django/contrib/auth/hashers.py b/django/contrib/auth/hashers.py
index 0897de8d84a..96ec40ba60f 100644
--- a/django/contrib/auth/hashers.py
+++ b/django/contrib/auth/hashers.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import hashlib
from django.dispatch import receiver
diff --git a/django/contrib/auth/management/__init__.py b/django/contrib/auth/management/__init__.py
index 66f54f18a85..100acb6c5be 100644
--- a/django/contrib/auth/management/__init__.py
+++ b/django/contrib/auth/management/__init__.py
@@ -1,6 +1,8 @@
"""
Creates permissions for all installed apps that need permissions.
"""
+from __future__ import unicode_literals
+
import getpass
import locale
import unicodedata
@@ -10,14 +12,14 @@ from django.contrib.auth.models import User
def _get_permission_codename(action, opts):
- return u'%s_%s' % (action, opts.object_name.lower())
+ return '%s_%s' % (action, opts.object_name.lower())
def _get_all_permissions(opts):
"Returns (codename, name) for all permissions in the given opts."
perms = []
for action in ('add', 'change', 'delete'):
- perms.append((_get_permission_codename(action, opts), u'Can %s %s' % (action, opts.verbose_name_raw)))
+ perms.append((_get_permission_codename(action, opts), 'Can %s %s' % (action, opts.verbose_name_raw)))
return perms + list(opts.permissions)
@@ -88,7 +90,7 @@ def get_system_username():
# if there is no corresponding entry in the /etc/passwd file
# (a very restricted chroot environment, for example).
# UnicodeDecodeError - preventive treatment for non-latin Windows.
- return u''
+ return ''
def get_default_username(check_db=True):
diff --git a/django/contrib/auth/models.py b/django/contrib/auth/models.py
index 090b6d40c88..244721065da 100644
--- a/django/contrib/auth/models.py
+++ b/django/contrib/auth/models.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import urllib
from django.core.exceptions import ImproperlyConfigured
@@ -76,7 +78,7 @@ class Permission(models.Model):
'codename')
def __unicode__(self):
- return u"%s | %s | %s" % (
+ return "%s | %s | %s" % (
unicode(self.content_type.app_label),
unicode(self.content_type),
unicode(self.name))
@@ -285,7 +287,7 @@ class User(models.Model):
"""
Returns the first_name plus the last_name, with a space in between.
"""
- full_name = u'%s %s' % (self.first_name, self.last_name)
+ full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def set_password(self, raw_password):
diff --git a/django/contrib/auth/tests/auth_backends.py b/django/contrib/auth/tests/auth_backends.py
index 7b38acfa50e..9a4d8f9b3a7 100644
--- a/django/contrib/auth/tests/auth_backends.py
+++ b/django/contrib/auth/tests/auth_backends.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.conf import settings
from django.contrib.auth.models import User, Group, Permission, AnonymousUser
from django.contrib.contenttypes.models import ContentType
@@ -51,7 +53,7 @@ class BackendTest(TestCase):
# reloading user to purge the _perm_cache
user = User.objects.get(username='test')
- self.assertEqual(user.get_all_permissions() == set([u'auth.test']), True)
+ self.assertEqual(user.get_all_permissions() == set(['auth.test']), True)
self.assertEqual(user.get_group_permissions(), set([]))
self.assertEqual(user.has_module_perms('Group'), False)
self.assertEqual(user.has_module_perms('auth'), True)
@@ -62,7 +64,7 @@ class BackendTest(TestCase):
user.user_permissions.add(perm)
user.save()
user = User.objects.get(username='test')
- self.assertEqual(user.get_all_permissions(), set([u'auth.test2', u'auth.test', u'auth.test3']))
+ self.assertEqual(user.get_all_permissions(), set(['auth.test2', 'auth.test', 'auth.test3']))
self.assertEqual(user.has_perm('test'), False)
self.assertEqual(user.has_perm('auth.test'), True)
self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), True)
@@ -72,9 +74,9 @@ class BackendTest(TestCase):
group.save()
user.groups.add(group)
user = User.objects.get(username='test')
- exp = set([u'auth.test2', u'auth.test', u'auth.test3', u'auth.test_group'])
+ exp = set(['auth.test2', 'auth.test', 'auth.test3', 'auth.test_group'])
self.assertEqual(user.get_all_permissions(), exp)
- self.assertEqual(user.get_group_permissions(), set([u'auth.test_group']))
+ self.assertEqual(user.get_group_permissions(), set(['auth.test_group']))
self.assertEqual(user.has_perms(['auth.test3', 'auth.test_group']), True)
user = AnonymousUser()
diff --git a/django/contrib/auth/tests/forms.py b/django/contrib/auth/tests/forms.py
index fd2b526f17e..2ab895804f6 100644
--- a/django/contrib/auth/tests/forms.py
+++ b/django/contrib/auth/tests/forms.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import os
from django.contrib.auth.models import User
from django.contrib.auth.forms import (UserCreationForm, AuthenticationForm,
@@ -299,7 +301,7 @@ class PasswordResetFormTest(TestCase):
# potential case where contrib.sites is not installed. Refs #16412.
form.save(domain_override='example.com')
self.assertEqual(len(mail.outbox), 1)
- self.assertEqual(mail.outbox[0].subject, u'Custom password reset on example.com')
+ self.assertEqual(mail.outbox[0].subject, 'Custom password reset on example.com')
def test_bug_5605(self):
# bug #5605, preserve the case of the user name (before the @ in the
@@ -328,4 +330,4 @@ class PasswordResetFormTest(TestCase):
form = PasswordResetForm(data)
self.assertFalse(form.is_valid())
self.assertEqual(form["email"].errors,
- [_(u"The user account associated with this e-mail address cannot reset the password.")])
+ [_("The user account associated with this e-mail address cannot reset the password.")])
diff --git a/django/contrib/auth/tests/hashers.py b/django/contrib/auth/tests/hashers.py
index 15fc1d1da72..673263b5669 100644
--- a/django/contrib/auth/tests/hashers.py
+++ b/django/contrib/auth/tests/hashers.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.conf.global_settings import PASSWORD_HASHERS as default_hashers
from django.contrib.auth.hashers import (is_password_usable,
check_password, make_password, PBKDF2PasswordHasher, load_hashers,
@@ -26,7 +28,7 @@ class TestUtilsHashPass(unittest.TestCase):
encoded = make_password('letmein')
self.assertTrue(encoded.startswith('pbkdf2_sha256$'))
self.assertTrue(is_password_usable(encoded))
- self.assertTrue(check_password(u'letmein', encoded))
+ self.assertTrue(check_password('letmein', encoded))
self.assertFalse(check_password('letmeinz', encoded))
def test_pkbdf2(self):
@@ -34,7 +36,7 @@ class TestUtilsHashPass(unittest.TestCase):
self.assertEqual(encoded,
'pbkdf2_sha256$10000$seasalt$FQCNpiZpTb0zub+HBsH6TOwyRxJ19FwvjbweatNmK/Y=')
self.assertTrue(is_password_usable(encoded))
- self.assertTrue(check_password(u'letmein', encoded))
+ self.assertTrue(check_password('letmein', encoded))
self.assertFalse(check_password('letmeinz', encoded))
self.assertEqual(identify_hasher(encoded).algorithm, "pbkdf2_sha256")
@@ -43,7 +45,7 @@ class TestUtilsHashPass(unittest.TestCase):
self.assertEqual(encoded,
'sha1$seasalt$fec3530984afba6bade3347b7140d1a7da7da8c7')
self.assertTrue(is_password_usable(encoded))
- self.assertTrue(check_password(u'letmein', encoded))
+ self.assertTrue(check_password('letmein', encoded))
self.assertFalse(check_password('letmeinz', encoded))
self.assertEqual(identify_hasher(encoded).algorithm, "sha1")
@@ -52,7 +54,7 @@ class TestUtilsHashPass(unittest.TestCase):
self.assertEqual(encoded,
'md5$seasalt$f5531bef9f3687d0ccf0f617f0e25573')
self.assertTrue(is_password_usable(encoded))
- self.assertTrue(check_password(u'letmein', encoded))
+ self.assertTrue(check_password('letmein', encoded))
self.assertFalse(check_password('letmeinz', encoded))
self.assertEqual(identify_hasher(encoded).algorithm, "md5")
@@ -60,7 +62,7 @@ class TestUtilsHashPass(unittest.TestCase):
encoded = make_password('letmein', 'seasalt', 'unsalted_md5')
self.assertEqual(encoded, '0d107d09f5bbe40cade3de5c71e9e9b7')
self.assertTrue(is_password_usable(encoded))
- self.assertTrue(check_password(u'letmein', encoded))
+ self.assertTrue(check_password('letmein', encoded))
self.assertFalse(check_password('letmeinz', encoded))
self.assertEqual(identify_hasher(encoded).algorithm, "unsalted_md5")
@@ -69,7 +71,7 @@ class TestUtilsHashPass(unittest.TestCase):
encoded = make_password('letmein', 'ab', 'crypt')
self.assertEqual(encoded, 'crypt$$abN/qM.L/H8EQ')
self.assertTrue(is_password_usable(encoded))
- self.assertTrue(check_password(u'letmein', encoded))
+ self.assertTrue(check_password('letmein', encoded))
self.assertFalse(check_password('letmeinz', encoded))
self.assertEqual(identify_hasher(encoded).algorithm, "crypt")
@@ -78,7 +80,7 @@ class TestUtilsHashPass(unittest.TestCase):
encoded = make_password('letmein', hasher='bcrypt')
self.assertTrue(is_password_usable(encoded))
self.assertTrue(encoded.startswith('bcrypt$'))
- self.assertTrue(check_password(u'letmein', encoded))
+ self.assertTrue(check_password('letmein', encoded))
self.assertFalse(check_password('letmeinz', encoded))
self.assertEqual(identify_hasher(encoded).algorithm, "bcrypt")
@@ -88,7 +90,7 @@ class TestUtilsHashPass(unittest.TestCase):
self.assertFalse(check_password(None, encoded))
self.assertFalse(check_password(UNUSABLE_PASSWORD, encoded))
self.assertFalse(check_password('', encoded))
- self.assertFalse(check_password(u'letmein', encoded))
+ self.assertFalse(check_password('letmein', encoded))
self.assertFalse(check_password('letmeinz', encoded))
self.assertRaises(ValueError, identify_hasher, encoded)
diff --git a/django/contrib/auth/tests/management.py b/django/contrib/auth/tests/management.py
index 81ab0aa0529..8d1f7c7965a 100644
--- a/django/contrib/auth/tests/management.py
+++ b/django/contrib/auth/tests/management.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from StringIO import StringIO
from django.contrib.auth import models, management
@@ -15,19 +17,19 @@ class GetDefaultUsernameTestCase(TestCase):
management.get_system_username = self._getpass_getuser
def test_simple(self):
- management.get_system_username = lambda: u'joe'
+ management.get_system_username = lambda: 'joe'
self.assertEqual(management.get_default_username(), 'joe')
def test_existing(self):
models.User.objects.create(username='joe')
- management.get_system_username = lambda: u'joe'
+ management.get_system_username = lambda: 'joe'
self.assertEqual(management.get_default_username(), '')
self.assertEqual(
management.get_default_username(check_db=False), 'joe')
def test_i18n(self):
# 'Julia' with accented 'u':
- management.get_system_username = lambda: u'J\xfalia'
+ management.get_system_username = lambda: 'J\xfalia'
self.assertEqual(management.get_default_username(), 'julia')
diff --git a/django/contrib/comments/admin.py b/django/contrib/comments/admin.py
index 4cb90663a0e..0024a1d1b5d 100644
--- a/django/contrib/comments/admin.py
+++ b/django/contrib/comments/admin.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib import admin
from django.contrib.comments.models import Comment
from django.utils.translation import ugettext_lazy as _, ungettext
@@ -62,8 +64,8 @@ class CommentsAdmin(admin.ModelAdmin):
action(request, comment)
n_comments += 1
- msg = ungettext(u'1 comment was successfully %(action)s.',
- u'%(count)s comments were successfully %(action)s.',
+ msg = ungettext('1 comment was successfully %(action)s.',
+ '%(count)s comments were successfully %(action)s.',
n_comments)
self.message_user(request, msg % {'count': n_comments, 'action': done_message(n_comments)})
diff --git a/django/contrib/contenttypes/generic.py b/django/contrib/contenttypes/generic.py
index a6732d7a2e3..d5062cabf3a 100644
--- a/django/contrib/contenttypes/generic.py
+++ b/django/contrib/contenttypes/generic.py
@@ -1,6 +1,7 @@
"""
Classes allowing "generic" relations through ContentType and object-id fields.
"""
+from __future__ import unicode_literals
from collections import defaultdict
from functools import partial
@@ -131,7 +132,7 @@ class GenericForeignKey(object):
def __set__(self, instance, value):
if instance is None:
- raise AttributeError(u"%s must be accessed via instance" % self.related.opts.object_name)
+ raise AttributeError("%s must be accessed via instance" % self.related.opts.object_name)
ct = None
fk = None
diff --git a/django/contrib/contenttypes/tests.py b/django/contrib/contenttypes/tests.py
index 0057dd535d3..2eaa4c182ec 100644
--- a/django/contrib/contenttypes/tests.py
+++ b/django/contrib/contenttypes/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import urllib
from django.db import models
@@ -181,4 +183,4 @@ class ContentTypesTests(TestCase):
app_label = 'contenttypes',
model = 'OldModel',
)
- self.assertEqual(unicode(ct), u'Old model')
+ self.assertEqual(unicode(ct), 'Old model')
diff --git a/django/contrib/contenttypes/views.py b/django/contrib/contenttypes/views.py
index 8d8e1c7a3e3..5c22cb6672e 100644
--- a/django/contrib/contenttypes/views.py
+++ b/django/contrib/contenttypes/views.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django import http
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site, get_current_site
@@ -12,11 +14,11 @@ def shortcut(request, content_type_id, object_id):
try:
content_type = ContentType.objects.get(pk=content_type_id)
if not content_type.model_class():
- raise http.Http404(_(u"Content type %(ct_id)s object has no associated model") %
+ raise http.Http404(_("Content type %(ct_id)s object has no associated model") %
{'ct_id': content_type_id})
obj = content_type.get_object_for_this_type(pk=object_id)
except (ObjectDoesNotExist, ValueError):
- raise http.Http404(_(u"Content type %(ct_id)s object %(obj_id)s doesn't exist") %
+ raise http.Http404(_("Content type %(ct_id)s object %(obj_id)s doesn't exist") %
{'ct_id': content_type_id, 'obj_id': object_id})
try:
diff --git a/django/contrib/databrowse/datastructures.py b/django/contrib/databrowse/datastructures.py
index 9a4ba17e19f..6a78b3688b9 100644
--- a/django/contrib/databrowse/datastructures.py
+++ b/django/contrib/databrowse/datastructures.py
@@ -2,6 +2,7 @@
These classes are light wrappers around Django's database API that provide
convenience functionality and permalink functions for the databrowse app.
"""
+from __future__ import unicode_literals
from django.db import models
from django.utils import formats
@@ -61,7 +62,7 @@ class EasyField(object):
self.model, self.field = easy_model, field
def __repr__(self):
- return smart_str(u'' % (self.model.model._meta.object_name, self.field.name))
+ return smart_str('' % (self.model.model._meta.object_name, self.field.name))
def choices(self):
for value, label in self.field.choices:
@@ -79,7 +80,7 @@ class EasyChoice(object):
self.value, self.label = value, label
def __repr__(self):
- return smart_str(u'' % (self.model.model._meta.object_name, self.field.name))
+ return smart_str('' % (self.model.model._meta.object_name, self.field.name))
def url(self):
return mark_safe('%s%s/%s/%s/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name, self.field.field.name, iri_to_uri(self.value)))
@@ -89,12 +90,12 @@ class EasyInstance(object):
self.model, self.instance = easy_model, instance
def __repr__(self):
- return smart_str(u'' % (self.model.model._meta.object_name, self.instance._get_pk_val()))
+ return smart_str('' % (self.model.model._meta.object_name, self.instance._get_pk_val()))
def __unicode__(self):
val = smart_unicode(self.instance)
if len(val) > DISPLAY_SIZE:
- return val[:DISPLAY_SIZE] + u'...'
+ return val[:DISPLAY_SIZE] + '...'
return val
def __str__(self):
@@ -136,7 +137,7 @@ class EasyInstanceField(object):
self.raw_value = getattr(instance.instance, field.name)
def __repr__(self):
- return smart_str(u'' % (self.model.model._meta.object_name, self.field.name))
+ return smart_str('' % (self.model.model._meta.object_name, self.field.name))
def values(self):
"""
diff --git a/django/contrib/databrowse/plugins/calendars.py b/django/contrib/databrowse/plugins/calendars.py
index 3416f88ca7f..587c752a949 100644
--- a/django/contrib/databrowse/plugins/calendars.py
+++ b/django/contrib/databrowse/plugins/calendars.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django import http
from django.db import models
from django.contrib.databrowse.datastructures import EasyModel
@@ -61,14 +63,14 @@ class CalendarPlugin(DatabrowsePlugin):
def model_index_html(self, request, model, site):
fields = self.field_dict(model)
if not fields:
- return u''
- return mark_safe(u'
View calendar by: %s
' % \
- u', '.join(['%s' % (f.name, force_unicode(capfirst(f.verbose_name))) for f in fields.values()]))
+ return ''
+ return mark_safe('
View calendar by: %s
' % \
+ ', '.join(['%s' % (f.name, force_unicode(capfirst(f.verbose_name))) for f in fields.values()]))
def urls(self, plugin_name, easy_instance_field):
if isinstance(easy_instance_field.field, models.DateField):
d = easy_instance_field.raw_value
- return [mark_safe(u'%s%s/%s/%s/%s/%s/' % (
+ return [mark_safe('%s%s/%s/%s/%s/%s/' % (
easy_instance_field.model.url(),
plugin_name, easy_instance_field.field.name,
str(d.year),
diff --git a/django/contrib/databrowse/plugins/fieldchoices.py b/django/contrib/databrowse/plugins/fieldchoices.py
index b3210681e9e..5a13252ab36 100644
--- a/django/contrib/databrowse/plugins/fieldchoices.py
+++ b/django/contrib/databrowse/plugins/fieldchoices.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django import http
from django.db import models
from django.contrib.databrowse.datastructures import EasyModel
@@ -29,14 +31,14 @@ class FieldChoicePlugin(DatabrowsePlugin):
def model_index_html(self, request, model, site):
fields = self.field_dict(model)
if not fields:
- return u''
- return mark_safe(u'
View by: %s
' % \
- u', '.join(['%s' % (f.name, force_unicode(capfirst(f.verbose_name))) for f in fields.values()]))
+ return ''
+ return mark_safe('
View by: %s
' % \
+ ', '.join(['%s' % (f.name, force_unicode(capfirst(f.verbose_name))) for f in fields.values()]))
def urls(self, plugin_name, easy_instance_field):
if easy_instance_field.field in self.field_dict(easy_instance_field.model.model).values():
field_value = smart_str(easy_instance_field.raw_value)
- return [mark_safe(u'%s%s/%s/%s/' % (
+ return [mark_safe('%s%s/%s/%s/' % (
easy_instance_field.model.url(),
plugin_name, easy_instance_field.field.name,
urllib.quote(field_value, safe='')))]
diff --git a/django/contrib/databrowse/sites.py b/django/contrib/databrowse/sites.py
index d90bb562b23..b5cb2639d63 100644
--- a/django/contrib/databrowse/sites.py
+++ b/django/contrib/databrowse/sites.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django import http
from django.db import models
from django.contrib.databrowse.datastructures import EasyModel
@@ -61,7 +63,7 @@ class ModelDatabrowse(object):
def main_view(self, request):
easy_model = EasyModel(self.site, self.model)
- html_snippets = mark_safe(u'\n'.join([p.model_index_html(request, self.model, self.site) for p in self.plugins.values()]))
+ html_snippets = mark_safe('\n'.join([p.model_index_html(request, self.model, self.site) for p in self.plugins.values()]))
return render_to_response('databrowse/model_detail.html', {
'model': easy_model,
'root_url': self.site.root_url,
diff --git a/django/contrib/flatpages/models.py b/django/contrib/flatpages/models.py
index 85873ac7b17..42ec155f343 100644
--- a/django/contrib/flatpages/models.py
+++ b/django/contrib/flatpages/models.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.db import models
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
@@ -20,7 +22,7 @@ class FlatPage(models.Model):
ordering = ('url',)
def __unicode__(self):
- return u"%s -- %s" % (self.url, self.title)
+ return "%s -- %s" % (self.url, self.title)
def get_absolute_url(self):
return self.url
diff --git a/django/contrib/flatpages/tests/forms.py b/django/contrib/flatpages/tests/forms.py
index 0e54176aa25..3bdfa15dfea 100644
--- a/django/contrib/flatpages/tests/forms.py
+++ b/django/contrib/flatpages/tests/forms.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.conf import settings
from django.contrib.flatpages.forms import FlatpageForm
from django.contrib.flatpages.models import FlatPage
@@ -60,7 +62,7 @@ class FlatpageAdminFormTests(TestCase):
self.assertEqual(
f.errors,
- {'__all__': [u'Flatpage with url /myflatpage1/ already exists for site example.com']})
+ {'__all__': ['Flatpage with url /myflatpage1/ already exists for site example.com']})
def test_flatpage_admin_form_edit(self):
"""
@@ -92,5 +94,5 @@ class FlatpageAdminFormTests(TestCase):
self.assertEqual(
f.errors,
- {'sites': [translation.ugettext(u'This field is required.')]})
+ {'sites': [translation.ugettext('This field is required.')]})
diff --git a/django/contrib/formtools/tests/__init__.py b/django/contrib/formtools/tests/__init__.py
index b5d905071f6..3bccb550340 100644
--- a/django/contrib/formtools/tests/__init__.py
+++ b/django/contrib/formtools/tests/__init__.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import os
import re
import warnings
@@ -41,7 +43,7 @@ class PreviewTests(TestCase):
self.preview = preview.FormPreview(TestForm)
input_template = ''
self.input = input_template % (self.preview.unused_name('stage'), "%d")
- self.test_data = {'field1':u'foo', 'field1_':u'asdf'}
+ self.test_data = {'field1': 'foo', 'field1_': 'asdf'}
def test_unused_name(self):
"""
@@ -117,7 +119,7 @@ class PreviewTests(TestCase):
"""
self.test_data.update({'stage':2})
hash = self.preview.security_hash(None, TestForm(self.test_data))
- self.test_data.update({'hash':hash, 'bool1':u'False'})
+ self.test_data.update({'hash': hash, 'bool1': 'False'})
with warnings.catch_warnings(record=True):
response = self.client.post('/preview/', self.test_data)
self.assertEqual(response.content, success_string)
@@ -163,8 +165,8 @@ class FormHmacTests(unittest.TestCase):
leading/trailing whitespace so as to be friendly to broken browsers that
submit it (usually in textareas).
"""
- f1 = HashTestForm({'name': u'joe', 'bio': u'Nothing notable.'})
- f2 = HashTestForm({'name': u' joe', 'bio': u'Nothing notable. '})
+ f1 = HashTestForm({'name': 'joe', 'bio': 'Nothing notable.'})
+ f2 = HashTestForm({'name': ' joe', 'bio': 'Nothing notable. '})
hash1 = utils.form_hmac(f1)
hash2 = utils.form_hmac(f2)
self.assertEqual(hash1, hash2)
@@ -266,10 +268,10 @@ class WizardTests(TestCase):
Form should advance if the hash is present and good, as calculated using
current method.
"""
- data = {"0-field": u"test",
- "1-field": u"test2",
- "hash_0": u"cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca",
- "wizard_step": u"1"}
+ data = {"0-field": "test",
+ "1-field": "test2",
+ "hash_0": "cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca",
+ "wizard_step": "1"}
response = self.client.post('/wizard1/', data)
self.assertEqual(2, response.context['step0'])
@@ -291,18 +293,18 @@ class WizardTests(TestCase):
reached[0] = True
wizard = WizardWithProcessStep([WizardPageOneForm])
- data = {"0-field": u"test",
- "1-field": u"test2",
- "hash_0": u"cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca",
- "wizard_step": u"1"}
+ data = {"0-field": "test",
+ "1-field": "test2",
+ "hash_0": "cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca",
+ "wizard_step": "1"}
wizard(DummyRequest(POST=data))
self.assertTrue(reached[0])
- data = {"0-field": u"test",
- "1-field": u"test2",
+ data = {"0-field": "test",
+ "1-field": "test2",
"hash_0": "cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca",
- "hash_1": u"1e6f6315da42e62f33a30640ec7e007ad3fbf1a1",
- "wizard_step": u"2"}
+ "hash_1": "1e6f6315da42e62f33a30640ec7e007ad3fbf1a1",
+ "wizard_step": "2"}
self.assertRaises(http.Http404, wizard, DummyRequest(POST=data))
def test_14498(self):
@@ -321,10 +323,10 @@ class WizardTests(TestCase):
wizard = WizardWithProcessStep([WizardPageOneForm,
WizardPageTwoForm,
WizardPageThreeForm])
- data = {"0-field": u"test",
- "1-field": u"test2",
- "hash_0": u"cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca",
- "wizard_step": u"1"}
+ data = {"0-field": "test",
+ "1-field": "test2",
+ "hash_0": "cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca",
+ "wizard_step": "1"}
wizard(DummyRequest(POST=data))
self.assertTrue(reached[0])
@@ -345,10 +347,10 @@ class WizardTests(TestCase):
wizard = Wizard([WizardPageOneForm,
WizardPageTwoForm])
- data = {"0-field": u"test",
- "1-field": u"test2",
- "hash_0": u"cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca",
- "wizard_step": u"1"}
+ data = {"0-field": "test",
+ "1-field": "test2",
+ "hash_0": "cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca",
+ "wizard_step": "1"}
wizard(DummyRequest(POST=data))
self.assertTrue(reached[0])
@@ -371,10 +373,10 @@ class WizardTests(TestCase):
wizard = WizardWithProcessStep([WizardPageOneForm,
WizardPageTwoForm,
WizardPageThreeForm])
- data = {"0-field": u"test",
- "1-field": u"test2",
- "hash_0": u"cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca",
- "wizard_step": u"1"}
+ data = {"0-field": "test",
+ "1-field": "test2",
+ "hash_0": "cd13b1db3e8f55174bc5745a1b1a53408d4fd1ca",
+ "wizard_step": "1"}
wizard(DummyRequest(POST=data))
self.assertTrue(reached[0])
diff --git a/django/contrib/formtools/tests/wizard/forms.py b/django/contrib/formtools/tests/wizard/forms.py
index 8afbd307214..51cfaa661b6 100644
--- a/django/contrib/formtools/tests/wizard/forms.py
+++ b/django/contrib/formtools/tests/wizard/forms.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django import forms, http
from django.conf import settings
from django.test import TestCase
@@ -64,22 +66,22 @@ class TestWizard(WizardView):
class FormTests(TestCase):
def test_form_init(self):
testform = TestWizard.get_initkwargs([Step1, Step2])
- self.assertEqual(testform['form_list'], {u'0': Step1, u'1': Step2})
+ self.assertEqual(testform['form_list'], {'0': Step1, '1': Step2})
testform = TestWizard.get_initkwargs([('start', Step1), ('step2', Step2)])
self.assertEqual(
- testform['form_list'], {u'start': Step1, u'step2': Step2})
+ testform['form_list'], {'start': Step1, 'step2': Step2})
testform = TestWizard.get_initkwargs([Step1, Step2, ('finish', Step3)])
self.assertEqual(
- testform['form_list'], {u'0': Step1, u'1': Step2, u'finish': Step3})
+ testform['form_list'], {'0': Step1, '1': Step2, 'finish': Step3})
def test_first_step(self):
request = get_request()
testform = TestWizard.as_view([Step1, Step2])
response, instance = testform(request)
- self.assertEqual(instance.steps.current, u'0')
+ self.assertEqual(instance.steps.current, '0')
testform = TestWizard.as_view([('start', Step1), ('step2', Step2)])
response, instance = testform(request)
diff --git a/django/contrib/formtools/tests/wizard/namedwizardtests/tests.py b/django/contrib/formtools/tests/wizard/namedwizardtests/tests.py
index 37913fa078e..a860edd9e98 100644
--- a/django/contrib/formtools/tests/wizard/namedwizardtests/tests.py
+++ b/django/contrib/formtools/tests/wizard/namedwizardtests/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.core.urlresolvers import reverse
from django.http import QueryDict
from django.test import TestCase
@@ -51,8 +53,8 @@ class NamedWizardTests(object):
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['wizard']['steps'].current, 'form1')
self.assertEqual(response.context['wizard']['form'].errors,
- {'name': [u'This field is required.'],
- 'user': [u'This field is required.']})
+ {'name': ['This field is required.'],
+ 'user': ['This field is required.']})
def test_form_post_success(self):
response = self.client.post(
@@ -150,10 +152,10 @@ class NamedWizardTests(object):
self.assertEqual(all_data[1]['file1'].read(), open(__file__, 'rb').read())
del all_data[1]['file1']
self.assertEqual(all_data, [
- {'name': u'Pony', 'thirsty': True, 'user': self.testuser},
- {'address1': u'123 Main St', 'address2': u'Djangoland'},
- {'random_crap': u'blah blah'},
- [{'random_crap': u'blah blah'}, {'random_crap': u'blah blah'}]])
+ {'name': 'Pony', 'thirsty': True, 'user': self.testuser},
+ {'address1': '123 Main St', 'address2': 'Djangoland'},
+ {'random_crap': 'blah blah'},
+ [{'random_crap': 'blah blah'}, {'random_crap': 'blah blah'}]])
def test_cleaned_data(self):
response = self.client.get(
@@ -203,11 +205,11 @@ class NamedWizardTests(object):
del all_data['file1']
self.assertEqual(
all_data,
- {'name': u'Pony', 'thirsty': True, 'user': self.testuser,
- 'address1': u'123 Main St', 'address2': u'Djangoland',
- 'random_crap': u'blah blah', 'formset-form4': [
- {'random_crap': u'blah blah'},
- {'random_crap': u'blah blah'}
+ {'name': 'Pony', 'thirsty': True, 'user': self.testuser,
+ 'address1': '123 Main St', 'address2': 'Djangoland',
+ 'random_crap': 'blah blah', 'formset-form4': [
+ {'random_crap': 'blah blah'},
+ {'random_crap': 'blah blah'}
]})
def test_manipulated_data(self):
diff --git a/django/contrib/formtools/tests/wizard/wizardtests/tests.py b/django/contrib/formtools/tests/wizard/wizardtests/tests.py
index a9a81ba70fd..a35664b3225 100644
--- a/django/contrib/formtools/tests/wizard/wizardtests/tests.py
+++ b/django/contrib/formtools/tests/wizard/wizardtests/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import os
from django import forms
@@ -33,8 +35,8 @@ class WizardTests(object):
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['wizard']['steps'].current, 'form1')
self.assertEqual(response.context['wizard']['form'].errors,
- {'name': [u'This field is required.'],
- 'user': [u'This field is required.']})
+ {'name': ['This field is required.'],
+ 'user': ['This field is required.']})
def test_form_post_success(self):
response = self.client.post(self.wizard_url, self.wizard_step_data[0])
@@ -96,11 +98,11 @@ class WizardTests(object):
self.assertEqual(all_data[1]['file1'].read(), open(__file__, 'rb').read())
del all_data[1]['file1']
self.assertEqual(all_data, [
- {'name': u'Pony', 'thirsty': True, 'user': self.testuser},
- {'address1': u'123 Main St', 'address2': u'Djangoland'},
- {'random_crap': u'blah blah'},
- [{'random_crap': u'blah blah'},
- {'random_crap': u'blah blah'}]])
+ {'name': 'Pony', 'thirsty': True, 'user': self.testuser},
+ {'address1': '123 Main St', 'address2': 'Djangoland'},
+ {'random_crap': 'blah blah'},
+ [{'random_crap': 'blah blah'},
+ {'random_crap': 'blah blah'}]])
def test_cleaned_data(self):
response = self.client.get(self.wizard_url)
@@ -124,11 +126,11 @@ class WizardTests(object):
self.assertEqual(all_data['file1'].read(), open(__file__, 'rb').read())
del all_data['file1']
self.assertEqual(all_data, {
- 'name': u'Pony', 'thirsty': True, 'user': self.testuser,
- 'address1': u'123 Main St', 'address2': u'Djangoland',
- 'random_crap': u'blah blah', 'formset-form4': [
- {'random_crap': u'blah blah'},
- {'random_crap': u'blah blah'}]})
+ 'name': 'Pony', 'thirsty': True, 'user': self.testuser,
+ 'address1': '123 Main St', 'address2': 'Djangoland',
+ 'random_crap': 'blah blah', 'formset-form4': [
+ {'random_crap': 'blah blah'},
+ {'random_crap': 'blah blah'}]})
def test_manipulated_data(self):
response = self.client.get(self.wizard_url)
diff --git a/django/contrib/gis/feeds.py b/django/contrib/gis/feeds.py
index c14fb858a5e..d7c52bf0193 100644
--- a/django/contrib/gis/feeds.py
+++ b/django/contrib/gis/feeds.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.contrib.syndication.views import Feed as BaseFeed
from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed
@@ -13,7 +15,7 @@ class GeoFeedMixin(object):
a single white space. Given a tuple of coordinates, this will return
a unicode GeoRSS representation.
"""
- return u' '.join([u'%f %f' % (coord[1], coord[0]) for coord in coords])
+ return ' '.join(['%f %f' % (coord[1], coord[0]) for coord in coords])
def add_georss_point(self, handler, coords, w3c_geo=False):
"""
@@ -23,10 +25,10 @@ class GeoFeedMixin(object):
"""
if w3c_geo:
lon, lat = coords[:2]
- handler.addQuickElement(u'geo:lat', u'%f' % lat)
- handler.addQuickElement(u'geo:lon', u'%f' % lon)
+ handler.addQuickElement('geo:lat', '%f' % lat)
+ handler.addQuickElement('geo:lon', '%f' % lon)
else:
- handler.addQuickElement(u'georss:point', self.georss_coords((coords,)))
+ handler.addQuickElement('georss:point', self.georss_coords((coords,)))
def add_georss_element(self, handler, item, w3c_geo=False):
"""
@@ -57,7 +59,7 @@ class GeoFeedMixin(object):
# If a GeoRSS box was given via tuple.
if not box_coords is None:
if w3c_geo: raise ValueError('Cannot use simple GeoRSS box in W3C Geo feeds.')
- handler.addQuickElement(u'georss:box', self.georss_coords(box_coords))
+ handler.addQuickElement('georss:box', self.georss_coords(box_coords))
else:
# Getting the lower-case geometry type.
gtype = str(geom.geom_type).lower()
@@ -68,10 +70,10 @@ class GeoFeedMixin(object):
# For formatting consistent w/the GeoRSS simple standard:
# http://georss.org/1.0#simple
if gtype in ('linestring', 'linearring'):
- handler.addQuickElement(u'georss:line', self.georss_coords(geom.coords))
+ handler.addQuickElement('georss:line', self.georss_coords(geom.coords))
elif gtype in ('polygon',):
# Only support the exterior ring.
- handler.addQuickElement(u'georss:polygon', self.georss_coords(geom[0].coords))
+ handler.addQuickElement('georss:polygon', self.georss_coords(geom[0].coords))
else:
raise ValueError('Geometry type "%s" not supported.' % geom.geom_type)
@@ -79,7 +81,7 @@ class GeoFeedMixin(object):
class GeoRSSFeed(Rss201rev2Feed, GeoFeedMixin):
def rss_attributes(self):
attrs = super(GeoRSSFeed, self).rss_attributes()
- attrs[u'xmlns:georss'] = u'http://www.georss.org/georss'
+ attrs['xmlns:georss'] = 'http://www.georss.org/georss'
return attrs
def add_item_elements(self, handler, item):
@@ -93,7 +95,7 @@ class GeoRSSFeed(Rss201rev2Feed, GeoFeedMixin):
class GeoAtom1Feed(Atom1Feed, GeoFeedMixin):
def root_attributes(self):
attrs = super(GeoAtom1Feed, self).root_attributes()
- attrs[u'xmlns:georss'] = u'http://www.georss.org/georss'
+ attrs['xmlns:georss'] = 'http://www.georss.org/georss'
return attrs
def add_item_elements(self, handler, item):
@@ -107,7 +109,7 @@ class GeoAtom1Feed(Atom1Feed, GeoFeedMixin):
class W3CGeoFeed(Rss201rev2Feed, GeoFeedMixin):
def rss_attributes(self):
attrs = super(W3CGeoFeed, self).rss_attributes()
- attrs[u'xmlns:geo'] = u'http://www.w3.org/2003/01/geo/wgs84_pos#'
+ attrs['xmlns:geo'] = 'http://www.w3.org/2003/01/geo/wgs84_pos#'
return attrs
def add_item_elements(self, handler, item):
diff --git a/django/contrib/gis/forms/fields.py b/django/contrib/gis/forms/fields.py
index f806dcb3c62..432f0e18729 100644
--- a/django/contrib/gis/forms/fields.py
+++ b/django/contrib/gis/forms/fields.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django import forms
from django.utils.translation import ugettext_lazy as _
@@ -14,10 +16,10 @@ class GeometryField(forms.Field):
widget = forms.Textarea
default_error_messages = {
- 'no_geom' : _(u'No geometry value provided.'),
- 'invalid_geom' : _(u'Invalid geometry value.'),
- 'invalid_geom_type' : _(u'Invalid geometry type.'),
- 'transform_error' : _(u'An error occurred when transforming the geometry '
+ 'no_geom' : _('No geometry value provided.'),
+ 'invalid_geom' : _('Invalid geometry value.'),
+ 'invalid_geom_type' : _('Invalid geometry type.'),
+ 'transform_error' : _('An error occurred when transforming the geometry '
'to the SRID of the geometry form field.'),
}
diff --git a/django/contrib/gis/gdal/tests/test_envelope.py b/django/contrib/gis/gdal/tests/test_envelope.py
index 7574284bbad..07e12c0ca73 100644
--- a/django/contrib/gis/gdal/tests/test_envelope.py
+++ b/django/contrib/gis/gdal/tests/test_envelope.py
@@ -23,7 +23,7 @@ class EnvelopeTest(unittest.TestCase):
self.assertRaises(OGRException, Envelope, (0, 0, 5, 5, 3))
self.assertRaises(OGRException, Envelope, ())
self.assertRaises(ValueError, Envelope, 0, 'a', 5, 5)
- self.assertRaises(TypeError, Envelope, u'foo')
+ self.assertRaises(TypeError, Envelope, 'foo')
self.assertRaises(OGRException, Envelope, (1, 1, 0, 0))
try:
Envelope(0, 0, 0, 0)
diff --git a/django/contrib/gis/geoip/tests.py b/django/contrib/gis/geoip/tests.py
index a629d86bbfd..1d9132ba6f0 100644
--- a/django/contrib/gis/geoip/tests.py
+++ b/django/contrib/gis/geoip/tests.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import os
from django.conf import settings
from django.contrib.gis.geos import GEOSGeometry
@@ -99,13 +101,13 @@ class GeoIPTest(unittest.TestCase):
"Testing that GeoIP strings are properly encoded, see #16553."
g = GeoIP()
d = g.city('62.224.93.23')
- self.assertEqual(u'Sch\xf6mberg', d['city'])
+ self.assertEqual('Schümberg', d['city'])
def test06_unicode_query(self):
"Testing that GeoIP accepts unicode string queries, see #17059."
g = GeoIP()
- d = g.country(u'whitehouse.gov')
- self.assertEqual(u'US', d['country_code'])
+ d = g.country('whitehouse.gov')
+ self.assertEqual('US', d['country_code'])
def suite():
diff --git a/django/contrib/gis/sitemaps/views.py b/django/contrib/gis/sitemaps/views.py
index 3a9acad7b04..eb42d0cae88 100644
--- a/django/contrib/gis/sitemaps/views.py
+++ b/django/contrib/gis/sitemaps/views.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.http import HttpResponse, Http404
from django.template import loader
from django.contrib.sites.models import get_current_site
@@ -41,7 +43,7 @@ def sitemap(request, sitemaps, section=None):
maps, urls = [], []
if section is not None:
if section not in sitemaps:
- raise Http404(_(u"No sitemap available for section: %r") % section)
+ raise Http404(_("No sitemap available for section: %r") % section)
maps.append(sitemaps[section])
else:
maps = sitemaps.values()
@@ -55,9 +57,9 @@ def sitemap(request, sitemaps, section=None):
else:
urls.extend(site.get_urls(page=page, site=current_site))
except EmptyPage:
- raise Http404(_(u"Page %s empty") % page)
+ raise Http404(_("Page %s empty") % page)
except PageNotAnInteger:
- raise Http404(_(u"No page '%s'") % page)
+ raise Http404(_("No page '%s'") % page)
xml = smart_str(loader.render_to_string('gis/sitemaps/geo_sitemap.xml', {'urlset': urls}))
return HttpResponse(xml, content_type='application/xml')
diff --git a/django/contrib/gis/tests/geoapp/test_feeds.py b/django/contrib/gis/tests/geoapp/test_feeds.py
index 936c1ded46c..85e777ae78c 100644
--- a/django/contrib/gis/tests/geoapp/test_feeds.py
+++ b/django/contrib/gis/tests/geoapp/test_feeds.py
@@ -44,7 +44,7 @@ class GeoFeedTest(TestCase):
# Incrementing through the feeds.
for feed in [feed1, feed2]:
# Ensuring the georss namespace was added to the element.
- self.assertEqual(feed.getAttribute(u'xmlns:georss'), u'http://www.georss.org/georss')
+ self.assertEqual(feed.getAttribute('xmlns:georss'), 'http://www.georss.org/georss')
chan = feed.getElementsByTagName('channel')[0]
items = chan.getElementsByTagName('item')
self.assertEqual(len(items), City.objects.count())
@@ -64,7 +64,7 @@ class GeoFeedTest(TestCase):
for feed in [feed1, feed2]:
# Ensuring the georsss namespace was added to the element.
- self.assertEqual(feed.getAttribute(u'xmlns:georss'), u'http://www.georss.org/georss')
+ self.assertEqual(feed.getAttribute('xmlns:georss'), 'http://www.georss.org/georss')
entries = feed.getElementsByTagName('entry')
self.assertEqual(len(entries), City.objects.count())
@@ -77,7 +77,7 @@ class GeoFeedTest(TestCase):
doc = minidom.parseString(self.client.get('/feeds/w3cgeo1/').content)
feed = doc.firstChild
# Ensuring the geo namespace was added to the element.
- self.assertEqual(feed.getAttribute(u'xmlns:geo'), u'http://www.w3.org/2003/01/geo/wgs84_pos#')
+ self.assertEqual(feed.getAttribute('xmlns:geo'), 'http://www.w3.org/2003/01/geo/wgs84_pos#')
chan = feed.getElementsByTagName('channel')[0]
items = chan.getElementsByTagName('item')
self.assertEqual(len(items), City.objects.count())
diff --git a/django/contrib/gis/tests/geoapp/test_sitemaps.py b/django/contrib/gis/tests/geoapp/test_sitemaps.py
index a5c8f41ba4f..5f063dfba31 100644
--- a/django/contrib/gis/tests/geoapp/test_sitemaps.py
+++ b/django/contrib/gis/tests/geoapp/test_sitemaps.py
@@ -34,7 +34,7 @@ class GeoSitemapTest(TestCase):
# Getting the geo index.
doc = minidom.parseString(self.client.get('/sitemap.xml').content)
index = doc.firstChild
- self.assertEqual(index.getAttribute(u'xmlns'), u'http://www.sitemaps.org/schemas/sitemap/0.9')
+ self.assertEqual(index.getAttribute('xmlns'), 'http://www.sitemaps.org/schemas/sitemap/0.9')
self.assertEqual(3, len(index.getElementsByTagName('sitemap')))
def test_geositemap_kml(self):
@@ -44,8 +44,8 @@ class GeoSitemapTest(TestCase):
# Ensuring the right sitemaps namespaces are present.
urlset = doc.firstChild
- self.assertEqual(urlset.getAttribute(u'xmlns'), u'http://www.sitemaps.org/schemas/sitemap/0.9')
- self.assertEqual(urlset.getAttribute(u'xmlns:geo'), u'http://www.google.com/geo/schemas/sitemap/1.0')
+ self.assertEqual(urlset.getAttribute('xmlns'), 'http://www.sitemaps.org/schemas/sitemap/0.9')
+ self.assertEqual(urlset.getAttribute('xmlns:geo'), 'http://www.google.com/geo/schemas/sitemap/1.0')
urls = urlset.getElementsByTagName('url')
self.assertEqual(2, len(urls)) # Should only be 2 sitemaps.
@@ -84,8 +84,8 @@ class GeoSitemapTest(TestCase):
# Ensuring the right sitemaps namespaces are present.
urlset = doc.firstChild
- self.assertEqual(urlset.getAttribute(u'xmlns'), u'http://www.sitemaps.org/schemas/sitemap/0.9')
- self.assertEqual(urlset.getAttribute(u'xmlns:geo'), u'http://www.google.com/geo/schemas/sitemap/1.0')
+ self.assertEqual(urlset.getAttribute('xmlns'), 'http://www.sitemaps.org/schemas/sitemap/0.9')
+ self.assertEqual(urlset.getAttribute('xmlns:geo'), 'http://www.google.com/geo/schemas/sitemap/1.0')
# Making sure the correct number of feed URLs were included.
urls = urlset.getElementsByTagName('url')
diff --git a/django/contrib/gis/views.py b/django/contrib/gis/views.py
index fc51a0bf3aa..3fa8f044ded 100644
--- a/django/contrib/gis/views.py
+++ b/django/contrib/gis/views.py
@@ -1,10 +1,12 @@
+from __future__ import unicode_literals
+
from django.http import Http404
from django.utils.translation import ugettext as _
def feed(request, url, feed_dict=None):
"""Provided for backwards compatibility."""
if not feed_dict:
- raise Http404(_(u"No feeds are registered."))
+ raise Http404(_("No feeds are registered."))
try:
slug, param = url.split('/', 1)
@@ -14,7 +16,7 @@ def feed(request, url, feed_dict=None):
try:
f = feed_dict[slug]
except KeyError:
- raise Http404(_(u"Slug %r isn't registered.") % slug)
+ raise Http404(_("Slug %r isn't registered.") % slug)
instance = f()
instance.feed_url = getattr(f, 'feed_url', None) or request.path
diff --git a/django/contrib/humanize/templatetags/humanize.py b/django/contrib/humanize/templatetags/humanize.py
index b075ff05c7c..7a2e5147d8a 100644
--- a/django/contrib/humanize/templatetags/humanize.py
+++ b/django/contrib/humanize/templatetags/humanize.py
@@ -1,3 +1,4 @@
+from __future__ import unicode_literals
import re
from datetime import date, datetime, timedelta
@@ -23,8 +24,8 @@ def ordinal(value):
return value
suffixes = (_('th'), _('st'), _('nd'), _('rd'), _('th'), _('th'), _('th'), _('th'), _('th'), _('th'))
if value % 100 in (11, 12, 13): # special case
- return u"%d%s" % (value, suffixes[0])
- return u"%d%s" % (value, suffixes[value % 10])
+ return "%d%s" % (value, suffixes[0])
+ return "%d%s" % (value, suffixes[value % 10])
@register.filter(is_safe=True)
def intcomma(value, use_l10n=True):
@@ -161,11 +162,11 @@ def naturalday(value, arg=None):
today = datetime.now(tzinfo).date()
delta = value - today
if delta.days == 0:
- return _(u'today')
+ return _('today')
elif delta.days == 1:
- return _(u'tomorrow')
+ return _('tomorrow')
elif delta.days == -1:
- return _(u'yesterday')
+ return _('yesterday')
return defaultfilters.date(value, arg)
@register.filter
@@ -185,20 +186,20 @@ def naturaltime(value):
'naturaltime', '%(delta)s ago'
) % {'delta': defaultfilters.timesince(value)}
elif delta.seconds == 0:
- return _(u'now')
+ return _('now')
elif delta.seconds < 60:
return ungettext(
- u'a second ago', u'%(count)s seconds ago', delta.seconds
+ 'a second ago', '%(count)s seconds ago', delta.seconds
) % {'count': delta.seconds}
elif delta.seconds // 60 < 60:
count = delta.seconds // 60
return ungettext(
- u'a minute ago', u'%(count)s minutes ago', count
+ 'a minute ago', '%(count)s minutes ago', count
) % {'count': count}
else:
count = delta.seconds // 60 // 60
return ungettext(
- u'an hour ago', u'%(count)s hours ago', count
+ 'an hour ago', '%(count)s hours ago', count
) % {'count': count}
else:
delta = value - now
@@ -207,18 +208,18 @@ def naturaltime(value):
'naturaltime', '%(delta)s from now'
) % {'delta': defaultfilters.timeuntil(value)}
elif delta.seconds == 0:
- return _(u'now')
+ return _('now')
elif delta.seconds < 60:
return ungettext(
- u'a second from now', u'%(count)s seconds from now', delta.seconds
+ 'a second from now', '%(count)s seconds from now', delta.seconds
) % {'count': delta.seconds}
elif delta.seconds // 60 < 60:
count = delta.seconds // 60
return ungettext(
- u'a minute from now', u'%(count)s minutes from now', count
+ 'a minute from now', '%(count)s minutes from now', count
) % {'count': count}
else:
count = delta.seconds // 60 // 60
return ungettext(
- u'an hour from now', u'%(count)s hours from now', count
+ 'an hour from now', '%(count)s hours from now', count
) % {'count': count}
diff --git a/django/contrib/humanize/tests.py b/django/contrib/humanize/tests.py
index bf6684766bc..ecf4b83d6de 100644
--- a/django/contrib/humanize/tests.py
+++ b/django/contrib/humanize/tests.py
@@ -1,3 +1,4 @@
+from __future__ import unicode_literals
import datetime
import new
@@ -89,8 +90,8 @@ class HumanizeTests(TestCase):
def test_apnumber(self):
test_list = [str(x) for x in range(1, 11)]
test_list.append(None)
- result_list = (u'one', u'two', u'three', u'four', u'five', u'six',
- u'seven', u'eight', u'nine', u'10', None)
+ result_list = ('one', 'two', 'three', 'four', 'five', 'six',
+ 'seven', 'eight', 'nine', '10', None)
self.humanize_tester(test_list, result_list, 'apnumber')
@@ -99,12 +100,12 @@ class HumanizeTests(TestCase):
yesterday = today - datetime.timedelta(days=1)
tomorrow = today + datetime.timedelta(days=1)
someday = today - datetime.timedelta(days=10)
- notdate = u"I'm not a date value"
+ notdate = "I'm not a date value"
test_list = (today, yesterday, tomorrow, someday, notdate, None)
someday_result = defaultfilters.date(someday)
- result_list = (_(u'today'), _(u'yesterday'), _(u'tomorrow'),
- someday_result, u"I'm not a date value", None)
+ result_list = (_('today'), _('yesterday'), _('tomorrow'),
+ someday_result, "I'm not a date value", None)
self.humanize_tester(test_list, result_list, 'naturalday')
def test_naturalday_tz(self):
diff --git a/django/contrib/localflavor/ar/ar_provinces.py b/django/contrib/localflavor/ar/ar_provinces.py
index a0efd4ba33e..600ef1eb166 100644
--- a/django/contrib/localflavor/ar/ar_provinces.py
+++ b/django/contrib/localflavor/ar/ar_provinces.py
@@ -7,30 +7,31 @@ http://www.argentina.gov.ar/argentina/portal/paginas.dhtml?pagina=425
This exists in this standalone file so that it's only imported into memory
when explicitly needed.
"""
+from __future__ import unicode_literals
PROVINCE_CHOICES = (
- ('B', u'Buenos Aires'),
- ('K', u'Catamarca'),
- ('H', u'Chaco'),
- ('U', u'Chubut'),
- ('C', u'Ciudad Autónoma de Buenos Aires'),
- ('X', u'Córdoba'),
- ('W', u'Corrientes'),
- ('E', u'Entre Ríos'),
- ('P', u'Formosa'),
- ('Y', u'Jujuy'),
- ('L', u'La Pampa'),
- ('F', u'La Rioja'),
- ('M', u'Mendoza'),
- ('N', u'Misiones'),
- ('Q', u'Neuquén'),
- ('R', u'Río Negro'),
- ('A', u'Salta'),
- ('J', u'San Juan'),
- ('D', u'San Luis'),
- ('Z', u'Santa Cruz'),
- ('S', u'Santa Fe'),
- ('G', u'Santiago del Estero'),
- ('V', u'Tierra del Fuego, Antártida e Islas del Atlántico Sur'),
- ('T', u'Tucumán'),
+ ('B', 'Buenos Aires'),
+ ('K', 'Catamarca'),
+ ('H', 'Chaco'),
+ ('U', 'Chubut'),
+ ('C', 'Ciudad Autónoma de Buenos Aires'),
+ ('X', 'Córdoba'),
+ ('W', 'Corrientes'),
+ ('E', 'Entre Ríos'),
+ ('P', 'Formosa'),
+ ('Y', 'Jujuy'),
+ ('L', 'La Pampa'),
+ ('F', 'La Rioja'),
+ ('M', 'Mendoza'),
+ ('N', 'Misiones'),
+ ('Q', 'Neuquén'),
+ ('R', 'Río Negro'),
+ ('A', 'Salta'),
+ ('J', 'San Juan'),
+ ('D', 'San Luis'),
+ ('Z', 'Santa Cruz'),
+ ('S', 'Santa Fe'),
+ ('G', 'Santiago del Estero'),
+ ('V', 'Tierra del Fuego, Antártida e Islas del Atlántico Sur'),
+ ('T', 'Tucumán'),
)
diff --git a/django/contrib/localflavor/ar/forms.py b/django/contrib/localflavor/ar/forms.py
index 1805839ce4b..8e252beec9f 100644
--- a/django/contrib/localflavor/ar/forms.py
+++ b/django/contrib/localflavor/ar/forms.py
@@ -3,7 +3,7 @@
AR-specific Form helpers.
"""
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from django.contrib.localflavor.ar.ar_provinces import PROVINCE_CHOICES
from django.core.validators import EMPTY_VALUES
@@ -37,11 +37,11 @@ class ARPostalCodeField(RegexField):
def clean(self, value):
value = super(ARPostalCodeField, self).clean(value)
if value in EMPTY_VALUES:
- return u''
+ return ''
if len(value) not in (4, 8):
raise ValidationError(self.error_messages['invalid'])
if len(value) == 8:
- return u'%s%s%s' % (value[0].upper(), value[1:5], value[5:].upper())
+ return '%s%s%s' % (value[0].upper(), value[1:5], value[5:].upper())
return value
class ARDNIField(CharField):
@@ -63,7 +63,7 @@ class ARDNIField(CharField):
"""
value = super(ARDNIField, self).clean(value)
if value in EMPTY_VALUES:
- return u''
+ return ''
if not value.isdigit():
value = value.replace('.', '')
if not value.isdigit():
@@ -94,7 +94,7 @@ class ARCUITField(RegexField):
"""
value = super(ARCUITField, self).clean(value)
if value in EMPTY_VALUES:
- return u''
+ return ''
value, cd = self._canon(value)
if self._calc_cd(value) != cd:
raise ValidationError(self.error_messages['checksum'])
@@ -113,5 +113,5 @@ class ARCUITField(RegexField):
if check_digit == None:
check_digit = cuit[-1]
cuit = cuit[:-1]
- return u'%s-%s-%s' % (cuit[:2], cuit[2:], check_digit)
+ return '%s-%s-%s' % (cuit[:2], cuit[2:], check_digit)
diff --git a/django/contrib/localflavor/at/forms.py b/django/contrib/localflavor/at/forms.py
index 262641bf1f3..c531bec2e9a 100644
--- a/django/contrib/localflavor/at/forms.py
+++ b/django/contrib/localflavor/at/forms.py
@@ -1,7 +1,7 @@
"""
AT-specific Form helpers
"""
-
+from __future__ import unicode_literals
import re
from django.core.validators import EMPTY_VALUES
@@ -47,13 +47,13 @@ class ATSocialSecurityNumberField(Field):
"""
default_error_messages = {
- 'invalid': _(u'Enter a valid Austrian Social Security Number in XXXX XXXXXX format.'),
+ 'invalid': _('Enter a valid Austrian Social Security Number in XXXX XXXXXX format.'),
}
def clean(self, value):
value = super(ATSocialSecurityNumberField, self).clean(value)
if value in EMPTY_VALUES:
- return u""
+ return ""
if not re_ssn.search(value):
raise ValidationError(self.error_messages['invalid'])
sqnr, date = value.split(" ")
@@ -66,4 +66,4 @@ class ATSocialSecurityNumberField(Field):
res = res % 11
if res != int(check):
raise ValidationError(self.error_messages['invalid'])
- return u'%s%s %s'%(sqnr, check, date,)
+ return '%s%s %s'%(sqnr, check, date,)
diff --git a/django/contrib/localflavor/au/forms.py b/django/contrib/localflavor/au/forms.py
index 19df98dc336..34170fabc88 100644
--- a/django/contrib/localflavor/au/forms.py
+++ b/django/contrib/localflavor/au/forms.py
@@ -2,7 +2,7 @@
Australian-specific Form helpers
"""
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import re
@@ -34,7 +34,7 @@ class AUPostCodeField(RegexField):
class AUPhoneNumberField(Field):
"""Australian phone number field."""
default_error_messages = {
- 'invalid': u'Phone numbers must contain 10 digits.',
+ 'invalid': 'Phone numbers must contain 10 digits.',
}
def clean(self, value):
@@ -43,11 +43,11 @@ class AUPhoneNumberField(Field):
"""
super(AUPhoneNumberField, self).clean(value)
if value in EMPTY_VALUES:
- return u''
+ return ''
value = re.sub('(\(|\)|\s+|-)', '', smart_unicode(value))
phone_match = PHONE_DIGITS_RE.search(value)
if phone_match:
- return u'%s' % phone_match.group(1)
+ return '%s' % phone_match.group(1)
raise ValidationError(self.error_messages['invalid'])
diff --git a/django/contrib/localflavor/br/br_states.py b/django/contrib/localflavor/br/br_states.py
index 98e54bca2c6..ab37b1d2231 100644
--- a/django/contrib/localflavor/br/br_states.py
+++ b/django/contrib/localflavor/br/br_states.py
@@ -5,33 +5,34 @@ An alphabetical list of Brazilian states for use as `choices` in a formfield.
This exists in this standalone file so that it's only imported into memory
when explicitly needed.
"""
+from __future__ import unicode_literals
STATE_CHOICES = (
('AC', 'Acre'),
('AL', 'Alagoas'),
- ('AP', u'Amapá'),
+ ('AP', 'Amapá'),
('AM', 'Amazonas'),
('BA', 'Bahia'),
- ('CE', u'Ceará'),
+ ('CE', 'Ceará'),
('DF', 'Distrito Federal'),
- ('ES', u'Espírito Santo'),
- ('GO', u'Goiás'),
- ('MA', u'Maranhão'),
+ ('ES', 'Espírito Santo'),
+ ('GO', 'Goiás'),
+ ('MA', 'Maranhão'),
('MT', 'Mato Grosso'),
('MS', 'Mato Grosso do Sul'),
('MG', 'Minas Gerais'),
- ('PA', u'Pará'),
- ('PB', u'Paraíba'),
- ('PR', u'Paraná'),
+ ('PA', 'Pará'),
+ ('PB', 'Paraíba'),
+ ('PR', 'Paraná'),
('PE', 'Pernambuco'),
- ('PI', u'Piauí'),
+ ('PI', 'Piauí'),
('RJ', 'Rio de Janeiro'),
('RN', 'Rio Grande do Norte'),
('RS', 'Rio Grande do Sul'),
- ('RO', u'Rondônia'),
+ ('RO', 'Rondônia'),
('RR', 'Roraima'),
('SC', 'Santa Catarina'),
- ('SP', u'São Paulo'),
+ ('SP', 'São Paulo'),
('SE', 'Sergipe'),
('TO', 'Tocantins'),
)
diff --git a/django/contrib/localflavor/br/forms.py b/django/contrib/localflavor/br/forms.py
index 88c7f2efcc2..f287d46a9ae 100644
--- a/django/contrib/localflavor/br/forms.py
+++ b/django/contrib/localflavor/br/forms.py
@@ -3,7 +3,7 @@
BR-specific Form helpers
"""
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import re
@@ -34,11 +34,11 @@ class BRPhoneNumberField(Field):
def clean(self, value):
super(BRPhoneNumberField, self).clean(value)
if value in EMPTY_VALUES:
- return u''
+ return ''
value = re.sub('(\(|\)|\s+)', '', smart_unicode(value))
m = phone_digits_re.search(value)
if m:
- return u'%s-%s-%s' % (m.group(1), m.group(2), m.group(3))
+ return '%s-%s-%s' % (m.group(1), m.group(2), m.group(3))
raise ValidationError(self.error_messages['invalid'])
class BRStateSelect(Select):
@@ -55,7 +55,7 @@ class BRStateChoiceField(Field):
"""
widget = Select
default_error_messages = {
- 'invalid': _(u'Select a valid brazilian state. That state is not one of the available states.'),
+ 'invalid': _('Select a valid brazilian state. That state is not one of the available states.'),
}
def __init__(self, required=True, widget=None, label=None,
@@ -67,9 +67,9 @@ class BRStateChoiceField(Field):
def clean(self, value):
value = super(BRStateChoiceField, self).clean(value)
if value in EMPTY_VALUES:
- value = u''
+ value = ''
value = smart_unicode(value)
- if value == u'':
+ if value == '':
return value
valid_values = set([smart_unicode(k) for k, v in self.widget.choices])
if value not in valid_values:
@@ -105,7 +105,7 @@ class BRCPFField(CharField):
"""
value = super(BRCPFField, self).clean(value)
if value in EMPTY_VALUES:
- return u''
+ return ''
orig_value = value[:]
if not value.isdigit():
value = re.sub("[-\.]", "", value)
@@ -142,7 +142,7 @@ class BRCNPJField(Field):
"""
value = super(BRCNPJField, self).clean(value)
if value in EMPTY_VALUES:
- return u''
+ return ''
orig_value = value[:]
if not value.isdigit():
value = re.sub("[-/\.]", "", value)
diff --git a/django/contrib/localflavor/ca/forms.py b/django/contrib/localflavor/ca/forms.py
index c3be79968fd..ec66e665393 100644
--- a/django/contrib/localflavor/ca/forms.py
+++ b/django/contrib/localflavor/ca/forms.py
@@ -2,7 +2,7 @@
Canada-specific Form helpers
"""
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import re
@@ -26,7 +26,7 @@ class CAPostalCodeField(CharField):
http://www.canadapost.ca/tools/pg/manual/PGaddress-e.asp#1402170
"""
default_error_messages = {
- 'invalid': _(u'Enter a postal code in the format XXX XXX.'),
+ 'invalid': _('Enter a postal code in the format XXX XXX.'),
}
postcode_regex = re.compile(r'^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ]) *(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$')
@@ -34,7 +34,7 @@ class CAPostalCodeField(CharField):
def clean(self, value):
value = super(CAPostalCodeField, self).clean(value)
if value in EMPTY_VALUES:
- return u''
+ return ''
postcode = value.upper().strip()
m = self.postcode_regex.match(postcode)
if not m:
@@ -44,7 +44,7 @@ class CAPostalCodeField(CharField):
class CAPhoneNumberField(Field):
"""Canadian phone number field."""
default_error_messages = {
- 'invalid': _(u'Phone numbers must be in XXX-XXX-XXXX format.'),
+ 'invalid': _('Phone numbers must be in XXX-XXX-XXXX format.'),
}
def clean(self, value):
@@ -52,11 +52,11 @@ class CAPhoneNumberField(Field):
"""
super(CAPhoneNumberField, self).clean(value)
if value in EMPTY_VALUES:
- return u''
+ return ''
value = re.sub('(\(|\)|\s+)', '', smart_unicode(value))
m = phone_digits_re.search(value)
if m:
- return u'%s-%s-%s' % (m.group(1), m.group(2), m.group(3))
+ return '%s-%s-%s' % (m.group(1), m.group(2), m.group(3))
raise ValidationError(self.error_messages['invalid'])
class CAProvinceField(Field):
@@ -66,13 +66,13 @@ class CAProvinceField(Field):
abbreviation for the given province.
"""
default_error_messages = {
- 'invalid': _(u'Enter a Canadian province or territory.'),
+ 'invalid': _('Enter a Canadian province or territory.'),
}
def clean(self, value):
super(CAProvinceField, self).clean(value)
if value in EMPTY_VALUES:
- return u''
+ return ''
try:
value = value.strip().lower()
except AttributeError:
@@ -113,14 +113,14 @@ class CASocialInsuranceNumberField(Field):
def clean(self, value):
super(CASocialInsuranceNumberField, self).clean(value)
if value in EMPTY_VALUES:
- return u''
+ return ''
match = re.match(sin_re, value)
if not match:
raise ValidationError(self.error_messages['invalid'])
- number = u'%s-%s-%s' % (match.group(1), match.group(2), match.group(3))
- check_number = u'%s%s%s' % (match.group(1), match.group(2), match.group(3))
+ number = '%s-%s-%s' % (match.group(1), match.group(2), match.group(3))
+ check_number = '%s%s%s' % (match.group(1), match.group(2), match.group(3))
if not self.luhn_checksum_is_valid(check_number):
raise ValidationError(self.error_messages['invalid'])
return number
diff --git a/django/contrib/localflavor/ch/forms.py b/django/contrib/localflavor/ch/forms.py
index 649a98ab715..e844a3c57cf 100644
--- a/django/contrib/localflavor/ch/forms.py
+++ b/django/contrib/localflavor/ch/forms.py
@@ -2,7 +2,7 @@
Swiss-specific Form helpers
"""
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import re
@@ -40,11 +40,11 @@ class CHPhoneNumberField(Field):
def clean(self, value):
super(CHPhoneNumberField, self).clean(value)
if value in EMPTY_VALUES:
- return u''
+ return ''
value = re.sub('(\.|\s|/|-)', '', smart_unicode(value))
m = phone_digits_re.search(value)
if m:
- return u'%s %s %s %s' % (value[0:3], value[3:6], value[6:8], value[8:10])
+ return '%s %s %s %s' % (value[0:3], value[3:6], value[6:8], value[8:10])
raise ValidationError(self.error_messages['invalid'])
class CHStateSelect(Select):
@@ -102,7 +102,7 @@ class CHIdentityCardNumberField(Field):
def clean(self, value):
super(CHIdentityCardNumberField, self).clean(value)
if value in EMPTY_VALUES:
- return u''
+ return ''
match = re.match(id_re, value)
if not match:
@@ -118,5 +118,5 @@ class CHIdentityCardNumberField(Field):
if not self.has_valid_checksum(all_digits):
raise ValidationError(self.error_messages['invalid'])
- return u'%s%s%s' % (idnumber, pos9, checksum)
+ return '%s%s%s' % (idnumber, pos9, checksum)
diff --git a/django/contrib/localflavor/cl/cl_regions.py b/django/contrib/localflavor/cl/cl_regions.py
index 47db6d39125..d76f6ad8340 100644
--- a/django/contrib/localflavor/cl/cl_regions.py
+++ b/django/contrib/localflavor/cl/cl_regions.py
@@ -5,21 +5,22 @@ A list of Chilean regions as `choices` in a formfield.
This exists in this standalone file so that it's only imported into memory
when explicitly needed.
"""
+from __future__ import unicode_literals
REGION_CHOICES = (
- ('RM', u'Región Metropolitana de Santiago'),
- ('I', u'Región de Tarapacá'),
- ('II', u'Región de Antofagasta'),
- ('III', u'Región de Atacama'),
- ('IV', u'Región de Coquimbo'),
- ('V', u'Región de Valparaíso'),
- ('VI', u'Región del Libertador Bernardo O\'Higgins'),
- ('VII', u'Región del Maule'),
- ('VIII',u'Región del Bío Bío'),
- ('IX', u'Región de la Araucanía'),
- ('X', u'Región de los Lagos'),
- ('XI', u'Región de Aysén del General Carlos Ibáñez del Campo'),
- ('XII', u'Región de Magallanes y la Antártica Chilena'),
- ('XIV', u'Región de Los Ríos'),
- ('XV', u'Región de Arica-Parinacota'),
+ ('RM', 'Región Metropolitana de Santiago'),
+ ('I', 'Región de Tarapacá'),
+ ('II', 'Región de Antofagasta'),
+ ('III', 'Región de Atacama'),
+ ('IV', 'Región de Coquimbo'),
+ ('V', 'Región de Valparaíso'),
+ ('VI', 'Región del Libertador Bernardo O\'Higgins'),
+ ('VII', 'Región del Maule'),
+ ('VIII','Región del Bío Bío'),
+ ('IX', 'Región de la Araucanía'),
+ ('X', 'Región de los Lagos'),
+ ('XI', 'Región de Aysén del General Carlos Ibáñez del Campo'),
+ ('XII', 'Región de Magallanes y la Antártica Chilena'),
+ ('XIV', 'Región de Los Ríos'),
+ ('XV', 'Región de Arica-Parinacota'),
)
diff --git a/django/contrib/localflavor/cl/forms.py b/django/contrib/localflavor/cl/forms.py
index 7a9aa2da8ca..59911763828 100644
--- a/django/contrib/localflavor/cl/forms.py
+++ b/django/contrib/localflavor/cl/forms.py
@@ -2,15 +2,15 @@
Chile specific form helpers.
"""
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
-from django.contrib.localflavor.cl.cl_regions import REGION_CHOICES
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import RegexField, Select
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import smart_unicode
+from .cl_regions import REGION_CHOICES
class CLRegionSelect(Select):
"""
@@ -50,7 +50,7 @@ class CLRutField(RegexField):
"""
super(CLRutField, self).clean(value)
if value in EMPTY_VALUES:
- return u''
+ return ''
rut, verificador = self._canonify(value)
if self._algorithm(rut) == verificador:
return self._format(rut, verificador)
@@ -68,7 +68,7 @@ class CLRutField(RegexField):
multi += 1
if multi == 8:
multi = 2
- return u'0123456789K0'[11 - suma % 11]
+ return '0123456789K0'[11 - suma % 11]
def _canonify(self, rut):
"""
@@ -93,5 +93,5 @@ class CLRutField(RegexField):
else:
new_dot = pos - 3
code = code[:new_dot] + '.' + code[new_dot:]
- return u'%s-%s' % (code, verifier)
+ return '%s-%s' % (code, verifier)
diff --git a/django/contrib/localflavor/cn/cn_provinces.py b/django/contrib/localflavor/cn/cn_provinces.py
index fe0aa37cb64..c27cba64231 100644
--- a/django/contrib/localflavor/cn/cn_provinces.py
+++ b/django/contrib/localflavor/cn/cn_provinces.py
@@ -9,41 +9,41 @@ http://en.wikipedia.org/wiki/Province_%28China%29
http://en.wikipedia.org/wiki/Direct-controlled_municipality
http://en.wikipedia.org/wiki/Autonomous_regions_of_China
"""
-
+from __future__ import unicode_literals
CN_PROVINCE_CHOICES = (
- ("anhui", u"安徽"),
- ("beijing", u"北京"),
- ("chongqing", u"重庆"),
- ("fujian", u"福建"),
- ("gansu", u"甘肃"),
- ("guangdong", u"广东"),
- ("guangxi", u"广西壮族自治区"),
- ("guizhou", u"贵州"),
- ("hainan", u"海南"),
- ("hebei", u"河北"),
- ("heilongjiang", u"黑龙江"),
- ("henan", u"河南"),
- ("hongkong", u"香港"),
- ("hubei", u"湖北"),
- ("hunan", u"湖南"),
- ("jiangsu", u"江苏"),
- ("jiangxi", u"江西"),
- ("jilin", u"吉林"),
- ("liaoning", u"辽宁"),
- ("macao", u"澳门"),
- ("neimongol", u"内蒙古自治区"),
- ("ningxia", u"宁夏回族自治区"),
- ("qinghai", u"青海"),
- ("shaanxi", u"陕西"),
- ("shandong", u"山东"),
- ("shanghai", u"上海"),
- ("shanxi", u"山西"),
- ("sichuan", u"四川"),
- ("taiwan", u"台湾"),
- ("tianjin", u"天津"),
- ("xinjiang", u"新疆维吾尔自治区"),
- ("xizang", u"西藏自治区"),
- ("yunnan", u"云南"),
- ("zhejiang", u"浙江"),
+ ("anhui", "安徽"),
+ ("beijing", "北京"),
+ ("chongqing", "重庆"),
+ ("fujian", "福建"),
+ ("gansu", "甘肃"),
+ ("guangdong", "广东"),
+ ("guangxi", "广西壮族自治区"),
+ ("guizhou", "贵州"),
+ ("hainan", "海南"),
+ ("hebei", "河北"),
+ ("heilongjiang", "黑龙江"),
+ ("henan", "河南"),
+ ("hongkong", "香港"),
+ ("hubei", "湖北"),
+ ("hunan", "湖南"),
+ ("jiangsu", "江苏"),
+ ("jiangxi", "江西"),
+ ("jilin", "吉林"),
+ ("liaoning", "辽宁"),
+ ("macao", "澳门"),
+ ("neimongol", "内蒙古自治区"),
+ ("ningxia", "宁夏回族自治区"),
+ ("qinghai", "青海"),
+ ("shaanxi", "陕西"),
+ ("shandong", "山东"),
+ ("shanghai", "上海"),
+ ("shanxi", "山西"),
+ ("sichuan", "四川"),
+ ("taiwan", "台湾"),
+ ("tianjin", "天津"),
+ ("xinjiang", "新疆维吾尔自治区"),
+ ("xizang", "西藏自治区"),
+ ("yunnan", "云南"),
+ ("zhejiang", "浙江"),
)
diff --git a/django/contrib/localflavor/cn/forms.py b/django/contrib/localflavor/cn/forms.py
index af92ba06ecb..43adcf3f013 100644
--- a/django/contrib/localflavor/cn/forms.py
+++ b/django/contrib/localflavor/cn/forms.py
@@ -3,7 +3,7 @@
"""
Chinese-specific form helpers
"""
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import re
@@ -81,7 +81,7 @@ class CNPostCodeField(RegexField):
Valid code is XXXXXX where X is digit.
"""
default_error_messages = {
- 'invalid': _(u'Enter a post code in the format XXXXXX.'),
+ 'invalid': _('Enter a post code in the format XXXXXX.'),
}
def __init__(self, *args, **kwargs):
@@ -102,10 +102,10 @@ class CNIDCardField(CharField):
The checksum algorithm is described in GB11643-1999.
"""
default_error_messages = {
- 'invalid': _(u'ID Card Number consists of 15 or 18 digits.'),
- 'checksum': _(u'Invalid ID Card Number: Wrong checksum'),
- 'birthday': _(u'Invalid ID Card Number: Wrong birthdate'),
- 'location': _(u'Invalid ID Card Number: Wrong location code'),
+ 'invalid': _('ID Card Number consists of 15 or 18 digits.'),
+ 'checksum': _('Invalid ID Card Number: Wrong checksum'),
+ 'birthday': _('Invalid ID Card Number: Wrong birthdate'),
+ 'location': _('Invalid ID Card Number: Wrong location code'),
}
def __init__(self, max_length=18, min_length=15, *args, **kwargs):
@@ -119,7 +119,7 @@ class CNIDCardField(CharField):
# Check the length of the ID card number.
super(CNIDCardField, self).clean(value)
if not value:
- return u""
+ return ""
# Check whether this ID card number has valid format
if not re.match(ID_CARD_RE, value):
raise ValidationError(self.error_messages['invalid'])
@@ -133,7 +133,7 @@ class CNIDCardField(CharField):
value = value.upper()
if not self.has_valid_checksum(value):
raise ValidationError(self.error_messages['checksum'])
- return u'%s' % value
+ return '%s' % value
def has_valid_birthday(self, value):
"""
@@ -190,7 +190,7 @@ class CNPhoneNumberField(RegexField):
010-55555555-35
"""
default_error_messages = {
- 'invalid': _(u'Enter a valid phone number.'),
+ 'invalid': _('Enter a valid phone number.'),
}
def __init__(self, *args, **kwargs):
@@ -207,7 +207,7 @@ class CNCellNumberField(RegexField):
The length of the cell number should be 11.
"""
default_error_messages = {
- 'invalid': _(u'Enter a valid cell number.'),
+ 'invalid': _('Enter a valid cell number.'),
}
def __init__(self, *args, **kwargs):
diff --git a/django/contrib/localflavor/co/co_departments.py b/django/contrib/localflavor/co/co_departments.py
index f0989b6ba68..7168f54cc23 100644
--- a/django/contrib/localflavor/co/co_departments.py
+++ b/django/contrib/localflavor/co/co_departments.py
@@ -6,39 +6,40 @@ formfield.
This exists in this standalone file so that it's only
imported into memory when explicitly needed.
"""
+from __future__ import unicode_literals
DEPARTMENT_CHOICES = (
- ('AMA', u'Amazonas'),
- ('ANT', u'Antioquia'),
- ('ARA', u'Arauca'),
- ('ATL', u'Atlántico'),
- ('DC', u'Bogotá'),
- ('BOL', u'Bolívar'),
- ('BOY', u'Boyacá'),
- ('CAL', u'Caldas'),
- ('CAQ', u'Caquetá'),
- ('CAS', u'Casanare'),
- ('CAU', u'Cauca'),
- ('CES', u'Cesar'),
- ('CHO', u'Chocó'),
- ('COR', u'Córdoba'),
- ('CUN', u'Cundinamarca'),
- ('GUA', u'Guainía'),
- ('GUV', u'Guaviare'),
- ('HUI', u'Huila'),
- ('LAG', u'La Guajira'),
- ('MAG', u'Magdalena'),
- ('MET', u'Meta'),
- ('NAR', u'Nariño'),
- ('NSA', u'Norte de Santander'),
- ('PUT', u'Putumayo'),
- ('QUI', u'Quindío'),
- ('RIS', u'Risaralda'),
- ('SAP', u'San Andrés and Providencia'),
- ('SAN', u'Santander'),
- ('SUC', u'Sucre'),
- ('TOL', u'Tolima'),
- ('VAC', u'Valle del Cauca'),
- ('VAU', u'Vaupés'),
- ('VID', u'Vichada'),
+ ('AMA', 'Amazonas'),
+ ('ANT', 'Antioquia'),
+ ('ARA', 'Arauca'),
+ ('ATL', 'Atlántico'),
+ ('DC', 'Bogotá'),
+ ('BOL', 'Bolívar'),
+ ('BOY', 'Boyacá'),
+ ('CAL', 'Caldas'),
+ ('CAQ', 'Caquetá'),
+ ('CAS', 'Casanare'),
+ ('CAU', 'Cauca'),
+ ('CES', 'Cesar'),
+ ('CHO', 'Chocó'),
+ ('COR', 'Córdoba'),
+ ('CUN', 'Cundinamarca'),
+ ('GUA', 'Guainía'),
+ ('GUV', 'Guaviare'),
+ ('HUI', 'Huila'),
+ ('LAG', 'La Guajira'),
+ ('MAG', 'Magdalena'),
+ ('MET', 'Meta'),
+ ('NAR', 'Nariño'),
+ ('NSA', 'Norte de Santander'),
+ ('PUT', 'Putumayo'),
+ ('QUI', 'Quindío'),
+ ('RIS', 'Risaralda'),
+ ('SAP', 'San Andrés and Providencia'),
+ ('SAN', 'Santander'),
+ ('SUC', 'Sucre'),
+ ('TOL', 'Tolima'),
+ ('VAC', 'Valle del Cauca'),
+ ('VAU', 'Vaupés'),
+ ('VID', 'Vichada'),
)
diff --git a/django/contrib/localflavor/cz/forms.py b/django/contrib/localflavor/cz/forms.py
index f3676b230b0..c7e81e40371 100644
--- a/django/contrib/localflavor/cz/forms.py
+++ b/django/contrib/localflavor/cz/forms.py
@@ -2,7 +2,7 @@
Czech-specific form helpers
"""
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import re
@@ -29,7 +29,7 @@ class CZPostalCodeField(RegexField):
Valid form is XXXXX or XXX XX, where X represents integer.
"""
default_error_messages = {
- 'invalid': _(u'Enter a postal code in the format XXXXX or XXX XX.'),
+ 'invalid': _('Enter a postal code in the format XXXXX or XXX XX.'),
}
def __init__(self, max_length=None, min_length=None, *args, **kwargs):
@@ -49,15 +49,15 @@ class CZBirthNumberField(Field):
Czech birth number field.
"""
default_error_messages = {
- 'invalid_format': _(u'Enter a birth number in the format XXXXXX/XXXX or XXXXXXXXXX.'),
- 'invalid': _(u'Enter a valid birth number.'),
+ 'invalid_format': _('Enter a birth number in the format XXXXXX/XXXX or XXXXXXXXXX.'),
+ 'invalid': _('Enter a valid birth number.'),
}
def clean(self, value, gender=None):
super(CZBirthNumberField, self).clean(value)
if value in EMPTY_VALUES:
- return u''
+ return ''
match = re.match(birth_number, value)
if not match:
@@ -67,7 +67,7 @@ class CZBirthNumberField(Field):
# Three digits for verification number were used until 1. january 1954
if len(id) == 3:
- return u'%s' % value
+ return '%s' % value
# Birth number is in format YYMMDD. Females have month value raised by 50.
# In case that all possible number are already used (for given date),
@@ -90,7 +90,7 @@ class CZBirthNumberField(Field):
modulo = int(birth + id[:3]) % 11
if (modulo == int(id[-1])) or (modulo == 10 and id[-1] == '0'):
- return u'%s' % value
+ return '%s' % value
else:
raise ValidationError(self.error_messages['invalid'])
@@ -99,14 +99,14 @@ class CZICNumberField(Field):
Czech IC number field.
"""
default_error_messages = {
- 'invalid': _(u'Enter a valid IC number.'),
+ 'invalid': _('Enter a valid IC number.'),
}
def clean(self, value):
super(CZICNumberField, self).clean(value)
if value in EMPTY_VALUES:
- return u''
+ return ''
match = re.match(ic_number, value)
if not match:
@@ -130,7 +130,7 @@ class CZICNumberField(Field):
if (not remainder % 10 and check == 1) or \
(remainder == 1 and check == 0) or \
(check == (11 - remainder)):
- return u'%s' % value
+ return '%s' % value
raise ValidationError(self.error_messages['invalid'])
diff --git a/django/contrib/localflavor/de/forms.py b/django/contrib/localflavor/de/forms.py
index 80b6248ed44..a7891d117f7 100644
--- a/django/contrib/localflavor/de/forms.py
+++ b/django/contrib/localflavor/de/forms.py
@@ -2,7 +2,7 @@
DE-specific Form helpers
"""
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import re
@@ -68,7 +68,7 @@ class DEIdentityCardNumberField(Field):
def clean(self, value):
super(DEIdentityCardNumberField, self).clean(value)
if value in EMPTY_VALUES:
- return u''
+ return ''
match = re.match(id_re, value)
if not match:
raise ValidationError(self.error_messages['invalid'])
@@ -80,9 +80,9 @@ class DEIdentityCardNumberField(Field):
if residence == '0000000000' or birthday == '0000000' or validity == '0000000':
raise ValidationError(self.error_messages['invalid'])
- all_digits = u"%s%s%s%s" % (residence, birthday, validity, checksum)
+ all_digits = "%s%s%s%s" % (residence, birthday, validity, checksum)
if not self.has_valid_checksum(residence) or not self.has_valid_checksum(birthday) or \
not self.has_valid_checksum(validity) or not self.has_valid_checksum(all_digits):
raise ValidationError(self.error_messages['invalid'])
- return u'%s%s-%s-%s-%s' % (residence, origin, birthday, validity, checksum)
+ return '%s%s-%s-%s-%s' % (residence, origin, birthday, validity, checksum)
diff --git a/django/contrib/localflavor/de_CH/formats.py b/django/contrib/localflavor/de_CH/formats.py
index d4f324a422f..9d56f9f2989 100644
--- a/django/contrib/localflavor/de_CH/formats.py
+++ b/django/contrib/localflavor/de_CH/formats.py
@@ -4,6 +4,8 @@
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
+from __future__ import unicode_literals
+
DATE_FORMAT = 'j. F Y'
TIME_FORMAT = 'H:i:s'
DATETIME_FORMAT = 'j. F Y H:i:s'
@@ -39,5 +41,5 @@ DATETIME_INPUT_FORMATS = (
# For details, please refer to http://www.bk.admin.ch/dokumentation/sprachen/04915/05016/index.html?lang=de
# (in German) and the documentation
DECIMAL_SEPARATOR = ','
-THOUSAND_SEPARATOR = u'\xa0' # non-breaking space
+THOUSAND_SEPARATOR = '\xa0' # non-breaking space
NUMBER_GROUPING = 3
diff --git a/django/contrib/localflavor/ec/ec_provinces.py b/django/contrib/localflavor/ec/ec_provinces.py
index 7e55078be03..db25d26ff80 100644
--- a/django/contrib/localflavor/ec/ec_provinces.py
+++ b/django/contrib/localflavor/ec/ec_provinces.py
@@ -6,30 +6,31 @@ formfield.
This exists in this standalone file so that it's only
imported into memory when explicitly needed.
"""
+from __future__ import unicode_literals
PROVINCE_CHOICES = (
- ('A', u'Azuay'),
- ('B', u'Bolívar'),
- ('F', u'Cañar'),
- ('C', u'Carchi'),
- ('H', u'Chimborazo'),
- ('X', u'Cotopaxi'),
- ('O', u'El Oro'),
- ('E', u'Esmeraldas'),
- ('W', u'Galápagos'),
- ('G', u'Guayas'),
- ('I', u'Imbabura'),
- ('L', u'Loja'),
- ('R', u'Los Ríos'),
- ('M', u'Manabí'),
- ('S', u'Morona Santiago'),
- ('N', u'Napo'),
- ('D', u'Orellana'),
- ('Y', u'Pastaza'),
- ('P', u'Pichincha'),
- ('SE', u'Santa Elena'),
- ('SD', u'Santo Domingo de los Tsáchilas'),
- ('U', u'Sucumbíos'),
- ('T', u'Tungurahua'),
- ('Z', u'Zamora Chinchipe'),
+ ('A', 'Azuay'),
+ ('B', 'Bolívar'),
+ ('F', 'Cañar'),
+ ('C', 'Carchi'),
+ ('H', 'Chimborazo'),
+ ('X', 'Cotopaxi'),
+ ('O', 'El Oro'),
+ ('E', 'Esmeraldas'),
+ ('W', 'Galápagos'),
+ ('G', 'Guayas'),
+ ('I', 'Imbabura'),
+ ('L', 'Loja'),
+ ('R', 'Los Ríos'),
+ ('M', 'Manabí'),
+ ('S', 'Morona Santiago'),
+ ('N', 'Napo'),
+ ('D', 'Orellana'),
+ ('Y', 'Pastaza'),
+ ('P', 'Pichincha'),
+ ('SE', 'Santa Elena'),
+ ('SD', 'Santo Domingo de los Tsáchilas'),
+ ('U', 'Sucumbíos'),
+ ('T', 'Tungurahua'),
+ ('Z', 'Zamora Chinchipe'),
)
diff --git a/django/contrib/localflavor/es/forms.py b/django/contrib/localflavor/es/forms.py
index fe237270f52..b5e256ca44a 100644
--- a/django/contrib/localflavor/es/forms.py
+++ b/django/contrib/localflavor/es/forms.py
@@ -91,7 +91,7 @@ class ESIdentityCardNumberField(RegexField):
def clean(self, value):
super(ESIdentityCardNumberField, self).clean(value)
if value in EMPTY_VALUES:
- return u''
+ return ''
nif_get_checksum = lambda d: self.nif_control[int(d)%23]
value = value.upper().replace(' ', '').replace('-', '')
@@ -157,7 +157,7 @@ class ESCCCField(RegexField):
def clean(self, value):
super(ESCCCField, self).clean(value)
if value in EMPTY_VALUES:
- return u''
+ return ''
control_str = [1, 2, 4, 8, 5, 10, 9, 7, 3, 6]
m = re.match(r'^(\d{4})[ -]?(\d{4})[ -]?(\d{2})[ -]?(\d{10})$', value)
entity, office, checksum, account = m.groups()
diff --git a/django/contrib/localflavor/fi/fi_municipalities.py b/django/contrib/localflavor/fi/fi_municipalities.py
index 4b8b886b8bb..6f90e5e02b5 100644
--- a/django/contrib/localflavor/fi/fi_municipalities.py
+++ b/django/contrib/localflavor/fi/fi_municipalities.py
@@ -7,347 +7,349 @@ This exists in this standalone file so that it's only imported into memory
when explicitly needed.
"""
+from __future__ import unicode_literals
+
MUNICIPALITY_CHOICES = (
- ('akaa', u"Akaa"),
- ('alajarvi', u"Alajärvi"),
- ('alavieska', u"Alavieska"),
- ('alavus', u"Alavus"),
- ('artjarvi', u"Artjärvi"),
- ('asikkala', u"Asikkala"),
- ('askola', u"Askola"),
- ('aura', u"Aura"),
- ('brando', u"Brändö"),
- ('eckero', u"Eckerö"),
- ('enonkoski', u"Enonkoski"),
- ('enontekio', u"Enontekiö"),
- ('espoo', u"Espoo"),
- ('eura', u"Eura"),
- ('eurajoki', u"Eurajoki"),
- ('evijarvi', u"Evijärvi"),
- ('finstrom', u"Finström"),
- ('forssa', u"Forssa"),
- ('foglo', u"Föglö"),
- ('geta', u"Geta"),
- ('haapajarvi', u"Haapajärvi"),
- ('haapavesi', u"Haapavesi"),
- ('hailuoto', u"Hailuoto"),
- ('halsua', u"Halsua"),
- ('hamina', u"Hamina"),
- ('hammarland', u"Hammarland"),
- ('hankasalmi', u"Hankasalmi"),
- ('hanko', u"Hanko"),
- ('harjavalta', u"Harjavalta"),
- ('hartola', u"Hartola"),
- ('hattula', u"Hattula"),
- ('haukipudas', u"Haukipudas"),
- ('hausjarvi', u"Hausjärvi"),
- ('heinola', u"Heinola"),
- ('heinavesi', u"Heinävesi"),
- ('helsinki', u"Helsinki"),
- ('hirvensalmi', u"Hirvensalmi"),
- ('hollola', u"Hollola"),
- ('honkajoki', u"Honkajoki"),
- ('huittinen', u"Huittinen"),
- ('humppila', u"Humppila"),
- ('hyrynsalmi', u"Hyrynsalmi"),
- ('hyvinkaa', u"Hyvinkää"),
- ('hameenkoski', u"Hämeenkoski"),
- ('hameenkyro', u"Hämeenkyrö"),
- ('hameenlinna', u"Hämeenlinna"),
- ('ii', u"Ii"),
- ('iisalmi', u"Iisalmi"),
- ('iitti', u"Iitti"),
- ('ikaalinen', u"Ikaalinen"),
- ('ilmajoki', u"Ilmajoki"),
- ('ilomantsi', u"Ilomantsi"),
- ('imatra', u"Imatra"),
- ('inari', u"Inari"),
- ('inkoo', u"Inkoo"),
- ('isojoki', u"Isojoki"),
- ('isokyro', u"Isokyrö"),
- ('jalasjarvi', u"Jalasjärvi"),
- ('janakkala', u"Janakkala"),
- ('joensuu', u"Joensuu"),
- ('jokioinen', u"Jokioinen"),
- ('jomala', u"Jomala"),
- ('joroinen', u"Joroinen"),
- ('joutsa', u"Joutsa"),
- ('juankoski', u"Juankoski"),
- ('juuka', u"Juuka"),
- ('juupajoki', u"Juupajoki"),
- ('juva', u"Juva"),
- ('jyvaskyla', u"Jyväskylä"),
- ('jamijarvi', u"Jämijärvi"),
- ('jamsa', u"Jämsä"),
- ('jarvenpaa', u"Järvenpää"),
- ('kaarina', u"Kaarina"),
- ('kaavi', u"Kaavi"),
- ('kajaani', u"Kajaani"),
- ('kalajoki', u"Kalajoki"),
- ('kangasala', u"Kangasala"),
- ('kangasniemi', u"Kangasniemi"),
- ('kankaanpaa', u"Kankaanpää"),
- ('kannonkoski', u"Kannonkoski"),
- ('kannus', u"Kannus"),
- ('karijoki', u"Karijoki"),
- ('karjalohja', u"Karjalohja"),
- ('karkkila', u"Karkkila"),
- ('karstula', u"Karstula"),
- ('karttula', u"Karttula"),
- ('karvia', u"Karvia"),
- ('kaskinen', u"Kaskinen"),
- ('kauhajoki', u"Kauhajoki"),
- ('kauhava', u"Kauhava"),
- ('kauniainen', u"Kauniainen"),
- ('kaustinen', u"Kaustinen"),
- ('keitele', u"Keitele"),
- ('kemi', u"Kemi"),
- ('kemijarvi', u"Kemijärvi"),
- ('keminmaa', u"Keminmaa"),
- ('kemionsaari', u"Kemiönsaari"),
- ('kempele', u"Kempele"),
- ('kerava', u"Kerava"),
- ('kerimaki', u"Kerimäki"),
- ('kesalahti', u"Kesälahti"),
- ('keuruu', u"Keuruu"),
- ('kihnio', u"Kihniö"),
- ('kiikoinen', u"Kiikoinen"),
- ('kiiminki', u"Kiiminki"),
- ('kinnula', u"Kinnula"),
- ('kirkkonummi', u"Kirkkonummi"),
- ('kitee', u"Kitee"),
- ('kittila', u"Kittilä"),
- ('kiuruvesi', u"Kiuruvesi"),
- ('kivijarvi', u"Kivijärvi"),
- ('kokemaki', u"Kokemäki"),
- ('kokkola', u"Kokkola"),
- ('kolari', u"Kolari"),
- ('konnevesi', u"Konnevesi"),
- ('kontiolahti', u"Kontiolahti"),
- ('korsnas', u"Korsnäs"),
- ('koskitl', u"Koski Tl"),
- ('kotka', u"Kotka"),
- ('kouvola', u"Kouvola"),
- ('kristiinankaupunki', u"Kristiinankaupunki"),
- ('kruunupyy', u"Kruunupyy"),
- ('kuhmalahti', u"Kuhmalahti"),
- ('kuhmo', u"Kuhmo"),
- ('kuhmoinen', u"Kuhmoinen"),
- ('kumlinge', u"Kumlinge"),
- ('kuopio', u"Kuopio"),
- ('kuortane', u"Kuortane"),
- ('kurikka', u"Kurikka"),
- ('kustavi', u"Kustavi"),
- ('kuusamo', u"Kuusamo"),
- ('kylmakoski', u"Kylmäkoski"),
- ('kyyjarvi', u"Kyyjärvi"),
- ('karkola', u"Kärkölä"),
- ('karsamaki', u"Kärsämäki"),
- ('kokar', u"Kökar"),
- ('koylio', u"Köyliö"),
- ('lahti', u"Lahti"),
- ('laihia', u"Laihia"),
- ('laitila', u"Laitila"),
- ('lapinjarvi', u"Lapinjärvi"),
- ('lapinlahti', u"Lapinlahti"),
- ('lappajarvi', u"Lappajärvi"),
- ('lappeenranta', u"Lappeenranta"),
- ('lapua', u"Lapua"),
- ('laukaa', u"Laukaa"),
- ('lavia', u"Lavia"),
- ('lemi', u"Lemi"),
- ('lemland', u"Lemland"),
- ('lempaala', u"Lempäälä"),
- ('leppavirta', u"Leppävirta"),
- ('lestijarvi', u"Lestijärvi"),
- ('lieksa', u"Lieksa"),
- ('lieto', u"Lieto"),
- ('liminka', u"Liminka"),
- ('liperi', u"Liperi"),
- ('lohja', u"Lohja"),
- ('loimaa', u"Loimaa"),
- ('loppi', u"Loppi"),
- ('loviisa', u"Loviisa"),
- ('luhanka', u"Luhanka"),
- ('lumijoki', u"Lumijoki"),
- ('lumparland', u"Lumparland"),
- ('luoto', u"Luoto"),
- ('luumaki', u"Luumäki"),
- ('luvia', u"Luvia"),
- ('lansi-turunmaa', u"Länsi-Turunmaa"),
- ('maalahti', u"Maalahti"),
- ('maaninka', u"Maaninka"),
- ('maarianhamina', u"Maarianhamina"),
- ('marttila', u"Marttila"),
- ('masku', u"Masku"),
- ('merijarvi', u"Merijärvi"),
- ('merikarvia', u"Merikarvia"),
- ('miehikkala', u"Miehikkälä"),
- ('mikkeli', u"Mikkeli"),
- ('muhos', u"Muhos"),
- ('multia', u"Multia"),
- ('muonio', u"Muonio"),
- ('mustasaari', u"Mustasaari"),
- ('muurame', u"Muurame"),
- ('mynamaki', u"Mynämäki"),
- ('myrskyla', u"Myrskylä"),
- ('mantsala', u"Mäntsälä"),
- ('mantta-vilppula', u"Mänttä-Vilppula"),
- ('mantyharju', u"Mäntyharju"),
- ('naantali', u"Naantali"),
- ('nakkila', u"Nakkila"),
- ('nastola', u"Nastola"),
- ('nilsia', u"Nilsiä"),
- ('nivala', u"Nivala"),
- ('nokia', u"Nokia"),
- ('nousiainen', u"Nousiainen"),
- ('nummi-pusula', u"Nummi-Pusula"),
- ('nurmes', u"Nurmes"),
- ('nurmijarvi', u"Nurmijärvi"),
- ('narpio', u"Närpiö"),
- ('oravainen', u"Oravainen"),
- ('orimattila', u"Orimattila"),
- ('oripaa', u"Oripää"),
- ('orivesi', u"Orivesi"),
- ('oulainen', u"Oulainen"),
- ('oulu', u"Oulu"),
- ('oulunsalo', u"Oulunsalo"),
- ('outokumpu', u"Outokumpu"),
- ('padasjoki', u"Padasjoki"),
- ('paimio', u"Paimio"),
- ('paltamo', u"Paltamo"),
- ('parikkala', u"Parikkala"),
- ('parkano', u"Parkano"),
- ('pedersore', u"Pedersöre"),
- ('pelkosenniemi', u"Pelkosenniemi"),
- ('pello', u"Pello"),
- ('perho', u"Perho"),
- ('pertunmaa', u"Pertunmaa"),
- ('petajavesi', u"Petäjävesi"),
- ('pieksamaki', u"Pieksämäki"),
- ('pielavesi', u"Pielavesi"),
- ('pietarsaari', u"Pietarsaari"),
- ('pihtipudas', u"Pihtipudas"),
- ('pirkkala', u"Pirkkala"),
- ('polvijarvi', u"Polvijärvi"),
- ('pomarkku', u"Pomarkku"),
- ('pori', u"Pori"),
- ('pornainen', u"Pornainen"),
- ('porvoo', u"Porvoo"),
- ('posio', u"Posio"),
- ('pudasjarvi', u"Pudasjärvi"),
- ('pukkila', u"Pukkila"),
- ('punkaharju', u"Punkaharju"),
- ('punkalaidun', u"Punkalaidun"),
- ('puolanka', u"Puolanka"),
- ('puumala', u"Puumala"),
- ('pyhtaa', u"Pyhtää"),
- ('pyhajoki', u"Pyhäjoki"),
- ('pyhajarvi', u"Pyhäjärvi"),
- ('pyhanta', u"Pyhäntä"),
- ('pyharanta', u"Pyhäranta"),
- ('palkane', u"Pälkäne"),
- ('poytya', u"Pöytyä"),
- ('raahe', u"Raahe"),
- ('raasepori', u"Raasepori"),
- ('raisio', u"Raisio"),
- ('rantasalmi', u"Rantasalmi"),
- ('ranua', u"Ranua"),
- ('rauma', u"Rauma"),
- ('rautalampi', u"Rautalampi"),
- ('rautavaara', u"Rautavaara"),
- ('rautjarvi', u"Rautjärvi"),
- ('reisjarvi', u"Reisjärvi"),
- ('riihimaki', u"Riihimäki"),
- ('ristiina', u"Ristiina"),
- ('ristijarvi', u"Ristijärvi"),
- ('rovaniemi', u"Rovaniemi"),
- ('ruokolahti', u"Ruokolahti"),
- ('ruovesi', u"Ruovesi"),
- ('rusko', u"Rusko"),
- ('raakkyla', u"Rääkkylä"),
- ('saarijarvi', u"Saarijärvi"),
- ('salla', u"Salla"),
- ('salo', u"Salo"),
- ('saltvik', u"Saltvik"),
- ('sastamala', u"Sastamala"),
- ('sauvo', u"Sauvo"),
- ('savitaipale', u"Savitaipale"),
- ('savonlinna', u"Savonlinna"),
- ('savukoski', u"Savukoski"),
- ('seinajoki', u"Seinäjoki"),
- ('sievi', u"Sievi"),
- ('siikainen', u"Siikainen"),
- ('siikajoki', u"Siikajoki"),
- ('siikalatva', u"Siikalatva"),
- ('siilinjarvi', u"Siilinjärvi"),
- ('simo', u"Simo"),
- ('sipoo', u"Sipoo"),
- ('siuntio', u"Siuntio"),
- ('sodankyla', u"Sodankylä"),
- ('soini', u"Soini"),
- ('somero', u"Somero"),
- ('sonkajarvi', u"Sonkajärvi"),
- ('sotkamo', u"Sotkamo"),
- ('sottunga', u"Sottunga"),
- ('sulkava', u"Sulkava"),
- ('sund', u"Sund"),
- ('suomenniemi', u"Suomenniemi"),
- ('suomussalmi', u"Suomussalmi"),
- ('suonenjoki', u"Suonenjoki"),
- ('sysma', u"Sysmä"),
- ('sakyla', u"Säkylä"),
- ('taipalsaari', u"Taipalsaari"),
- ('taivalkoski', u"Taivalkoski"),
- ('taivassalo', u"Taivassalo"),
- ('tammela', u"Tammela"),
- ('tampere', u"Tampere"),
- ('tarvasjoki', u"Tarvasjoki"),
- ('tervo', u"Tervo"),
- ('tervola', u"Tervola"),
- ('teuva', u"Teuva"),
- ('tohmajarvi', u"Tohmajärvi"),
- ('toholampi', u"Toholampi"),
- ('toivakka', u"Toivakka"),
- ('tornio', u"Tornio"),
- ('turku', u"Turku"),
- ('tuusniemi', u"Tuusniemi"),
- ('tuusula', u"Tuusula"),
- ('tyrnava', u"Tyrnävä"),
- ('toysa', u"Töysä"),
- ('ulvila', u"Ulvila"),
- ('urjala', u"Urjala"),
- ('utajarvi', u"Utajärvi"),
- ('utsjoki', u"Utsjoki"),
- ('uurainen', u"Uurainen"),
- ('uusikaarlepyy', u"Uusikaarlepyy"),
- ('uusikaupunki', u"Uusikaupunki"),
- ('vaala', u"Vaala"),
- ('vaasa', u"Vaasa"),
- ('valkeakoski', u"Valkeakoski"),
- ('valtimo', u"Valtimo"),
- ('vantaa', u"Vantaa"),
- ('varkaus', u"Varkaus"),
- ('varpaisjarvi', u"Varpaisjärvi"),
- ('vehmaa', u"Vehmaa"),
- ('vesanto', u"Vesanto"),
- ('vesilahti', u"Vesilahti"),
- ('veteli', u"Veteli"),
- ('vierema', u"Vieremä"),
- ('vihanti', u"Vihanti"),
- ('vihti', u"Vihti"),
- ('viitasaari', u"Viitasaari"),
- ('vimpeli', u"Vimpeli"),
- ('virolahti', u"Virolahti"),
- ('virrat', u"Virrat"),
- ('vardo', u"Vårdö"),
- ('vahakyro', u"Vähäkyrö"),
- ('voyri-maksamaa', u"Vöyri-Maksamaa"),
- ('yli-ii', u"Yli-Ii"),
- ('ylitornio', u"Ylitornio"),
- ('ylivieska', u"Ylivieska"),
- ('ylojarvi', u"Ylöjärvi"),
- ('ypaja', u"Ypäjä"),
- ('ahtari', u"Ähtäri"),
- ('aanekoski', u"Äänekoski")
-)
\ No newline at end of file
+ ('akaa', "Akaa"),
+ ('alajarvi', "Alajärvi"),
+ ('alavieska', "Alavieska"),
+ ('alavus', "Alavus"),
+ ('artjarvi', "Artjärvi"),
+ ('asikkala', "Asikkala"),
+ ('askola', "Askola"),
+ ('aura', "Aura"),
+ ('brando', "Brändö"),
+ ('eckero', "Eckerö"),
+ ('enonkoski', "Enonkoski"),
+ ('enontekio', "Enontekiö"),
+ ('espoo', "Espoo"),
+ ('eura', "Eura"),
+ ('eurajoki', "Eurajoki"),
+ ('evijarvi', "Evijärvi"),
+ ('finstrom', "Finström"),
+ ('forssa', "Forssa"),
+ ('foglo', "Föglö"),
+ ('geta', "Geta"),
+ ('haapajarvi', "Haapajärvi"),
+ ('haapavesi', "Haapavesi"),
+ ('hailuoto', "Hailuoto"),
+ ('halsua', "Halsua"),
+ ('hamina', "Hamina"),
+ ('hammarland', "Hammarland"),
+ ('hankasalmi', "Hankasalmi"),
+ ('hanko', "Hanko"),
+ ('harjavalta', "Harjavalta"),
+ ('hartola', "Hartola"),
+ ('hattula', "Hattula"),
+ ('haukipudas', "Haukipudas"),
+ ('hausjarvi', "Hausjärvi"),
+ ('heinola', "Heinola"),
+ ('heinavesi', "Heinävesi"),
+ ('helsinki', "Helsinki"),
+ ('hirvensalmi', "Hirvensalmi"),
+ ('hollola', "Hollola"),
+ ('honkajoki', "Honkajoki"),
+ ('huittinen', "Huittinen"),
+ ('humppila', "Humppila"),
+ ('hyrynsalmi', "Hyrynsalmi"),
+ ('hyvinkaa', "Hyvinkää"),
+ ('hameenkoski', "Hämeenkoski"),
+ ('hameenkyro', "Hämeenkyrö"),
+ ('hameenlinna', "Hämeenlinna"),
+ ('ii', "Ii"),
+ ('iisalmi', "Iisalmi"),
+ ('iitti', "Iitti"),
+ ('ikaalinen', "Ikaalinen"),
+ ('ilmajoki', "Ilmajoki"),
+ ('ilomantsi', "Ilomantsi"),
+ ('imatra', "Imatra"),
+ ('inari', "Inari"),
+ ('inkoo', "Inkoo"),
+ ('isojoki', "Isojoki"),
+ ('isokyro', "Isokyrö"),
+ ('jalasjarvi', "Jalasjärvi"),
+ ('janakkala', "Janakkala"),
+ ('joensuu', "Joensuu"),
+ ('jokioinen', "Jokioinen"),
+ ('jomala', "Jomala"),
+ ('joroinen', "Joroinen"),
+ ('joutsa', "Joutsa"),
+ ('juankoski', "Juankoski"),
+ ('juuka', "Juuka"),
+ ('juupajoki', "Juupajoki"),
+ ('juva', "Juva"),
+ ('jyvaskyla', "Jyväskylä"),
+ ('jamijarvi', "Jämijärvi"),
+ ('jamsa', "Jämsä"),
+ ('jarvenpaa', "Järvenpää"),
+ ('kaarina', "Kaarina"),
+ ('kaavi', "Kaavi"),
+ ('kajaani', "Kajaani"),
+ ('kalajoki', "Kalajoki"),
+ ('kangasala', "Kangasala"),
+ ('kangasniemi', "Kangasniemi"),
+ ('kankaanpaa', "Kankaanpää"),
+ ('kannonkoski', "Kannonkoski"),
+ ('kannus', "Kannus"),
+ ('karijoki', "Karijoki"),
+ ('karjalohja', "Karjalohja"),
+ ('karkkila', "Karkkila"),
+ ('karstula', "Karstula"),
+ ('karttula', "Karttula"),
+ ('karvia', "Karvia"),
+ ('kaskinen', "Kaskinen"),
+ ('kauhajoki', "Kauhajoki"),
+ ('kauhava', "Kauhava"),
+ ('kauniainen', "Kauniainen"),
+ ('kaustinen', "Kaustinen"),
+ ('keitele', "Keitele"),
+ ('kemi', "Kemi"),
+ ('kemijarvi', "Kemijärvi"),
+ ('keminmaa', "Keminmaa"),
+ ('kemionsaari', "Kemiönsaari"),
+ ('kempele', "Kempele"),
+ ('kerava', "Kerava"),
+ ('kerimaki', "Kerimäki"),
+ ('kesalahti', "Kesälahti"),
+ ('keuruu', "Keuruu"),
+ ('kihnio', "Kihniö"),
+ ('kiikoinen', "Kiikoinen"),
+ ('kiiminki', "Kiiminki"),
+ ('kinnula', "Kinnula"),
+ ('kirkkonummi', "Kirkkonummi"),
+ ('kitee', "Kitee"),
+ ('kittila', "Kittilä"),
+ ('kiuruvesi', "Kiuruvesi"),
+ ('kivijarvi', "Kivijärvi"),
+ ('kokemaki', "Kokemäki"),
+ ('kokkola', "Kokkola"),
+ ('kolari', "Kolari"),
+ ('konnevesi', "Konnevesi"),
+ ('kontiolahti', "Kontiolahti"),
+ ('korsnas', "Korsnäs"),
+ ('koskitl', "Koski Tl"),
+ ('kotka', "Kotka"),
+ ('kouvola', "Kouvola"),
+ ('kristiinankaupunki', "Kristiinankaupunki"),
+ ('kruunupyy', "Kruunupyy"),
+ ('kuhmalahti', "Kuhmalahti"),
+ ('kuhmo', "Kuhmo"),
+ ('kuhmoinen', "Kuhmoinen"),
+ ('kumlinge', "Kumlinge"),
+ ('kuopio', "Kuopio"),
+ ('kuortane', "Kuortane"),
+ ('kurikka', "Kurikka"),
+ ('kustavi', "Kustavi"),
+ ('kuusamo', "Kuusamo"),
+ ('kylmakoski', "Kylmäkoski"),
+ ('kyyjarvi', "Kyyjärvi"),
+ ('karkola', "Kärkölä"),
+ ('karsamaki', "Kärsämäki"),
+ ('kokar', "Kökar"),
+ ('koylio', "Köyliö"),
+ ('lahti', "Lahti"),
+ ('laihia', "Laihia"),
+ ('laitila', "Laitila"),
+ ('lapinjarvi', "Lapinjärvi"),
+ ('lapinlahti', "Lapinlahti"),
+ ('lappajarvi', "Lappajärvi"),
+ ('lappeenranta', "Lappeenranta"),
+ ('lapua', "Lapua"),
+ ('laukaa', "Laukaa"),
+ ('lavia', "Lavia"),
+ ('lemi', "Lemi"),
+ ('lemland', "Lemland"),
+ ('lempaala', "Lempäälä"),
+ ('leppavirta', "Leppävirta"),
+ ('lestijarvi', "Lestijärvi"),
+ ('lieksa', "Lieksa"),
+ ('lieto', "Lieto"),
+ ('liminka', "Liminka"),
+ ('liperi', "Liperi"),
+ ('lohja', "Lohja"),
+ ('loimaa', "Loimaa"),
+ ('loppi', "Loppi"),
+ ('loviisa', "Loviisa"),
+ ('luhanka', "Luhanka"),
+ ('lumijoki', "Lumijoki"),
+ ('lumparland', "Lumparland"),
+ ('luoto', "Luoto"),
+ ('luumaki', "Luumäki"),
+ ('luvia', "Luvia"),
+ ('lansi-turunmaa', "Länsi-Turunmaa"),
+ ('maalahti', "Maalahti"),
+ ('maaninka', "Maaninka"),
+ ('maarianhamina', "Maarianhamina"),
+ ('marttila', "Marttila"),
+ ('masku', "Masku"),
+ ('merijarvi', "Merijärvi"),
+ ('merikarvia', "Merikarvia"),
+ ('miehikkala', "Miehikkälä"),
+ ('mikkeli', "Mikkeli"),
+ ('muhos', "Muhos"),
+ ('multia', "Multia"),
+ ('muonio', "Muonio"),
+ ('mustasaari', "Mustasaari"),
+ ('muurame', "Muurame"),
+ ('mynamaki', "Mynämäki"),
+ ('myrskyla', "Myrskylä"),
+ ('mantsala', "Mäntsälä"),
+ ('mantta-vilppula', "Mänttä-Vilppula"),
+ ('mantyharju', "Mäntyharju"),
+ ('naantali', "Naantali"),
+ ('nakkila', "Nakkila"),
+ ('nastola', "Nastola"),
+ ('nilsia', "Nilsiä"),
+ ('nivala', "Nivala"),
+ ('nokia', "Nokia"),
+ ('nousiainen', "Nousiainen"),
+ ('nummi-pusula', "Nummi-Pusula"),
+ ('nurmes', "Nurmes"),
+ ('nurmijarvi', "Nurmijärvi"),
+ ('narpio', "Närpiö"),
+ ('oravainen', "Oravainen"),
+ ('orimattila', "Orimattila"),
+ ('oripaa', "Oripää"),
+ ('orivesi', "Orivesi"),
+ ('oulainen', "Oulainen"),
+ ('oulu', "Oulu"),
+ ('oulunsalo', "Oulunsalo"),
+ ('outokumpu', "Outokumpu"),
+ ('padasjoki', "Padasjoki"),
+ ('paimio', "Paimio"),
+ ('paltamo', "Paltamo"),
+ ('parikkala', "Parikkala"),
+ ('parkano', "Parkano"),
+ ('pedersore', "Pedersöre"),
+ ('pelkosenniemi', "Pelkosenniemi"),
+ ('pello', "Pello"),
+ ('perho', "Perho"),
+ ('pertunmaa', "Pertunmaa"),
+ ('petajavesi', "Petäjävesi"),
+ ('pieksamaki', "Pieksämäki"),
+ ('pielavesi', "Pielavesi"),
+ ('pietarsaari', "Pietarsaari"),
+ ('pihtipudas', "Pihtipudas"),
+ ('pirkkala', "Pirkkala"),
+ ('polvijarvi', "Polvijärvi"),
+ ('pomarkku', "Pomarkku"),
+ ('pori', "Pori"),
+ ('pornainen', "Pornainen"),
+ ('porvoo', "Porvoo"),
+ ('posio', "Posio"),
+ ('pudasjarvi', "Pudasjärvi"),
+ ('pukkila', "Pukkila"),
+ ('punkaharju', "Punkaharju"),
+ ('punkalaidun', "Punkalaidun"),
+ ('puolanka', "Puolanka"),
+ ('puumala', "Puumala"),
+ ('pyhtaa', "Pyhtää"),
+ ('pyhajoki', "Pyhäjoki"),
+ ('pyhajarvi', "Pyhäjärvi"),
+ ('pyhanta', "Pyhäntä"),
+ ('pyharanta', "Pyhäranta"),
+ ('palkane', "Pälkäne"),
+ ('poytya', "Pöytyä"),
+ ('raahe', "Raahe"),
+ ('raasepori', "Raasepori"),
+ ('raisio', "Raisio"),
+ ('rantasalmi', "Rantasalmi"),
+ ('ranua', "Ranua"),
+ ('rauma', "Rauma"),
+ ('rautalampi', "Rautalampi"),
+ ('rautavaara', "Rautavaara"),
+ ('rautjarvi', "Rautjärvi"),
+ ('reisjarvi', "Reisjärvi"),
+ ('riihimaki', "Riihimäki"),
+ ('ristiina', "Ristiina"),
+ ('ristijarvi', "Ristijärvi"),
+ ('rovaniemi', "Rovaniemi"),
+ ('ruokolahti', "Ruokolahti"),
+ ('ruovesi', "Ruovesi"),
+ ('rusko', "Rusko"),
+ ('raakkyla', "Rääkkylä"),
+ ('saarijarvi', "Saarijärvi"),
+ ('salla', "Salla"),
+ ('salo', "Salo"),
+ ('saltvik', "Saltvik"),
+ ('sastamala', "Sastamala"),
+ ('sauvo', "Sauvo"),
+ ('savitaipale', "Savitaipale"),
+ ('savonlinna', "Savonlinna"),
+ ('savukoski', "Savukoski"),
+ ('seinajoki', "Seinäjoki"),
+ ('sievi', "Sievi"),
+ ('siikainen', "Siikainen"),
+ ('siikajoki', "Siikajoki"),
+ ('siikalatva', "Siikalatva"),
+ ('siilinjarvi', "Siilinjärvi"),
+ ('simo', "Simo"),
+ ('sipoo', "Sipoo"),
+ ('siuntio', "Siuntio"),
+ ('sodankyla', "Sodankylä"),
+ ('soini', "Soini"),
+ ('somero', "Somero"),
+ ('sonkajarvi', "Sonkajärvi"),
+ ('sotkamo', "Sotkamo"),
+ ('sottunga', "Sottunga"),
+ ('sulkava', "Sulkava"),
+ ('sund', "Sund"),
+ ('suomenniemi', "Suomenniemi"),
+ ('suomussalmi', "Suomussalmi"),
+ ('suonenjoki', "Suonenjoki"),
+ ('sysma', "Sysmä"),
+ ('sakyla', "Säkylä"),
+ ('taipalsaari', "Taipalsaari"),
+ ('taivalkoski', "Taivalkoski"),
+ ('taivassalo', "Taivassalo"),
+ ('tammela', "Tammela"),
+ ('tampere', "Tampere"),
+ ('tarvasjoki', "Tarvasjoki"),
+ ('tervo', "Tervo"),
+ ('tervola', "Tervola"),
+ ('teuva', "Teuva"),
+ ('tohmajarvi', "Tohmajärvi"),
+ ('toholampi', "Toholampi"),
+ ('toivakka', "Toivakka"),
+ ('tornio', "Tornio"),
+ ('turku', "Turku"),
+ ('tuusniemi', "Tuusniemi"),
+ ('tuusula', "Tuusula"),
+ ('tyrnava', "Tyrnävä"),
+ ('toysa', "Töysä"),
+ ('ulvila', "Ulvila"),
+ ('urjala', "Urjala"),
+ ('utajarvi', "Utajärvi"),
+ ('utsjoki', "Utsjoki"),
+ ('uurainen', "Uurainen"),
+ ('uusikaarlepyy', "Uusikaarlepyy"),
+ ('uusikaupunki', "Uusikaupunki"),
+ ('vaala', "Vaala"),
+ ('vaasa', "Vaasa"),
+ ('valkeakoski', "Valkeakoski"),
+ ('valtimo', "Valtimo"),
+ ('vantaa', "Vantaa"),
+ ('varkaus', "Varkaus"),
+ ('varpaisjarvi', "Varpaisjärvi"),
+ ('vehmaa', "Vehmaa"),
+ ('vesanto', "Vesanto"),
+ ('vesilahti', "Vesilahti"),
+ ('veteli', "Veteli"),
+ ('vierema', "Vieremä"),
+ ('vihanti', "Vihanti"),
+ ('vihti', "Vihti"),
+ ('viitasaari', "Viitasaari"),
+ ('vimpeli', "Vimpeli"),
+ ('virolahti', "Virolahti"),
+ ('virrat', "Virrat"),
+ ('vardo', "Vårdö"),
+ ('vahakyro', "Vähäkyrö"),
+ ('voyri-maksamaa', "Vöyri-Maksamaa"),
+ ('yli-ii', "Yli-Ii"),
+ ('ylitornio', "Ylitornio"),
+ ('ylivieska', "Ylivieska"),
+ ('ylojarvi', "Ylöjärvi"),
+ ('ypaja', "Ypäjä"),
+ ('ahtari', "Ähtäri"),
+ ('aanekoski', "Äänekoski")
+)
diff --git a/django/contrib/localflavor/fi/forms.py b/django/contrib/localflavor/fi/forms.py
index ddc3b48c54b..633f3e5f1b2 100644
--- a/django/contrib/localflavor/fi/forms.py
+++ b/django/contrib/localflavor/fi/forms.py
@@ -2,7 +2,7 @@
FI-specific Form helpers
"""
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import re
@@ -36,7 +36,7 @@ class FISocialSecurityNumber(Field):
def clean(self, value):
super(FISocialSecurityNumber, self).clean(value)
if value in EMPTY_VALUES:
- return u''
+ return ''
checkmarks = "0123456789ABCDEFHJKLMNPRSTUVWXY"
result = re.match(r"""^
@@ -51,5 +51,5 @@ class FISocialSecurityNumber(Field):
gd = result.groupdict()
checksum = int(gd['date'] + gd['serial'])
if checkmarks[checksum % len(checkmarks)] == gd['checksum'].upper():
- return u'%s' % value.upper()
+ return '%s' % value.upper()
raise ValidationError(self.error_messages['invalid'])
diff --git a/django/contrib/localflavor/fr/forms.py b/django/contrib/localflavor/fr/forms.py
index 34e4a96bf4f..47177db685f 100644
--- a/django/contrib/localflavor/fr/forms.py
+++ b/django/contrib/localflavor/fr/forms.py
@@ -1,7 +1,7 @@
"""
FR-specific Form helpers
"""
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import re
@@ -38,11 +38,11 @@ class FRPhoneNumberField(Field):
def clean(self, value):
super(FRPhoneNumberField, self).clean(value)
if value in EMPTY_VALUES:
- return u''
+ return ''
value = re.sub('(\.|\s)', '', smart_unicode(value))
m = phone_digits_re.search(value)
if m:
- return u'%s %s %s %s %s' % (value[0:2], value[2:4], value[4:6], value[6:8], value[8:10])
+ return '%s %s %s %s %s' % (value[0:2], value[2:4], value[4:6], value[6:8], value[8:10])
raise ValidationError(self.error_messages['invalid'])
class FRDepartmentSelect(Select):
diff --git a/django/contrib/localflavor/fr/fr_department.py b/django/contrib/localflavor/fr/fr_department.py
index 9f146ac8f94..a2cca957c27 100644
--- a/django/contrib/localflavor/fr/fr_department.py
+++ b/django/contrib/localflavor/fr/fr_department.py
@@ -1,117 +1,118 @@
# -*- coding: utf-8 -*-
# See the "Code officiel géographique" on the INSEE website .
+from __future__ import unicode_literals
DEPARTMENT_CHOICES = (
# Metropolitan departments
- ('01', u'01 - Ain'),
- ('02', u'02 - Aisne'),
- ('03', u'03 - Allier'),
- ('04', u'04 - Alpes-de-Haute-Provence'),
- ('05', u'05 - Hautes-Alpes'),
- ('06', u'06 - Alpes-Maritimes'),
- ('07', u'07 - Ardèche'),
- ('08', u'08 - Ardennes'),
- ('09', u'09 - Ariège'),
- ('10', u'10 - Aube'),
- ('11', u'11 - Aude'),
- ('12', u'12 - Aveyron'),
- ('13', u'13 - Bouches-du-Rhône'),
- ('14', u'14 - Calvados'),
- ('15', u'15 - Cantal'),
- ('16', u'16 - Charente'),
- ('17', u'17 - Charente-Maritime'),
- ('18', u'18 - Cher'),
- ('19', u'19 - Corrèze'),
- ('2A', u'2A - Corse-du-Sud'),
- ('2B', u'2B - Haute-Corse'),
- ('21', u'21 - Côte-d\'Or'),
- ('22', u'22 - Côtes-d\'Armor'),
- ('23', u'23 - Creuse'),
- ('24', u'24 - Dordogne'),
- ('25', u'25 - Doubs'),
- ('26', u'26 - Drôme'),
- ('27', u'27 - Eure'),
- ('28', u'28 - Eure-et-Loir'),
- ('29', u'29 - Finistère'),
- ('30', u'30 - Gard'),
- ('31', u'31 - Haute-Garonne'),
- ('32', u'32 - Gers'),
- ('33', u'33 - Gironde'),
- ('34', u'34 - Hérault'),
- ('35', u'35 - Ille-et-Vilaine'),
- ('36', u'36 - Indre'),
- ('37', u'37 - Indre-et-Loire'),
- ('38', u'38 - Isère'),
- ('39', u'39 - Jura'),
- ('40', u'40 - Landes'),
- ('41', u'41 - Loir-et-Cher'),
- ('42', u'42 - Loire'),
- ('43', u'43 - Haute-Loire'),
- ('44', u'44 - Loire-Atlantique'),
- ('45', u'45 - Loiret'),
- ('46', u'46 - Lot'),
- ('47', u'47 - Lot-et-Garonne'),
- ('48', u'48 - Lozère'),
- ('49', u'49 - Maine-et-Loire'),
- ('50', u'50 - Manche'),
- ('51', u'51 - Marne'),
- ('52', u'52 - Haute-Marne'),
- ('53', u'53 - Mayenne'),
- ('54', u'54 - Meurthe-et-Moselle'),
- ('55', u'55 - Meuse'),
- ('56', u'56 - Morbihan'),
- ('57', u'57 - Moselle'),
- ('58', u'58 - Nièvre'),
- ('59', u'59 - Nord'),
- ('60', u'60 - Oise'),
- ('61', u'61 - Orne'),
- ('62', u'62 - Pas-de-Calais'),
- ('63', u'63 - Puy-de-Dôme'),
- ('64', u'64 - Pyrénées-Atlantiques'),
- ('65', u'65 - Hautes-Pyrénées'),
- ('66', u'66 - Pyrénées-Orientales'),
- ('67', u'67 - Bas-Rhin'),
- ('68', u'68 - Haut-Rhin'),
- ('69', u'69 - Rhône'),
- ('70', u'70 - Haute-Saône'),
- ('71', u'71 - Saône-et-Loire'),
- ('72', u'72 - Sarthe'),
- ('73', u'73 - Savoie'),
- ('74', u'74 - Haute-Savoie'),
- ('75', u'75 - Paris'),
- ('76', u'76 - Seine-Maritime'),
- ('77', u'77 - Seine-et-Marne'),
- ('78', u'78 - Yvelines'),
- ('79', u'79 - Deux-Sèvres'),
- ('80', u'80 - Somme'),
- ('81', u'81 - Tarn'),
- ('82', u'82 - Tarn-et-Garonne'),
- ('83', u'83 - Var'),
- ('84', u'84 - Vaucluse'),
- ('85', u'85 - Vendée'),
- ('86', u'86 - Vienne'),
- ('87', u'87 - Haute-Vienne'),
- ('88', u'88 - Vosges'),
- ('89', u'89 - Yonne'),
- ('90', u'90 - Territoire de Belfort'),
- ('91', u'91 - Essonne'),
- ('92', u'92 - Hauts-de-Seine'),
- ('93', u'93 - Seine-Saint-Denis'),
- ('94', u'94 - Val-de-Marne'),
- ('95', u'95 - Val-d\'Oise'),
+ ('01', '01 - Ain'),
+ ('02', '02 - Aisne'),
+ ('03', '03 - Allier'),
+ ('04', '04 - Alpes-de-Haute-Provence'),
+ ('05', '05 - Hautes-Alpes'),
+ ('06', '06 - Alpes-Maritimes'),
+ ('07', '07 - Ardèche'),
+ ('08', '08 - Ardennes'),
+ ('09', '09 - Ariège'),
+ ('10', '10 - Aube'),
+ ('11', '11 - Aude'),
+ ('12', '12 - Aveyron'),
+ ('13', '13 - Bouches-du-Rhône'),
+ ('14', '14 - Calvados'),
+ ('15', '15 - Cantal'),
+ ('16', '16 - Charente'),
+ ('17', '17 - Charente-Maritime'),
+ ('18', '18 - Cher'),
+ ('19', '19 - Corrèze'),
+ ('2A', '2A - Corse-du-Sud'),
+ ('2B', '2B - Haute-Corse'),
+ ('21', '21 - Côte-d\'Or'),
+ ('22', '22 - Côtes-d\'Armor'),
+ ('23', '23 - Creuse'),
+ ('24', '24 - Dordogne'),
+ ('25', '25 - Doubs'),
+ ('26', '26 - Drôme'),
+ ('27', '27 - Eure'),
+ ('28', '28 - Eure-et-Loir'),
+ ('29', '29 - Finistère'),
+ ('30', '30 - Gard'),
+ ('31', '31 - Haute-Garonne'),
+ ('32', '32 - Gers'),
+ ('33', '33 - Gironde'),
+ ('34', '34 - Hérault'),
+ ('35', '35 - Ille-et-Vilaine'),
+ ('36', '36 - Indre'),
+ ('37', '37 - Indre-et-Loire'),
+ ('38', '38 - Isère'),
+ ('39', '39 - Jura'),
+ ('40', '40 - Landes'),
+ ('41', '41 - Loir-et-Cher'),
+ ('42', '42 - Loire'),
+ ('43', '43 - Haute-Loire'),
+ ('44', '44 - Loire-Atlantique'),
+ ('45', '45 - Loiret'),
+ ('46', '46 - Lot'),
+ ('47', '47 - Lot-et-Garonne'),
+ ('48', '48 - Lozère'),
+ ('49', '49 - Maine-et-Loire'),
+ ('50', '50 - Manche'),
+ ('51', '51 - Marne'),
+ ('52', '52 - Haute-Marne'),
+ ('53', '53 - Mayenne'),
+ ('54', '54 - Meurthe-et-Moselle'),
+ ('55', '55 - Meuse'),
+ ('56', '56 - Morbihan'),
+ ('57', '57 - Moselle'),
+ ('58', '58 - Nièvre'),
+ ('59', '59 - Nord'),
+ ('60', '60 - Oise'),
+ ('61', '61 - Orne'),
+ ('62', '62 - Pas-de-Calais'),
+ ('63', '63 - Puy-de-Dôme'),
+ ('64', '64 - Pyrénées-Atlantiques'),
+ ('65', '65 - Hautes-Pyrénées'),
+ ('66', '66 - Pyrénées-Orientales'),
+ ('67', '67 - Bas-Rhin'),
+ ('68', '68 - Haut-Rhin'),
+ ('69', '69 - Rhône'),
+ ('70', '70 - Haute-Saône'),
+ ('71', '71 - Saône-et-Loire'),
+ ('72', '72 - Sarthe'),
+ ('73', '73 - Savoie'),
+ ('74', '74 - Haute-Savoie'),
+ ('75', '75 - Paris'),
+ ('76', '76 - Seine-Maritime'),
+ ('77', '77 - Seine-et-Marne'),
+ ('78', '78 - Yvelines'),
+ ('79', '79 - Deux-Sèvres'),
+ ('80', '80 - Somme'),
+ ('81', '81 - Tarn'),
+ ('82', '82 - Tarn-et-Garonne'),
+ ('83', '83 - Var'),
+ ('84', '84 - Vaucluse'),
+ ('85', '85 - Vendée'),
+ ('86', '86 - Vienne'),
+ ('87', '87 - Haute-Vienne'),
+ ('88', '88 - Vosges'),
+ ('89', '89 - Yonne'),
+ ('90', '90 - Territoire de Belfort'),
+ ('91', '91 - Essonne'),
+ ('92', '92 - Hauts-de-Seine'),
+ ('93', '93 - Seine-Saint-Denis'),
+ ('94', '94 - Val-de-Marne'),
+ ('95', '95 - Val-d\'Oise'),
# Overseas departments, communities, and other territories
- ('971', u'971 - Guadeloupe'),
- ('972', u'972 - Martinique'),
- ('973', u'973 - Guyane'),
- ('974', u'974 - La Réunion'),
- ('975', u'975 - Saint-Pierre-et-Miquelon'),
- ('976', u'976 - Mayotte'),
- ('977', u'977 - Saint-Barthélemy'),
- ('978', u'978 - Saint-Martin'),
- ('984', u'984 - Terres australes et antarctiques françaises'),
- ('986', u'986 - Wallis et Futuna'),
- ('987', u'987 - Polynésie française'),
- ('988', u'988 - Nouvelle-Calédonie'),
- ('989', u'989 - Île de Clipperton'),
+ ('971', '971 - Guadeloupe'),
+ ('972', '972 - Martinique'),
+ ('973', '973 - Guyane'),
+ ('974', '974 - La Réunion'),
+ ('975', '975 - Saint-Pierre-et-Miquelon'),
+ ('976', '976 - Mayotte'),
+ ('977', '977 - Saint-Barthélemy'),
+ ('978', '978 - Saint-Martin'),
+ ('984', '984 - Terres australes et antarctiques françaises'),
+ ('986', '986 - Wallis et Futuna'),
+ ('987', '987 - Polynésie française'),
+ ('988', '988 - Nouvelle-Calédonie'),
+ ('989', '989 - Île de Clipperton'),
)
diff --git a/django/contrib/localflavor/gb/forms.py b/django/contrib/localflavor/gb/forms.py
index a6658578b1f..bf90f802812 100644
--- a/django/contrib/localflavor/gb/forms.py
+++ b/django/contrib/localflavor/gb/forms.py
@@ -2,7 +2,7 @@
GB-specific Form helpers
"""
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import re
@@ -22,7 +22,7 @@ class GBPostcodeField(CharField):
The value is uppercased and a space added in the correct place, if required.
"""
default_error_messages = {
- 'invalid': _(u'Enter a valid postcode.'),
+ 'invalid': _('Enter a valid postcode.'),
}
outcode_pattern = '[A-PR-UWYZ]([0-9]{1,2}|([A-HIK-Y][0-9](|[0-9]|[ABEHMNPRVWXY]))|[0-9][A-HJKSTUW])'
incode_pattern = '[0-9][ABD-HJLNP-UW-Z]{2}'
@@ -31,7 +31,7 @@ class GBPostcodeField(CharField):
def clean(self, value):
value = super(GBPostcodeField, self).clean(value)
- if value == u'':
+ if value == '':
return value
postcode = value.upper().strip()
# Put a single space before the incode (second part).
diff --git a/django/contrib/localflavor/hk/forms.py b/django/contrib/localflavor/hk/forms.py
index 852ef7d4b21..8cf9360e198 100644
--- a/django/contrib/localflavor/hk/forms.py
+++ b/django/contrib/localflavor/hk/forms.py
@@ -1,7 +1,7 @@
"""
Hong Kong specific Form helpers
"""
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import re
@@ -51,14 +51,14 @@ class HKPhoneNumberField(CharField):
super(HKPhoneNumberField, self).clean(value)
if value in EMPTY_VALUES:
- return u''
+ return ''
value = re.sub('(\(|\)|\s+|\+)', '', smart_unicode(value))
m = hk_phone_digits_re.search(value)
if not m:
raise ValidationError(self.error_messages['invalid'])
- value = u'%s-%s' % (m.group(1), m.group(2))
+ value = '%s-%s' % (m.group(1), m.group(2))
for special in hk_special_numbers:
if value.startswith(special):
raise ValidationError(self.error_messages['disguise'])
diff --git a/django/contrib/localflavor/hr/forms.py b/django/contrib/localflavor/hr/forms.py
index 0ff283d6c83..eb4436a78c5 100644
--- a/django/contrib/localflavor/hr/forms.py
+++ b/django/contrib/localflavor/hr/forms.py
@@ -2,7 +2,7 @@
"""
HR-specific Form helpers
"""
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import re
@@ -19,8 +19,8 @@ from django.utils.translation import ugettext_lazy as _
jmbg_re = re.compile(r'^(?P
' % p for p in paras]
- return u'\n\n'.join(paras)
+ return '\n\n'.join(paras)
@register.tag
def lorem(parser, token):
diff --git a/django/contrib/webdesign/tests.py b/django/contrib/webdesign/tests.py
index 8907ea3ba7b..16ec501e447 100644
--- a/django/contrib/webdesign/tests.py
+++ b/django/contrib/webdesign/tests.py
@@ -1,4 +1,5 @@
# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
import unittest
@@ -9,7 +10,7 @@ from django.template import loader, Context
class WebdesignTest(unittest.TestCase):
def test_words(self):
- self.assertEqual(words(7), u'lorem ipsum dolor sit amet consectetur adipisicing')
+ self.assertEqual(words(7), 'lorem ipsum dolor sit amet consectetur adipisicing')
def test_paragraphs(self):
self.assertEqual(paragraphs(1),
@@ -18,4 +19,4 @@ class WebdesignTest(unittest.TestCase):
def test_lorem_tag(self):
t = loader.get_template_from_string("{% load webdesign %}{% lorem 3 w %}")
self.assertEqual(t.render(Context({})),
- u'lorem ipsum dolor')
+ 'lorem ipsum dolor')
diff --git a/django/core/context_processors.py b/django/core/context_processors.py
index 3ba519188bf..325f64d224e 100644
--- a/django/core/context_processors.py
+++ b/django/core/context_processors.py
@@ -9,6 +9,7 @@ RequestContext.
from django.conf import settings
from django.middleware.csrf import get_token
+from django.utils.encoding import smart_str
from django.utils.functional import lazy
def csrf(request):
@@ -24,7 +25,7 @@ def csrf(request):
# instead of returning an empty dict.
return b'NOTPROVIDED'
else:
- return token
+ return smart_str(token)
_get_val = lazy(_get_val, str)
return {'csrf_token': _get_val() }
diff --git a/django/core/files/base.py b/django/core/files/base.py
index a2d703c963f..04853fad0c3 100644
--- a/django/core/files/base.py
+++ b/django/core/files/base.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import os
from io import BytesIO
@@ -19,7 +21,7 @@ class File(FileProxyMixin):
return smart_str(self.name or '')
def __unicode__(self):
- return smart_unicode(self.name or u'')
+ return smart_unicode(self.name or '')
def __repr__(self):
return "<%s: %s>" % (self.__class__.__name__, self or "None")
diff --git a/django/core/files/uploadhandler.py b/django/core/files/uploadhandler.py
index 88f78904bb4..68d540e595e 100644
--- a/django/core/files/uploadhandler.py
+++ b/django/core/files/uploadhandler.py
@@ -2,6 +2,8 @@
Base file upload handler classes, and the built-in concrete subclasses
"""
+from __future__ import unicode_literals
+
from io import BytesIO
from django.conf import settings
@@ -33,9 +35,9 @@ class StopUpload(UploadFileException):
def __unicode__(self):
if self.connection_reset:
- return u'StopUpload: Halt current upload.'
+ return 'StopUpload: Halt current upload.'
else:
- return u'StopUpload: Consume request data, then halt.'
+ return 'StopUpload: Consume request data, then halt.'
class SkipFile(UploadFileException):
"""
diff --git a/django/core/handlers/base.py b/django/core/handlers/base.py
index 4c9dfc07bc5..4c07524ecc8 100644
--- a/django/core/handlers/base.py
+++ b/django/core/handlers/base.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import sys
from django import http
@@ -254,9 +256,9 @@ def get_script_name(environ):
# rewrites. Unfortunately not every Web server (lighttpd!) passes this
# information through all the time, so FORCE_SCRIPT_NAME, above, is still
# needed.
- script_url = environ.get('SCRIPT_URL', u'')
+ script_url = environ.get('SCRIPT_URL', '')
if not script_url:
- script_url = environ.get('REDIRECT_URL', u'')
+ script_url = environ.get('REDIRECT_URL', '')
if script_url:
return force_unicode(script_url[:-len(environ.get('PATH_INFO', ''))])
- return force_unicode(environ.get('SCRIPT_NAME', u''))
+ return force_unicode(environ.get('SCRIPT_NAME', ''))
diff --git a/django/core/handlers/wsgi.py b/django/core/handlers/wsgi.py
index 128ff7ac64f..5215101a355 100644
--- a/django/core/handlers/wsgi.py
+++ b/django/core/handlers/wsgi.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import sys
from io import BytesIO
from threading import Lock
@@ -7,7 +9,7 @@ from django.core import signals
from django.core.handlers import base
from django.core.urlresolvers import set_script_prefix
from django.utils import datastructures
-from django.utils.encoding import force_unicode, iri_to_uri
+from django.utils.encoding import force_unicode, smart_str, iri_to_uri
from django.utils.log import getLogger
logger = getLogger('django.request')
@@ -125,7 +127,7 @@ class LimitedStream(object):
class WSGIRequest(http.HttpRequest):
def __init__(self, environ):
script_name = base.get_script_name(environ)
- path_info = force_unicode(environ.get('PATH_INFO', u'/'))
+ path_info = force_unicode(environ.get('PATH_INFO', '/'))
if not path_info or path_info == script_name:
# Sometimes PATH_INFO exists, but is empty (e.g. accessing
# the SCRIPT_NAME URL without a trailing slash). We really need to
@@ -134,7 +136,7 @@ class WSGIRequest(http.HttpRequest):
#
# (The comparison of path_info to script_name is to work around an
# apparent bug in flup 1.0.1. See Django ticket #8490).
- path_info = u'/'
+ path_info = '/'
self.environ = environ
self.path_info = path_info
self.path = '%s%s' % (script_name, path_info)
@@ -246,6 +248,6 @@ class WSGIHandler(base.BaseHandler):
status = '%s %s' % (response.status_code, status_text)
response_headers = [(str(k), str(v)) for k, v in response.items()]
for c in response.cookies.values():
- response_headers.append(('Set-Cookie', str(c.output(header=''))))
- start_response(status, response_headers)
+ response_headers.append((b'Set-Cookie', str(c.output(header=''))))
+ start_response(smart_str(status), response_headers)
return response
diff --git a/django/core/mail/__init__.py b/django/core/mail/__init__.py
index 1bee0cac9fd..08f9702934d 100644
--- a/django/core/mail/__init__.py
+++ b/django/core/mail/__init__.py
@@ -1,6 +1,7 @@
"""
Tools for sending email.
"""
+from __future__ import unicode_literals
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
@@ -89,7 +90,7 @@ def mail_admins(subject, message, fail_silently=False, connection=None,
"""Sends a message to the admins, as defined by the ADMINS setting."""
if not settings.ADMINS:
return
- mail = EmailMultiAlternatives(u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject),
+ mail = EmailMultiAlternatives('%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject),
message, settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS],
connection=connection)
if html_message:
@@ -102,7 +103,7 @@ def mail_managers(subject, message, fail_silently=False, connection=None,
"""Sends a message to the managers, as defined by the MANAGERS setting."""
if not settings.MANAGERS:
return
- mail = EmailMultiAlternatives(u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject),
+ mail = EmailMultiAlternatives('%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject),
message, settings.SERVER_EMAIL, [a[1] for a in settings.MANAGERS],
connection=connection)
if html_message:
diff --git a/django/core/mail/message.py b/django/core/mail/message.py
index 2618c7f17da..82f6b6900fc 100644
--- a/django/core/mail/message.py
+++ b/django/core/mail/message.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import mimetypes
import os
import random
@@ -90,7 +92,7 @@ def forbid_multi_line_headers(name, val, encoding):
else:
if name.lower() == 'subject':
val = Header(val)
- return name, val
+ return smart_str(name), val
def sanitize_address(addr, encoding):
@@ -101,8 +103,8 @@ def sanitize_address(addr, encoding):
try:
addr = addr.encode('ascii')
except UnicodeEncodeError: # IDN
- if u'@' in addr:
- localpart, domain = addr.split(u'@', 1)
+ if '@' in addr:
+ localpart, domain = addr.split('@', 1)
localpart = str(Header(localpart, encoding))
domain = domain.encode('idna')
addr = '@'.join([localpart, domain])
diff --git a/django/core/management/commands/createcachetable.py b/django/core/management/commands/createcachetable.py
index bcc47e17c80..fd6dbbbd2c5 100644
--- a/django/core/management/commands/createcachetable.py
+++ b/django/core/management/commands/createcachetable.py
@@ -4,6 +4,8 @@ from django.core.cache.backends.db import BaseDatabaseCache
from django.core.management.base import LabelCommand, CommandError
from django.db import connections, router, transaction, models, DEFAULT_DB_ALIAS
from django.db.utils import DatabaseError
+from django.utils.encoding import force_unicode
+
class Command(LabelCommand):
help = "Creates the table needed to use the SQL cache backend."
@@ -58,7 +60,7 @@ class Command(LabelCommand):
transaction.rollback_unless_managed(using=db)
raise CommandError(
"Cache table '%s' could not be created.\nThe error was: %s." %
- (tablename, e))
+ (tablename, force_unicode(e)))
for statement in index_output:
curs.execute(statement)
transaction.commit_unless_managed(using=db)
diff --git a/django/core/management/commands/loaddata.py b/django/core/management/commands/loaddata.py
index 078fd6fa27a..34f8041d338 100644
--- a/django/core/management/commands/loaddata.py
+++ b/django/core/management/commands/loaddata.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import sys
import os
import gzip
@@ -12,6 +14,7 @@ from django.core.management.color import no_style
from django.db import (connections, router, transaction, DEFAULT_DB_ALIAS,
IntegrityError, DatabaseError)
from django.db.models import get_apps
+from django.utils.encoding import force_unicode
from itertools import product
try:
@@ -186,7 +189,7 @@ class Command(BaseCommand):
'app_label': obj.object._meta.app_label,
'object_name': obj.object._meta.object_name,
'pk': obj.object.pk,
- 'error_msg': e
+ 'error_msg': force_unicode(e)
},)
raise
diff --git a/django/core/management/commands/sql.py b/django/core/management/commands/sql.py
index 59b2e77b692..52b2058650d 100644
--- a/django/core/management/commands/sql.py
+++ b/django/core/management/commands/sql.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from optparse import make_option
from django.core.management.base import AppCommand
@@ -16,4 +18,4 @@ class Command(AppCommand):
output_transaction = True
def handle_app(self, app, **options):
- return u'\n'.join(sql_create(app, self.style, connections[options.get('database')])).encode('utf-8')
+ return '\n'.join(sql_create(app, self.style, connections[options.get('database')]))
diff --git a/django/core/management/commands/sqlall.py b/django/core/management/commands/sqlall.py
index ab702bfffb0..6d0735a6f9e 100644
--- a/django/core/management/commands/sqlall.py
+++ b/django/core/management/commands/sqlall.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from optparse import make_option
from django.core.management.base import AppCommand
@@ -16,4 +18,4 @@ class Command(AppCommand):
output_transaction = True
def handle_app(self, app, **options):
- return u'\n'.join(sql_all(app, self.style, connections[options.get('database')])).encode('utf-8')
+ return '\n'.join(sql_all(app, self.style, connections[options.get('database')]))
diff --git a/django/core/management/commands/sqlclear.py b/django/core/management/commands/sqlclear.py
index b8f491392b7..ec2602d2a38 100644
--- a/django/core/management/commands/sqlclear.py
+++ b/django/core/management/commands/sqlclear.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from optparse import make_option
from django.core.management.base import AppCommand
@@ -16,4 +18,4 @@ class Command(AppCommand):
output_transaction = True
def handle_app(self, app, **options):
- return u'\n'.join(sql_delete(app, self.style, connections[options.get('database')])).encode('utf-8')
+ return '\n'.join(sql_delete(app, self.style, connections[options.get('database')]))
diff --git a/django/core/management/commands/sqlcustom.py b/django/core/management/commands/sqlcustom.py
index 6a984560de7..0d46c4ec705 100644
--- a/django/core/management/commands/sqlcustom.py
+++ b/django/core/management/commands/sqlcustom.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from optparse import make_option
from django.core.management.base import AppCommand
@@ -16,4 +18,4 @@ class Command(AppCommand):
output_transaction = True
def handle_app(self, app, **options):
- return u'\n'.join(sql_custom(app, self.style, connections[options.get('database')])).encode('utf-8')
+ return '\n'.join(sql_custom(app, self.style, connections[options.get('database')]))
diff --git a/django/core/management/commands/sqlflush.py b/django/core/management/commands/sqlflush.py
index 19054fbfa96..b98ecfd8ff3 100644
--- a/django/core/management/commands/sqlflush.py
+++ b/django/core/management/commands/sqlflush.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from optparse import make_option
from django.core.management.base import NoArgsCommand
@@ -16,4 +18,4 @@ class Command(NoArgsCommand):
output_transaction = True
def handle_noargs(self, **options):
- return u'\n'.join(sql_flush(self.style, connections[options.get('database')], only_django=True)).encode('utf-8')
+ return '\n'.join(sql_flush(self.style, connections[options.get('database')], only_django=True))
diff --git a/django/core/management/commands/sqlindexes.py b/django/core/management/commands/sqlindexes.py
index bf55b0dffcc..f95d4f158c8 100644
--- a/django/core/management/commands/sqlindexes.py
+++ b/django/core/management/commands/sqlindexes.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from optparse import make_option
from django.core.management.base import AppCommand
@@ -17,4 +19,4 @@ class Command(AppCommand):
output_transaction = True
def handle_app(self, app, **options):
- return u'\n'.join(sql_indexes(app, self.style, connections[options.get('database')])).encode('utf-8')
+ return '\n'.join(sql_indexes(app, self.style, connections[options.get('database')]))
diff --git a/django/core/management/commands/sqlsequencereset.py b/django/core/management/commands/sqlsequencereset.py
index 6460f000626..7b9e85a9ee0 100644
--- a/django/core/management/commands/sqlsequencereset.py
+++ b/django/core/management/commands/sqlsequencereset.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from optparse import make_option
from django.core.management.base import AppCommand
@@ -17,4 +19,4 @@ class Command(AppCommand):
def handle_app(self, app, **options):
connection = connections[options.get('database')]
- return u'\n'.join(connection.ops.sequence_reset_sql(self.style, models.get_models(app, include_auto_created=True))).encode('utf-8')
+ return '\n'.join(connection.ops.sequence_reset_sql(self.style, models.get_models(app, include_auto_created=True)))
diff --git a/django/core/management/sql.py b/django/core/management/sql.py
index 53d97362934..993d75aa6bb 100644
--- a/django/core/management/sql.py
+++ b/django/core/management/sql.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import os
import re
@@ -160,9 +162,9 @@ def custom_sql_for_model(model, style, connection):
with open(sql_file, 'U') as fp:
for statement in statements.split(fp.read().decode(settings.FILE_CHARSET)):
# Remove any comments from the file
- statement = re.sub(ur"--.*([\n\Z]|$)", "", statement)
+ statement = re.sub(r"--.*([\n\Z]|$)", "", statement)
if statement.strip():
- output.append(statement + u";")
+ output.append(statement + ";")
return output
diff --git a/django/core/management/validation.py b/django/core/management/validation.py
index 272ac5be419..7cd6958abf2 100644
--- a/django/core/management/validation.py
+++ b/django/core/management/validation.py
@@ -1,6 +1,7 @@
import sys
from django.core.management.color import color_style
+from django.utils.encoding import smart_str
from django.utils.itercompat import is_iterable
class ModelErrorCollection:
@@ -11,7 +12,7 @@ class ModelErrorCollection:
def add(self, context, error):
self.errors.append((context, error))
- self.outfile.write(self.style.ERROR("%s: %s\n" % (context, error)))
+ self.outfile.write(self.style.ERROR(smart_str("%s: %s\n" % (context, error))))
def get_validation_errors(outfile, app=None):
"""
diff --git a/django/core/serializers/json.py b/django/core/serializers/json.py
index fce00600f4a..1b9a61750df 100644
--- a/django/core/serializers/json.py
+++ b/django/core/serializers/json.py
@@ -13,6 +13,7 @@ from io import BytesIO
from django.core.serializers.base import DeserializationError
from django.core.serializers.python import Serializer as PythonSerializer
from django.core.serializers.python import Deserializer as PythonDeserializer
+from django.utils.encoding import smart_str
from django.utils.timezone import is_aware
class Serializer(PythonSerializer):
@@ -61,8 +62,10 @@ def Deserializer(stream_or_string, **options):
"""
Deserialize a stream or string of JSON data.
"""
- if isinstance(stream_or_string, basestring):
+ if isinstance(stream_or_string, bytes):
stream = BytesIO(stream_or_string)
+ elif isinstance(stream_or_string, unicode):
+ stream = BytesIO(smart_str(stream_or_string))
else:
stream = stream_or_string
try:
diff --git a/django/core/serializers/python.py b/django/core/serializers/python.py
index 49120434ebe..333161c9295 100644
--- a/django/core/serializers/python.py
+++ b/django/core/serializers/python.py
@@ -3,6 +3,7 @@ A Python "serializer". Doesn't do much serializing per se -- just converts to
and from basic Python data types (lists, dicts, strings, etc.). Useful as a basis for
other serializers.
"""
+from __future__ import unicode_literals
from django.conf import settings
from django.core.serializers import base
@@ -138,5 +139,5 @@ def _get_model(model_identifier):
except TypeError:
Model = None
if Model is None:
- raise base.DeserializationError(u"Invalid model identifier: '%s'" % model_identifier)
+ raise base.DeserializationError("Invalid model identifier: '%s'" % model_identifier)
return Model
diff --git a/django/core/serializers/xml_serializer.py b/django/core/serializers/xml_serializer.py
index a5edeac5af0..9d9c023b647 100644
--- a/django/core/serializers/xml_serializer.py
+++ b/django/core/serializers/xml_serializer.py
@@ -2,6 +2,8 @@
XML serializer.
"""
+from __future__ import unicode_literals
+
from django.conf import settings
from django.core.serializers import base
from django.db import models, DEFAULT_DB_ALIAS
@@ -289,4 +291,4 @@ def getInnerText(node):
inner_text.extend(getInnerText(child))
else:
pass
- return u"".join(inner_text)
+ return "".join(inner_text)
diff --git a/django/core/urlresolvers.py b/django/core/urlresolvers.py
index 78ce00511ce..625ec6348b8 100644
--- a/django/core/urlresolvers.py
+++ b/django/core/urlresolvers.py
@@ -6,6 +6,7 @@ a string) and returns a tuple in this format:
(view_function, function_args, function_kwargs)
"""
+from __future__ import unicode_literals
import re
from threading import local
@@ -182,7 +183,7 @@ class RegexURLPattern(LocaleRegexProvider):
self.name = name
def __repr__(self):
- return smart_str(u'<%s %s %s>' % (self.__class__.__name__, self.name, self.regex.pattern))
+ return smart_str('<%s %s %s>' % (self.__class__.__name__, self.name, self.regex.pattern))
def add_prefix(self, prefix):
"""
@@ -232,7 +233,7 @@ class RegexURLResolver(LocaleRegexProvider):
self._app_dict = {}
def __repr__(self):
- return smart_str(u'<%s %s (%s:%s) %s>' % (self.__class__.__name__, self.urlconf_name, self.app_name, self.namespace, self.regex.pattern))
+ return smart_str('<%s %s (%s:%s) %s>' % (self.__class__.__name__, self.urlconf_name, self.app_name, self.namespace, self.regex.pattern))
def _populate(self):
lookups = MultiValueDict()
@@ -379,7 +380,7 @@ class RegexURLResolver(LocaleRegexProvider):
continue
unicode_kwargs = dict([(k, force_unicode(v)) for (k, v) in kwargs.items()])
candidate = (prefix_norm + result) % unicode_kwargs
- if re.search(u'^%s%s' % (_prefix, pattern), candidate, re.UNICODE):
+ if re.search('^%s%s' % (_prefix, pattern), candidate, re.UNICODE):
return candidate
# lookup_view can be URL label, or dotted path, or callable, Any of
# these can be passed in at the top, but callables are not friendly in
@@ -497,7 +498,7 @@ def get_script_prefix():
wishes to construct their own URLs manually (although accessing the request
instance is normally going to be a lot cleaner).
"""
- return getattr(_prefixes, "value", u'/')
+ return getattr(_prefixes, "value", '/')
def set_urlconf(urlconf_name):
"""
diff --git a/django/core/validators.py b/django/core/validators.py
index 3d4bcc86c8f..c7c89786da4 100644
--- a/django/core/validators.py
+++ b/django/core/validators.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import re
import urlparse
@@ -11,7 +13,7 @@ EMPTY_VALUES = (None, '', [], (), {})
class RegexValidator(object):
regex = ''
- message = _(u'Enter a valid value.')
+ message = _('Enter a valid value.')
code = 'invalid'
def __init__(self, regex=None, message=None, code=None):
@@ -75,13 +77,13 @@ class EmailValidator(RegexValidator):
super(EmailValidator, self).__call__(value)
except ValidationError as e:
# Trivial case failed. Try for possible IDN domain-part
- if value and u'@' in value:
- parts = value.split(u'@')
+ if value and '@' in value:
+ parts = value.split('@')
try:
parts[-1] = parts[-1].encode('idna')
except UnicodeError:
raise e
- super(EmailValidator, self).__call__(u'@'.join(parts))
+ super(EmailValidator, self).__call__('@'.join(parts))
else:
raise
@@ -91,17 +93,17 @@ email_re = re.compile(
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"'
r')@((?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$)' # domain
r'|\[(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\]$', re.IGNORECASE) # literal form, ipv4 address (SMTP 4.1.3)
-validate_email = EmailValidator(email_re, _(u'Enter a valid e-mail address.'), 'invalid')
+validate_email = EmailValidator(email_re, _('Enter a valid e-mail address.'), 'invalid')
slug_re = re.compile(r'^[-\w]+$')
-validate_slug = RegexValidator(slug_re, _(u"Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."), 'invalid')
+validate_slug = RegexValidator(slug_re, _("Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."), 'invalid')
ipv4_re = re.compile(r'^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$')
-validate_ipv4_address = RegexValidator(ipv4_re, _(u'Enter a valid IPv4 address.'), 'invalid')
+validate_ipv4_address = RegexValidator(ipv4_re, _('Enter a valid IPv4 address.'), 'invalid')
def validate_ipv6_address(value):
if not is_valid_ipv6_address(value):
- raise ValidationError(_(u'Enter a valid IPv6 address.'), code='invalid')
+ raise ValidationError(_('Enter a valid IPv6 address.'), code='invalid')
def validate_ipv46_address(value):
try:
@@ -110,7 +112,7 @@ def validate_ipv46_address(value):
try:
validate_ipv6_address(value)
except ValidationError:
- raise ValidationError(_(u'Enter a valid IPv4 or IPv6 address.'), code='invalid')
+ raise ValidationError(_('Enter a valid IPv4 or IPv6 address.'), code='invalid')
ip_address_validator_map = {
'both': ([validate_ipv46_address], _('Enter a valid IPv4 or IPv6 address.')),
@@ -135,13 +137,13 @@ def ip_address_validators(protocol, unpack_ipv4):
% (protocol, ip_address_validator_map.keys()))
comma_separated_int_list_re = re.compile('^[\d,]+$')
-validate_comma_separated_integer_list = RegexValidator(comma_separated_int_list_re, _(u'Enter only digits separated by commas.'), 'invalid')
+validate_comma_separated_integer_list = RegexValidator(comma_separated_int_list_re, _('Enter only digits separated by commas.'), 'invalid')
class BaseValidator(object):
compare = lambda self, a, b: a is not b
clean = lambda self, x: x
- message = _(u'Ensure this value is %(limit_value)s (it is %(show_value)s).')
+ message = _('Ensure this value is %(limit_value)s (it is %(show_value)s).')
code = 'limit_value'
def __init__(self, limit_value):
@@ -159,23 +161,23 @@ class BaseValidator(object):
class MaxValueValidator(BaseValidator):
compare = lambda self, a, b: a > b
- message = _(u'Ensure this value is less than or equal to %(limit_value)s.')
+ message = _('Ensure this value is less than or equal to %(limit_value)s.')
code = 'max_value'
class MinValueValidator(BaseValidator):
compare = lambda self, a, b: a < b
- message = _(u'Ensure this value is greater than or equal to %(limit_value)s.')
+ message = _('Ensure this value is greater than or equal to %(limit_value)s.')
code = 'min_value'
class MinLengthValidator(BaseValidator):
compare = lambda self, a, b: a < b
clean = lambda self, x: len(x)
- message = _(u'Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).')
+ message = _('Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).')
code = 'min_length'
class MaxLengthValidator(BaseValidator):
compare = lambda self, a, b: a > b
clean = lambda self, x: len(x)
- message = _(u'Ensure this value has at most %(limit_value)d characters (it has %(show_value)d).')
+ message = _('Ensure this value has at most %(limit_value)d characters (it has %(show_value)d).')
code = 'max_length'
diff --git a/django/db/backends/mysql/base.py b/django/db/backends/mysql/base.py
index 1df487bd928..ff227b6e7e6 100644
--- a/django/db/backends/mysql/base.py
+++ b/django/db/backends/mysql/base.py
@@ -3,6 +3,7 @@ MySQL database backend for Django.
Requires MySQLdb: http://sourceforge.net/projects/mysql-python
"""
+from __future__ import unicode_literals
import datetime
import re
@@ -61,8 +62,8 @@ def adapt_datetime_with_timezone_support(value, conv):
# Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
if settings.USE_TZ:
if timezone.is_naive(value):
- warnings.warn(u"SQLite received a naive datetime (%s)"
- u" while time zone support is active." % value,
+ warnings.warn("SQLite received a naive datetime (%s)"
+ " while time zone support is active." % value,
RuntimeWarning)
default_timezone = timezone.get_default_timezone()
value = timezone.make_aware(value, default_timezone)
diff --git a/django/db/backends/oracle/base.py b/django/db/backends/oracle/base.py
index fe512dfee57..785e4b72a60 100644
--- a/django/db/backends/oracle/base.py
+++ b/django/db/backends/oracle/base.py
@@ -3,7 +3,7 @@ Oracle database backend for Django.
Requires cx_Oracle: http://cx-oracle.sourceforge.net/
"""
-
+from __future__ import unicode_literals
import datetime
import decimal
@@ -160,7 +160,7 @@ WHEN (new.%(col_name)s IS NULL)
# string instead of null, but only if the field accepts the
# empty string.
if value is None and field and field.empty_strings_allowed:
- value = u''
+ value = ''
# Convert 1 or 0 to True or False
elif value in (1, 0) and field and field.get_internal_type() in ('BooleanField', 'NullBooleanField'):
value = bool(value)
@@ -235,7 +235,7 @@ WHEN (new.%(col_name)s IS NULL)
def process_clob(self, value):
if value is None:
- return u''
+ return ''
return force_unicode(value.read())
def quote_name(self, name):
@@ -567,8 +567,8 @@ class OracleParam(object):
# without being converted by DateTimeField.get_db_prep_value.
if settings.USE_TZ and isinstance(param, datetime.datetime):
if timezone.is_naive(param):
- warnings.warn(u"Oracle received a naive datetime (%s)"
- u" while time zone support is active." % param,
+ warnings.warn("Oracle received a naive datetime (%s)"
+ " while time zone support is active." % param,
RuntimeWarning)
default_timezone = timezone.get_default_timezone()
param = timezone.make_aware(param, default_timezone)
diff --git a/django/db/backends/postgresql_psycopg2/introspection.py b/django/db/backends/postgresql_psycopg2/introspection.py
index fbf7a22769a..99573b90191 100644
--- a/django/db/backends/postgresql_psycopg2/introspection.py
+++ b/django/db/backends/postgresql_psycopg2/introspection.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.db.backends import BaseDatabaseIntrospection
@@ -43,7 +45,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
WHERE table_name = %s""", [table_name])
null_map = dict(cursor.fetchall())
cursor.execute("SELECT * FROM %s LIMIT 1" % self.connection.ops.quote_name(table_name))
- return [tuple([item for item in line[:6]] + [null_map[line[0]]==u'YES'])
+ return [tuple([item for item in line[:6]] + [null_map[line[0]]=='YES'])
for line in cursor.description]
def get_relations(self, cursor, table_name):
diff --git a/django/db/backends/postgresql_psycopg2/operations.py b/django/db/backends/postgresql_psycopg2/operations.py
index 395cd92047f..46b464b551f 100644
--- a/django/db/backends/postgresql_psycopg2/operations.py
+++ b/django/db/backends/postgresql_psycopg2/operations.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.db.backends import BaseDatabaseOperations
@@ -21,14 +23,14 @@ class DatabaseOperations(BaseDatabaseOperations):
"""
modifiers = []
if timedelta.days:
- modifiers.append(u'%s days' % timedelta.days)
+ modifiers.append('%s days' % timedelta.days)
if timedelta.seconds:
- modifiers.append(u'%s seconds' % timedelta.seconds)
+ modifiers.append('%s seconds' % timedelta.seconds)
if timedelta.microseconds:
- modifiers.append(u'%s microseconds' % timedelta.microseconds)
- mods = u' '.join(modifiers)
- conn = u' %s ' % connector
- return u'(%s)' % conn.join([sql, u'interval \'%s\'' % mods])
+ modifiers.append('%s microseconds' % timedelta.microseconds)
+ mods = ' '.join(modifiers)
+ conn = ' %s ' % connector
+ return '(%s)' % conn.join([sql, 'interval \'%s\'' % mods])
def date_trunc_sql(self, lookup_type, field_name):
# http://www.postgresql.org/docs/8.0/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC
diff --git a/django/db/backends/sqlite3/base.py b/django/db/backends/sqlite3/base.py
index 4fba304e237..75e1d9792c2 100644
--- a/django/db/backends/sqlite3/base.py
+++ b/django/db/backends/sqlite3/base.py
@@ -4,6 +4,7 @@ SQLite3 backend for django.
Works with either the pysqlite2 module or the sqlite3 module in the
standard library.
"""
+from __future__ import unicode_literals
import datetime
import decimal
@@ -45,8 +46,8 @@ def adapt_datetime_with_timezone_support(value):
# Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
if settings.USE_TZ:
if timezone.is_naive(value):
- warnings.warn(u"SQLite received a naive datetime (%s)"
- u" while time zone support is active." % value,
+ warnings.warn("SQLite received a naive datetime (%s)"
+ " while time zone support is active." % value,
RuntimeWarning)
default_timezone = timezone.get_default_timezone()
value = timezone.make_aware(value, default_timezone)
@@ -118,7 +119,7 @@ class DatabaseOperations(BaseDatabaseOperations):
# values differently. So instead we register our own function that
# formats the datetime combined with the delta in a manner suitable
# for comparisons.
- return u'django_format_dtdelta(%s, "%s", "%d", "%d", "%d")' % (sql,
+ return 'django_format_dtdelta(%s, "%s", "%d", "%d", "%d")' % (sql,
connector, timedelta.days, timedelta.seconds, timedelta.microseconds)
def date_trunc_sql(self, lookup_type, field_name):
diff --git a/django/db/backends/util.py b/django/db/backends/util.py
index 32e0f4f7023..775bb3e1823 100644
--- a/django/db/backends/util.py
+++ b/django/db/backends/util.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import datetime
import decimal
import hashlib
@@ -146,6 +148,6 @@ def format_number(value, max_digits, decimal_places):
if isinstance(value, decimal.Decimal):
context = decimal.getcontext().copy()
context.prec = max_digits
- return u'%s' % str(value.quantize(decimal.Decimal(".1") ** decimal_places, context=context))
+ return '%s' % str(value.quantize(decimal.Decimal(".1") ** decimal_places, context=context))
else:
- return u"%.*f" % (decimal_places, value)
+ return "%.*f" % (decimal_places, value)
diff --git a/django/db/models/base.py b/django/db/models/base.py
index 13238fc9dcf..f52a626d8bd 100644
--- a/django/db/models/base.py
+++ b/django/db/models/base.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import copy
import sys
from functools import update_wrapper
@@ -373,7 +375,7 @@ class Model(object):
u = unicode(self)
except (UnicodeEncodeError, UnicodeDecodeError):
u = '[Bad Unicode data]'
- return smart_str(u'<%s: %s>' % (self.__class__.__name__, u))
+ return smart_str('<%s: %s>' % (self.__class__.__name__, u))
def __str__(self):
if hasattr(self, '__unicode__'):
@@ -786,7 +788,7 @@ class Model(object):
def date_error_message(self, lookup_type, field, unique_for):
opts = self._meta
- return _(u"%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
+ return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
'field_name': unicode(capfirst(opts.get_field(field).verbose_name)),
'date_field': unicode(capfirst(opts.get_field(unique_for).verbose_name)),
'lookup': lookup_type,
@@ -810,7 +812,7 @@ class Model(object):
else:
field_labels = map(lambda f: capfirst(opts.get_field(f).verbose_name), unique_check)
field_labels = get_text_list(field_labels, _('and'))
- return _(u"%(model_name)s with this %(field_label)s already exists.") % {
+ return _("%(model_name)s with this %(field_label)s already exists.") % {
'model_name': unicode(model_name),
'field_label': unicode(field_labels)
}
diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py
index d572cce28f8..9db76a617b2 100644
--- a/django/db/models/fields/__init__.py
+++ b/django/db/models/fields/__init__.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
import collections
import copy
import datetime
@@ -61,16 +63,16 @@ class Field(object):
auto_creation_counter = -1
default_validators = [] # Default set of validators
default_error_messages = {
- 'invalid_choice': _(u'Value %r is not a valid choice.'),
- 'null': _(u'This field cannot be null.'),
- 'blank': _(u'This field cannot be blank.'),
- 'unique': _(u'%(model_name)s with this %(field_label)s '
- u'already exists.'),
+ 'invalid_choice': _('Value %r is not a valid choice.'),
+ 'null': _('This field cannot be null.'),
+ 'blank': _('This field cannot be blank.'),
+ 'unique': _('%(model_name)s with this %(field_label)s '
+ 'already exists.'),
}
# Generic field type description, usually overriden by subclasses
def _description(self):
- return _(u'Field of type: %(field_type)s') % {
+ return _('Field of type: %(field_type)s') % {
'field_type': self.__class__.__name__
}
description = property(_description)
@@ -512,7 +514,7 @@ class AutoField(Field):
empty_strings_allowed = False
default_error_messages = {
- 'invalid': _(u"'%s' value must be an integer."),
+ 'invalid': _("'%s' value must be an integer."),
}
def __init__(self, *args, **kwargs):
@@ -560,7 +562,7 @@ class AutoField(Field):
class BooleanField(Field):
empty_strings_allowed = False
default_error_messages = {
- 'invalid': _(u"'%s' value must be either True or False."),
+ 'invalid': _("'%s' value must be either True or False."),
}
description = _("Boolean (Either True or False)")
@@ -646,7 +648,7 @@ class CommaSeparatedIntegerField(CharField):
def formfield(self, **kwargs):
defaults = {
'error_messages': {
- 'invalid': _(u'Enter only digits separated by commas.'),
+ 'invalid': _('Enter only digits separated by commas.'),
}
}
defaults.update(kwargs)
@@ -655,10 +657,10 @@ class CommaSeparatedIntegerField(CharField):
class DateField(Field):
empty_strings_allowed = False
default_error_messages = {
- 'invalid': _(u"'%s' value has an invalid date format. It must be "
- u"in YYYY-MM-DD format."),
- 'invalid_date': _(u"'%s' value has the correct format (YYYY-MM-DD) "
- u"but it is an invalid date."),
+ 'invalid': _("'%s' value has an invalid date format. It must be "
+ "in YYYY-MM-DD format."),
+ 'invalid_date': _("'%s' value has the correct format (YYYY-MM-DD) "
+ "but it is an invalid date."),
}
description = _("Date (without time)")
@@ -743,13 +745,13 @@ class DateField(Field):
class DateTimeField(DateField):
empty_strings_allowed = False
default_error_messages = {
- 'invalid': _(u"'%s' value has an invalid format. It must be in "
- u"YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."),
- 'invalid_date': _(u"'%s' value has the correct format "
- u"(YYYY-MM-DD) but it is an invalid date."),
- 'invalid_datetime': _(u"'%s' value has the correct format "
- u"(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) "
- u"but it is an invalid date/time."),
+ 'invalid': _("'%s' value has an invalid format. It must be in "
+ "YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."),
+ 'invalid_date': _("'%s' value has the correct format "
+ "(YYYY-MM-DD) but it is an invalid date."),
+ 'invalid_datetime': _("'%s' value has the correct format "
+ "(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) "
+ "but it is an invalid date/time."),
}
description = _("Date (with time)")
@@ -770,8 +772,8 @@ class DateTimeField(DateField):
# local time. This won't work during DST change, but we can't
# do much about it, so we let the exceptions percolate up the
# call stack.
- warnings.warn(u"DateTimeField received a naive datetime (%s)"
- u" while time zone support is active." % value,
+ warnings.warn("DateTimeField received a naive datetime (%s)"
+ " while time zone support is active." % value,
RuntimeWarning)
default_timezone = timezone.get_default_timezone()
value = timezone.make_aware(value, default_timezone)
@@ -815,8 +817,8 @@ class DateTimeField(DateField):
# For backwards compatibility, interpret naive datetimes in local
# time. This won't work during DST change, but we can't do much
# about it, so we let the exceptions percolate up the call stack.
- warnings.warn(u"DateTimeField received a naive datetime (%s)"
- u" while time zone support is active." % value,
+ warnings.warn("DateTimeField received a naive datetime (%s)"
+ " while time zone support is active." % value,
RuntimeWarning)
default_timezone = timezone.get_default_timezone()
value = timezone.make_aware(value, default_timezone)
@@ -840,7 +842,7 @@ class DateTimeField(DateField):
class DecimalField(Field):
empty_strings_allowed = False
default_error_messages = {
- 'invalid': _(u"'%s' value must be a decimal number."),
+ 'invalid': _("'%s' value must be a decimal number."),
}
description = _("Decimal number")
@@ -1195,10 +1197,10 @@ class TextField(Field):
class TimeField(Field):
empty_strings_allowed = False
default_error_messages = {
- 'invalid': _(u"'%s' value has an invalid format. It must be in "
- u"HH:MM[:ss[.uuuuuu]] format."),
- 'invalid_time': _(u"'%s' value has the correct format "
- u"(HH:MM[:ss[.uuuuuu]]) but it is an invalid time."),
+ 'invalid': _("'%s' value has an invalid format. It must be in "
+ "HH:MM[:ss[.uuuuuu]] format."),
+ 'invalid_time': _("'%s' value has the correct format "
+ "(HH:MM[:ss[.uuuuuu]]) but it is an invalid time."),
}
description = _("Time")
diff --git a/django/db/models/fields/files.py b/django/db/models/fields/files.py
index 34cf84dbc0a..e0c095974dc 100644
--- a/django/db/models/fields/files.py
+++ b/django/db/models/fields/files.py
@@ -207,7 +207,7 @@ class FileDescriptor(object):
class FileField(Field):
default_error_messages = {
- 'max_length': _(u'Filename is %(extra)d characters too long.')
+ 'max_length': _('Filename is %(extra)d characters too long.')
}
# The class to wrap instance attributes in. Accessing the file object off
diff --git a/django/forms/extras/widgets.py b/django/forms/extras/widgets.py
index 0a2223bc3f5..6c39b25a740 100644
--- a/django/forms/extras/widgets.py
+++ b/django/forms/extras/widgets.py
@@ -1,6 +1,7 @@
"""
Extra HTML Widget classes
"""
+from __future__ import unicode_literals
import datetime
import re
@@ -90,7 +91,7 @@ class SelectDateWidget(Widget):
output.append(month_html)
elif field == 'day':
output.append(day_html)
- return mark_safe(u'\n'.join(output))
+ return mark_safe('\n'.join(output))
def id_for_label(self, id_):
first_select = None
diff --git a/django/forms/fields.py b/django/forms/fields.py
index 3811510326b..4668eade974 100644
--- a/django/forms/fields.py
+++ b/django/forms/fields.py
@@ -2,7 +2,7 @@
Field classes.
"""
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import copy
import datetime
@@ -20,7 +20,7 @@ from django.forms.widgets import (TextInput, PasswordInput, HiddenInput,
NullBooleanSelect, SelectMultiple, DateInput, DateTimeInput, TimeInput,
SplitDateTimeWidget, SplitHiddenDateTimeWidget, FILE_INPUT_CONTRADICTION)
from django.utils import formats
-from django.utils.encoding import smart_unicode, smart_str, force_unicode
+from django.utils.encoding import smart_unicode, force_unicode
from django.utils.ipv6 import clean_ipv6_address
from django.utils.translation import ugettext_lazy as _
@@ -44,8 +44,8 @@ class Field(object):
hidden_widget = HiddenInput # Default widget to use when rendering this as "hidden".
default_validators = [] # Default set of validators
default_error_messages = {
- 'required': _(u'This field is required.'),
- 'invalid': _(u'Enter a valid value.'),
+ 'required': _('This field is required.'),
+ 'invalid': _('Enter a valid value.'),
}
# Tracks each time a Field instance is created. Used to retain order.
@@ -78,7 +78,7 @@ class Field(object):
self.required, self.label, self.initial = required, label, initial
self.show_hidden_initial = show_hidden_initial
if help_text is None:
- self.help_text = u''
+ self.help_text = ''
else:
self.help_text = smart_unicode(help_text)
widget = widget or self.widget
@@ -190,7 +190,7 @@ class CharField(Field):
def to_python(self, value):
"Returns a Unicode object."
if value in validators.EMPTY_VALUES:
- return u''
+ return ''
return smart_unicode(value)
def widget_attrs(self, widget):
@@ -202,9 +202,9 @@ class CharField(Field):
class IntegerField(Field):
default_error_messages = {
- 'invalid': _(u'Enter a whole number.'),
- 'max_value': _(u'Ensure this value is less than or equal to %(limit_value)s.'),
- 'min_value': _(u'Ensure this value is greater than or equal to %(limit_value)s.'),
+ 'invalid': _('Enter a whole number.'),
+ 'max_value': _('Ensure this value is less than or equal to %(limit_value)s.'),
+ 'min_value': _('Ensure this value is greater than or equal to %(limit_value)s.'),
}
def __init__(self, max_value=None, min_value=None, *args, **kwargs):
@@ -234,7 +234,7 @@ class IntegerField(Field):
class FloatField(IntegerField):
default_error_messages = {
- 'invalid': _(u'Enter a number.'),
+ 'invalid': _('Enter a number.'),
}
def to_python(self, value):
@@ -255,9 +255,9 @@ class FloatField(IntegerField):
class DecimalField(Field):
default_error_messages = {
- 'invalid': _(u'Enter a number.'),
- 'max_value': _(u'Ensure this value is less than or equal to %(limit_value)s.'),
- 'min_value': _(u'Ensure this value is greater than or equal to %(limit_value)s.'),
+ 'invalid': _('Enter a number.'),
+ 'max_value': _('Ensure this value is less than or equal to %(limit_value)s.'),
+ 'min_value': _('Ensure this value is greater than or equal to %(limit_value)s.'),
'max_digits': _('Ensure that there are no more than %s digits in total.'),
'max_decimal_places': _('Ensure that there are no more than %s decimal places.'),
'max_whole_digits': _('Ensure that there are no more than %s digits before the decimal point.')
@@ -284,7 +284,7 @@ class DecimalField(Field):
return None
if self.localize:
value = formats.sanitize_separators(value)
- value = smart_str(value).strip()
+ value = smart_unicode(value).strip()
try:
value = Decimal(value)
except DecimalException:
@@ -348,7 +348,7 @@ class DateField(BaseTemporalField):
widget = DateInput
input_formats = formats.get_format_lazy('DATE_INPUT_FORMATS')
default_error_messages = {
- 'invalid': _(u'Enter a valid date.'),
+ 'invalid': _('Enter a valid date.'),
}
def to_python(self, value):
@@ -371,7 +371,7 @@ class TimeField(BaseTemporalField):
widget = TimeInput
input_formats = formats.get_format_lazy('TIME_INPUT_FORMATS')
default_error_messages = {
- 'invalid': _(u'Enter a valid time.')
+ 'invalid': _('Enter a valid time.')
}
def to_python(self, value):
@@ -392,7 +392,7 @@ class DateTimeField(BaseTemporalField):
widget = DateTimeInput
input_formats = formats.get_format_lazy('DATETIME_INPUT_FORMATS')
default_error_messages = {
- 'invalid': _(u'Enter a valid date/time.'),
+ 'invalid': _('Enter a valid date/time.'),
}
def prepare_value(self, value):
@@ -457,7 +457,7 @@ class RegexField(CharField):
class EmailField(CharField):
default_error_messages = {
- 'invalid': _(u'Enter a valid e-mail address.'),
+ 'invalid': _('Enter a valid e-mail address.'),
}
default_validators = [validators.validate_email]
@@ -468,11 +468,11 @@ class EmailField(CharField):
class FileField(Field):
widget = ClearableFileInput
default_error_messages = {
- 'invalid': _(u"No file was submitted. Check the encoding type on the form."),
- 'missing': _(u"No file was submitted."),
- 'empty': _(u"The submitted file is empty."),
- 'max_length': _(u'Ensure this filename has at most %(max)d characters (it has %(length)d).'),
- 'contradiction': _(u'Please either submit a file or check the clear checkbox, not both.')
+ 'invalid': _("No file was submitted. Check the encoding type on the form."),
+ 'missing': _("No file was submitted."),
+ 'empty': _("The submitted file is empty."),
+ 'max_length': _('Ensure this filename has at most %(max)d characters (it has %(length)d).'),
+ 'contradiction': _('Please either submit a file or check the clear checkbox, not both.')
}
def __init__(self, *args, **kwargs):
@@ -527,7 +527,7 @@ class FileField(Field):
class ImageField(FileField):
default_error_messages = {
- 'invalid_image': _(u"Upload a valid image. The file you uploaded was either not an image or a corrupted image."),
+ 'invalid_image': _("Upload a valid image. The file you uploaded was either not an image or a corrupted image."),
}
def to_python(self, data):
@@ -583,7 +583,7 @@ class ImageField(FileField):
class URLField(CharField):
default_error_messages = {
- 'invalid': _(u'Enter a valid URL.'),
+ 'invalid': _('Enter a valid URL.'),
}
def __init__(self, max_length=None, min_length=None, *args, **kwargs):
@@ -669,7 +669,7 @@ class NullBooleanField(BooleanField):
class ChoiceField(Field):
widget = Select
default_error_messages = {
- 'invalid_choice': _(u'Select a valid choice. %(value)s is not one of the available choices.'),
+ 'invalid_choice': _('Select a valid choice. %(value)s is not one of the available choices.'),
}
def __init__(self, choices=(), required=True, widget=None, label=None,
@@ -697,7 +697,7 @@ class ChoiceField(Field):
def to_python(self, value):
"Returns a Unicode object."
if value in validators.EMPTY_VALUES:
- return u''
+ return ''
return smart_unicode(value)
def validate(self, value):
@@ -749,8 +749,8 @@ class MultipleChoiceField(ChoiceField):
hidden_widget = MultipleHiddenInput
widget = SelectMultiple
default_error_messages = {
- 'invalid_choice': _(u'Select a valid choice. %(value)s is not one of the available choices.'),
- 'invalid_list': _(u'Enter a list of values.'),
+ 'invalid_choice': _('Select a valid choice. %(value)s is not one of the available choices.'),
+ 'invalid_list': _('Enter a list of values.'),
}
def to_python(self, value):
@@ -838,7 +838,7 @@ class MultiValueField(Field):
You'll probably want to use this with MultiWidget.
"""
default_error_messages = {
- 'invalid': _(u'Enter a list of values.'),
+ 'invalid': _('Enter a list of values.'),
}
def __init__(self, fields=(), *args, **kwargs):
@@ -956,8 +956,8 @@ class SplitDateTimeField(MultiValueField):
widget = SplitDateTimeWidget
hidden_widget = SplitHiddenDateTimeWidget
default_error_messages = {
- 'invalid_date': _(u'Enter a valid date.'),
- 'invalid_time': _(u'Enter a valid time.'),
+ 'invalid_date': _('Enter a valid date.'),
+ 'invalid_time': _('Enter a valid time.'),
}
def __init__(self, input_date_formats=None, input_time_formats=None, *args, **kwargs):
@@ -990,7 +990,7 @@ class SplitDateTimeField(MultiValueField):
class IPAddressField(CharField):
default_error_messages = {
- 'invalid': _(u'Enter a valid IPv4 address.'),
+ 'invalid': _('Enter a valid IPv4 address.'),
}
default_validators = [validators.validate_ipv4_address]
@@ -1007,7 +1007,7 @@ class GenericIPAddressField(CharField):
def to_python(self, value):
if value in validators.EMPTY_VALUES:
- return u''
+ return ''
if value and ':' in value:
return clean_ipv6_address(value,
self.unpack_ipv4, self.error_messages['invalid'])
@@ -1016,7 +1016,7 @@ class GenericIPAddressField(CharField):
class SlugField(CharField):
default_error_messages = {
- 'invalid': _(u"Enter a valid 'slug' consisting of letters, numbers,"
- u" underscores or hyphens."),
+ 'invalid': _("Enter a valid 'slug' consisting of letters, numbers,"
+ " underscores or hyphens."),
}
default_validators = [validators.validate_slug]
diff --git a/django/forms/forms.py b/django/forms/forms.py
index 09663d173c3..22c3057c627 100644
--- a/django/forms/forms.py
+++ b/django/forms/forms.py
@@ -2,7 +2,7 @@
Form classes
"""
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import copy
@@ -23,7 +23,7 @@ NON_FIELD_ERRORS = '__all__'
def pretty_name(name):
"""Converts 'first_name' to 'First name'"""
if not name:
- return u''
+ return ''
return name.replace('_', ' ').capitalize()
def get_declared_fields(bases, attrs, with_base_fields=True):
@@ -136,7 +136,7 @@ class BaseForm(StrAndUnicode):
"""
Add a 'initial' prefix for checking dynamic initial values
"""
- return u'initial-%s' % self.add_prefix(field_name)
+ return 'initial-%s' % self.add_prefix(field_name)
def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row):
"Helper function for outputting HTML. Used by as_table(), as_ul(), as_p()."
@@ -149,7 +149,7 @@ class BaseForm(StrAndUnicode):
bf_errors = self.error_class([conditional_escape(error) for error in bf.errors]) # Escape and cache in local variable.
if bf.is_hidden:
if bf_errors:
- top_errors.extend([u'(Hidden field %s) %s' % (name, force_unicode(e)) for e in bf_errors])
+ top_errors.extend(['(Hidden field %s) %s' % (name, force_unicode(e)) for e in bf_errors])
hidden_fields.append(unicode(bf))
else:
# Create a 'class="..."' atribute if the row should have any
@@ -175,7 +175,7 @@ class BaseForm(StrAndUnicode):
if field.help_text:
help_text = help_text_html % force_unicode(field.help_text)
else:
- help_text = u''
+ help_text = ''
output.append(normal_row % {
'errors': force_unicode(bf_errors),
@@ -189,7 +189,7 @@ class BaseForm(StrAndUnicode):
output.insert(0, error_row % force_unicode(top_errors))
if hidden_fields: # Insert any hidden fields in the last row.
- str_hidden = u''.join(hidden_fields)
+ str_hidden = ''.join(hidden_fields)
if output:
last_row = output[-1]
# Chop off the trailing row_ender (e.g. '') and
@@ -208,33 +208,33 @@ class BaseForm(StrAndUnicode):
# If there aren't any rows in the output, just append the
# hidden fields.
output.append(str_hidden)
- return mark_safe(u'\n'.join(output))
+ return mark_safe('\n'.join(output))
def as_table(self):
"Returns this form rendered as HTML
',
+ row_ender = '',
+ help_text_html = ' %s',
errors_on_separate_row = False)
def as_ul(self):
"Returns this form rendered as HTML
s -- excluding the
."
return self._html_output(
- normal_row = u'
%(errors)s%(label)s %(field)s%(help_text)s
',
- error_row = u'
%s
',
+ normal_row = '
%(errors)s%(label)s %(field)s%(help_text)s
',
+ error_row = '
%s
',
row_ender = '',
- help_text_html = u' %s',
+ help_text_html = ' %s',
errors_on_separate_row = False)
def as_p(self):
"Returns this form rendered as HTML
s."
return self._html_output(
- normal_row = u'
%(label)s %(field)s%(help_text)s
',
- error_row = u'%s',
+ normal_row = '
%(label)s %(field)s%(help_text)s
',
+ error_row = '%s',
row_ender = '
',
- help_text_html = u' %s',
+ help_text_html = ' %s',
errors_on_separate_row = True)
def non_field_errors(self):
@@ -508,7 +508,7 @@ class BoundField(StrAndUnicode):
id_ = widget.attrs.get('id') or self.auto_id
if id_:
attrs = attrs and flatatt(attrs) or ''
- contents = u'' % (widget.id_for_label(id_), attrs, unicode(contents))
+ contents = '' % (widget.id_for_label(id_), attrs, unicode(contents))
return mark_safe(contents)
def css_classes(self, extra_classes=None):
diff --git a/django/forms/formsets.py b/django/forms/formsets.py
index 739a9d44e37..31ca088bdb3 100644
--- a/django/forms/formsets.py
+++ b/django/forms/formsets.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from django.core.exceptions import ValidationError
from django.forms import Form
@@ -314,11 +314,11 @@ class BaseFormSet(StrAndUnicode):
if self.can_order:
# Only pre-fill the ordering field for initial forms.
if index is not None and index < self.initial_form_count():
- form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_(u'Order'), initial=index+1, required=False)
+ form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_('Order'), initial=index+1, required=False)
else:
- form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_(u'Order'), required=False)
+ form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_('Order'), required=False)
if self.can_delete:
- form.fields[DELETION_FIELD_NAME] = BooleanField(label=_(u'Delete'), required=False)
+ form.fields[DELETION_FIELD_NAME] = BooleanField(label=_('Delete'), required=False)
def add_prefix(self, index):
return '%s-%s' % (self.prefix, index)
@@ -344,18 +344,18 @@ class BaseFormSet(StrAndUnicode):
# XXX: there is no semantic division between forms here, there
# probably should be. It might make sense to render each form as a
# table row with each field as a td.
- forms = u' '.join([form.as_table() for form in self])
- return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
+ forms = ' '.join([form.as_table() for form in self])
+ return mark_safe('\n'.join([unicode(self.management_form), forms]))
def as_p(self):
"Returns this formset rendered as HTML
s."
- forms = u' '.join([form.as_p() for form in self])
- return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
+ forms = ' '.join([form.as_p() for form in self])
+ return mark_safe('\n'.join([unicode(self.management_form), forms]))
def as_ul(self):
"Returns this formset rendered as HTML
s."
- forms = u' '.join([form.as_ul() for form in self])
- return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
+ forms = ' '.join([form.as_ul() for form in self])
+ return mark_safe('\n'.join([unicode(self.management_form), forms]))
def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
can_delete=False, max_num=None):
@@ -363,7 +363,7 @@ def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
attrs = {'form': form, 'extra': extra,
'can_order': can_order, 'can_delete': can_delete,
'max_num': max_num}
- return type(form.__name__ + 'FormSet', (formset,), attrs)
+ return type(form.__name__ + b'FormSet', (formset,), attrs)
def all_valid(formsets):
"""Returns true if every formset in formsets is valid."""
diff --git a/django/forms/models.py b/django/forms/models.py
index 5fcf9590eb6..26f869155b5 100644
--- a/django/forms/models.py
+++ b/django/forms/models.py
@@ -3,7 +3,7 @@ Helper functions for creating Form classes from Django models
and database field objects.
"""
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
from django.core.exceptions import ValidationError, NON_FIELD_ERRORS, FieldError
from django.core.validators import EMPTY_VALUES
@@ -846,7 +846,7 @@ class InlineForeignKeyField(Field):
given parent instance in an inline.
"""
default_error_messages = {
- 'invalid_choice': _(u'The inline foreign key did not match the parent instance primary key.'),
+ 'invalid_choice': _('The inline foreign key did not match the parent instance primary key.'),
}
def __init__(self, parent_instance, *args, **kwargs):
@@ -884,7 +884,7 @@ class ModelChoiceIterator(object):
def __iter__(self):
if self.field.empty_label is not None:
- yield (u"", self.field.empty_label)
+ yield ("", self.field.empty_label)
if self.field.cache_choices:
if self.field.choice_cache is None:
self.field.choice_cache = [
@@ -907,11 +907,11 @@ class ModelChoiceField(ChoiceField):
# This class is a subclass of ChoiceField for purity, but it doesn't
# actually use any of ChoiceField's implementation.
default_error_messages = {
- 'invalid_choice': _(u'Select a valid choice. That choice is not one of'
- u' the available choices.'),
+ 'invalid_choice': _('Select a valid choice. That choice is not one of'
+ ' the available choices.'),
}
- def __init__(self, queryset, empty_label=u"---------", cache_choices=False,
+ def __init__(self, queryset, empty_label="---------", cache_choices=False,
required=True, widget=None, label=None, initial=None,
help_text=None, to_field_name=None, *args, **kwargs):
if required and (initial is not None):
@@ -996,10 +996,10 @@ class ModelMultipleChoiceField(ModelChoiceField):
widget = SelectMultiple
hidden_widget = MultipleHiddenInput
default_error_messages = {
- 'list': _(u'Enter a list of values.'),
- 'invalid_choice': _(u'Select a valid choice. %s is not one of the'
- u' available choices.'),
- 'invalid_pk_value': _(u'"%s" is not a valid value for a primary key.')
+ 'list': _('Enter a list of values.'),
+ 'invalid_choice': _('Select a valid choice. %s is not one of the'
+ ' available choices.'),
+ 'invalid_pk_value': _('"%s" is not a valid value for a primary key.')
}
def __init__(self, queryset, cache_choices=False, required=True,
diff --git a/django/forms/util.py b/django/forms/util.py
index 66904425346..ca53b1f3d45 100644
--- a/django/forms/util.py
+++ b/django/forms/util.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
from django.conf import settings
from django.utils.html import conditional_escape
from django.utils.encoding import StrAndUnicode, force_unicode
@@ -16,7 +18,7 @@ def flatatt(attrs):
XML-style pairs. It is assumed that the keys do not need to be XML-escaped.
If the passed dictionary is empty, then return an empty string.
"""
- return u''.join([u' %s="%s"' % (k, conditional_escape(v)) for k, v in attrs.items()])
+ return ''.join([' %s="%s"' % (k, conditional_escape(v)) for k, v in attrs.items()])
class ErrorDict(dict, StrAndUnicode):
"""
@@ -28,13 +30,13 @@ class ErrorDict(dict, StrAndUnicode):
return self.as_ul()
def as_ul(self):
- if not self: return u''
- return mark_safe(u'
%s
'
- % ''.join([u'
%s%s
' % (k, conditional_escape(force_unicode(v)))
+ if not self: return ''
+ return mark_safe('
%s
'
+ % ''.join(['
%s%s
' % (k, conditional_escape(force_unicode(v)))
for k, v in self.items()]))
def as_text(self):
- return u'\n'.join([u'* %s\n%s' % (k, u'\n'.join([u' * %s' % force_unicode(i) for i in v])) for k, v in self.items()])
+ return '\n'.join(['* %s\n%s' % (k, '\n'.join([' * %s' % force_unicode(i) for i in v])) for k, v in self.items()])
class ErrorList(list, StrAndUnicode):
"""
@@ -44,13 +46,13 @@ class ErrorList(list, StrAndUnicode):
return self.as_ul()
def as_ul(self):
- if not self: return u''
- return mark_safe(u'
%s
'
- % ''.join([u'
%s
' % conditional_escape(force_unicode(e)) for e in self]))
+ if not self: return ''
+ return mark_safe('
%s
'
+ % ''.join(['
%s
' % conditional_escape(force_unicode(e)) for e in self]))
def as_text(self):
- if not self: return u''
- return u'\n'.join([u'* %s' % force_unicode(e) for e in self])
+ if not self: return ''
+ return '\n'.join(['* %s' % force_unicode(e) for e in self])
def __repr__(self):
return repr([force_unicode(e) for e in self])
diff --git a/django/forms/widgets.py b/django/forms/widgets.py
index 4813af69e96..2fddee918a2 100644
--- a/django/forms/widgets.py
+++ b/django/forms/widgets.py
@@ -2,7 +2,7 @@
HTML Widget classes
"""
-from __future__ import absolute_import
+from __future__ import absolute_import, unicode_literals
import copy
import datetime
@@ -50,10 +50,10 @@ class Media(StrAndUnicode):
return self.render()
def render(self):
- return mark_safe(u'\n'.join(chain(*[getattr(self, 'render_' + name)() for name in MEDIA_TYPES])))
+ return mark_safe('\n'.join(chain(*[getattr(self, 'render_' + name)() for name in MEDIA_TYPES])))
def render_js(self):
- return [u'' % self.absolute_path(path) for path in self._js]
+ return ['' % self.absolute_path(path) for path in self._js]
def render_css(self):
# To keep rendering order consistent, we can't just iterate over items().
@@ -61,12 +61,12 @@ class Media(StrAndUnicode):
media = self._css.keys()
media.sort()
return chain(*[
- [u'' % (self.absolute_path(path), medium)
+ ['' % (self.absolute_path(path), medium)
for path in self._css[medium]]
for medium in media])
def absolute_path(self, path, prefix=None):
- if path.startswith(u'http://') or path.startswith(u'https://') or path.startswith(u'/'):
+ if path.startswith(('http://', 'https://', '/')):
return path
if prefix is None:
if settings.STATIC_URL is None:
@@ -210,13 +210,13 @@ class Widget(object):
"""
# For purposes of seeing whether something has changed, None is
# the same as an empty string, if the data or inital value we get
- # is None, replace it w/ u''.
+ # is None, replace it w/ ''.
if data is None:
- data_value = u''
+ data_value = ''
else:
data_value = data
if initial is None:
- initial_value = u''
+ initial_value = ''
else:
initial_value = initial
if force_unicode(initial_value) != force_unicode(data_value):
@@ -254,7 +254,7 @@ class Input(Widget):
if value != '':
# Only add the 'value' attribute if a value is non-empty.
final_attrs['value'] = force_unicode(self._format_value(value))
- return mark_safe(u'' % flatatt(final_attrs))
+ return mark_safe('' % flatatt(final_attrs))
class TextInput(Input):
input_type = 'text'
@@ -295,8 +295,8 @@ class MultipleHiddenInput(HiddenInput):
# An ID attribute was given. Add a numeric index as a suffix
# so that the inputs don't all have the same ID attribute.
input_attrs['id'] = '%s_%s' % (id_, i)
- inputs.append(u'' % flatatt(input_attrs))
- return mark_safe(u'\n'.join(inputs))
+ inputs.append('' % flatatt(input_attrs))
+ return mark_safe('\n'.join(inputs))
def value_from_datadict(self, data, files, name):
if isinstance(data, (MultiValueDict, MergeDict)):
@@ -326,9 +326,9 @@ class ClearableFileInput(FileInput):
input_text = ugettext_lazy('Change')
clear_checkbox_label = ugettext_lazy('Clear')
- template_with_initial = u'%(initial_text)s: %(initial)s %(clear_template)s %(input_text)s: %(input)s'
+ template_with_initial = '%(initial_text)s: %(initial)s %(clear_template)s %(input_text)s: %(input)s'
- template_with_clear = u'%(clear)s '
+ template_with_clear = '%(clear)s '
def clear_checkbox_name(self, name):
"""
@@ -350,12 +350,12 @@ class ClearableFileInput(FileInput):
'clear_template': '',
'clear_checkbox_label': self.clear_checkbox_label,
}
- template = u'%(input)s'
+ template = '%(input)s'
substitutions['input'] = super(ClearableFileInput, self).render(name, value, attrs)
if value and hasattr(value, "url"):
template = self.template_with_initial
- substitutions['initial'] = (u'%s'
+ substitutions['initial'] = ('%s'
% (escape(value.url),
escape(force_unicode(value))))
if not self.is_required:
@@ -392,7 +392,7 @@ class Textarea(Widget):
def render(self, name, value, attrs=None):
if value is None: value = ''
final_attrs = self.build_attrs(attrs, name=name)
- return mark_safe(u'' % (flatatt(final_attrs),
+ return mark_safe('' % (flatatt(final_attrs),
conditional_escape(force_unicode(value))))
class DateInput(Input):
@@ -511,7 +511,7 @@ class CheckboxInput(Widget):
if not (value is True or value is False or value is None or value == ''):
# Only add the 'value' attribute if a value is non-empty.
final_attrs['value'] = force_unicode(value)
- return mark_safe(u'' % flatatt(final_attrs))
+ return mark_safe('' % flatatt(final_attrs))
def value_from_datadict(self, data, files, name):
if name not in data:
@@ -526,7 +526,7 @@ class CheckboxInput(Widget):
return value
def _has_changed(self, initial, data):
- # Sometimes data or initial could be None or u'' which should be the
+ # Sometimes data or initial could be None or '' which should be the
# same thing as False.
return bool(initial) != bool(data)
@@ -543,23 +543,23 @@ class Select(Widget):
def render(self, name, value, attrs=None, choices=()):
if value is None: value = ''
final_attrs = self.build_attrs(attrs, name=name)
- output = [u'')
+ return mark_safe('\n'.join(output))
def render_option(self, selected_choices, option_value, option_label):
option_value = force_unicode(option_value)
if option_value in selected_choices:
- selected_html = u' selected="selected"'
+ selected_html = ' selected="selected"'
if not self.allow_multiple_selected:
# Only allow for a single selection.
selected_choices.remove(option_value)
else:
selected_html = ''
- return u'' % (
+ return '' % (
escape(option_value), selected_html,
conditional_escape(force_unicode(option_label)))
@@ -569,37 +569,37 @@ class Select(Widget):
output = []
for option_value, option_label in chain(self.choices, choices):
if isinstance(option_label, (list, tuple)):
- output.append(u'')
else:
output.append(self.render_option(selected_choices, option_value, option_label))
- return u'\n'.join(output)
+ return '\n'.join(output)
class NullBooleanSelect(Select):
"""
A Select Widget intended to be used with NullBooleanField.
"""
def __init__(self, attrs=None):
- choices = ((u'1', ugettext_lazy('Unknown')),
- (u'2', ugettext_lazy('Yes')),
- (u'3', ugettext_lazy('No')))
+ choices = (('1', ugettext_lazy('Unknown')),
+ ('2', ugettext_lazy('Yes')),
+ ('3', ugettext_lazy('No')))
super(NullBooleanSelect, self).__init__(attrs, choices)
def render(self, name, value, attrs=None, choices=()):
try:
- value = {True: u'2', False: u'3', u'2': u'2', u'3': u'3'}[value]
+ value = {True: '2', False: '3', '2': '2', '3': '3'}[value]
except KeyError:
- value = u'1'
+ value = '1'
return super(NullBooleanSelect, self).render(name, value, attrs, choices)
def value_from_datadict(self, data, files, name):
value = data.get(name, None)
- return {u'2': True,
+ return {'2': True,
True: True,
'True': True,
- u'3': False,
+ '3': False,
'False': False,
False: False}.get(value, None)
@@ -618,12 +618,12 @@ class SelectMultiple(Select):
def render(self, name, value, attrs=None, choices=()):
if value is None: value = []
final_attrs = self.build_attrs(attrs, name=name)
- output = [u'' % flatatt(final_attrs)]
+ output = ['' % flatatt(final_attrs)]
options = self.render_options(choices, value)
if options:
output.append(options)
output.append('')
- return mark_safe(u'\n'.join(output))
+ return mark_safe('\n'.join(output))
def value_from_datadict(self, data, files, name):
if isinstance(data, (MultiValueDict, MergeDict)):
@@ -666,7 +666,7 @@ class RadioInput(SubWidget):
else:
label_for = ''
choice_label = conditional_escape(force_unicode(self.choice_label))
- return mark_safe(u'' % (label_for, self.tag(), choice_label))
+ return mark_safe('' % (label_for, self.tag(), choice_label))
def is_checked(self):
return self.value == self.choice_value
@@ -677,7 +677,7 @@ class RadioInput(SubWidget):
final_attrs = dict(self.attrs, type='radio', name=self.name, value=self.choice_value)
if self.is_checked():
final_attrs['checked'] = 'checked'
- return mark_safe(u'' % flatatt(final_attrs))
+ return mark_safe('' % flatatt(final_attrs))
class RadioFieldRenderer(StrAndUnicode):
"""
@@ -701,7 +701,7 @@ class RadioFieldRenderer(StrAndUnicode):
def render(self):
"""Outputs a